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
|
|---|---|---|---|---|---|
<form method="POST" action="/getsetting/{{blockId}}">
username: <input style='width:60px' type="text" name="username" value="{{username}}" autocomplete="off">
password: <input style='width:60px' type="password" name="password" value="{{password}}" autocomplete="off"><br />
custom: <input type="text" name="custom" value="{{custom}}" autocomplete="off"><br />
<input type="submit" value="save" name="change">
</form>
|
sibojia/ihomepage
|
1/app/templates/ServiceSetting.html
|
HTML
|
mit
| 420
|
define([ 'game/events', 'game/scene/scene', 'game/scene/camera' ], function (events, scene, camera) {
var container = document.getElementById('game-container');
var renderer = new THREE.WebGLRenderer( { clearColor: 0xefd1b5, clearAlpha: 1 } );
renderer.shadowMapEnabled = true;
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
events.on('game:resize', function () {
renderer.setSize(window.innerWidth, window.innerHeight);
});
events.on('game:render', function () {
renderer.render(scene, camera);
});
return renderer;
})
|
drborges/yo-bro
|
public/js/game/renderer.js
|
JavaScript
|
mit
| 603
|
//var word : string = "请输入想要输出的金字塔层数"
function pyramid(totalLine) {
for (var currentLine = 1; currentLine <= totalLine; currentLine++) {
var singleLineStr = "";
for (var spaceCount = totalLine - currentLine; spaceCount > 0; spaceCount--) {
singleLineStr += " ";
}
for (var starCount = 1; starCount <= (currentLine * 2) - 1; starCount++) {
singleLineStr += "*";
}
console.log(singleLineStr);
}
}
var num = process.argv[2];
if (!num) {
}
else {
pyramid(parseInt(num));
}
//# sourceMappingURL=main.js.map
|
QuietRain/HelloWorld
|
main.js
|
JavaScript
|
mit
| 611
|
package jaci.openrio.toast.lib.math;
/**
* A utility class to help with Math
*
* @author Jaci
*/
public class MathHelper {
/**
* Round a number (d) to the specified amount of decimal places (res)
*/
public static double round(double d, int res) {
int x = (int) Math.pow(10, res);
return Math.rint(d * x) / x;
}
}
|
m3rcuriel/ToastAPI
|
src/main/java/jaci/openrio/toast/lib/math/MathHelper.java
|
Java
|
mit
| 357
|
var _ = require('./');
// Browsers to run on Sauce Labs platforms
// (See https://saucelabs.com/platform/supported-browsers-devices for an
// up-to-date overview of supported versions of browsers and platforms.)
var sauceBrowsers = _.reduce([
['firefox', 'latest'],
['firefox', '60'],
['firefox', '40'],
['firefox', '11'],
// ['firefox', '4'], // failing due to "not enough arguments"
['chrome', 'latest'],
['chrome', '60'],
['chrome', '40'],
['chrome', '26'],
// latest Edge as well as pre-Blink versions
['microsoftedge', 'latest', 'Windows 10'],
['microsoftedge', '18', 'Windows 10'],
['microsoftedge', '13', 'Windows 10'],
['internet explorer', 'latest', 'Windows 10'],
['internet explorer', '10', 'Windows 8'],
['internet explorer', '9', 'Windows 7'],
// Older versions of IE no longer supported by Sauce Labs
['safari', 'latest', 'macOS 10.15'],
['safari', '12', 'macOS 10.14'],
['safari', '11', 'macOS 10.13'],
['safari', '8', 'OS X 10.10'],
], function(memo, platform) {
// internet explorer -> ie
var label = platform[0].split(' ');
if (label.length > 1) {
label = _.invoke(label, 'charAt', 0)
}
label = (label.join("") + '_v' + platform[1]).replace(' ', '_').toUpperCase();
memo[label] = _.pick({
'base': 'SauceLabs',
'browserName': platform[0],
'version': platform[1],
'platform': platform[2]
}, Boolean);
return memo;
}, {});
module.exports = function(config) {
if ( !process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY ) {
console.log('Sauce environments not set --- Skipping');
return process.exit(0);
}
config.set({
basePath: '',
frameworks: ['qunit'],
singleRun: true,
browserDisconnectTolerance: 5,
browserNoActivityTimeout: 240000,
// list of files / patterns to load in the browser
files: [
'test/vendor/qunit-extras.js',
'test/qunit-setup.js',
'underscore-umd.js',
'test/*.js'
],
// Number of sauce tests to start in parallel
concurrency: 9,
// test results reporter to use
reporters: ['dots', 'saucelabs'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
sauceLabs: {
build: 'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')',
startConnect: true,
tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER
},
captureTimeout: 120000,
customLaunchers: sauceBrowsers,
// Browsers to launch, commented out to prevent karma from starting
// too many concurrent browsers and timing sauce out.
browsers: _.keys(sauceBrowsers)
});
};
|
jashkenas/underscore
|
karma.conf-sauce.js
|
JavaScript
|
mit
| 2,624
|
module Fog
module AWS
class ELB < Fog::Service
extend Fog::AWS::CredentialFetcher::ServiceMethods
class DuplicatePolicyName < Fog::Errors::Error; end
class IdentifierTaken < Fog::Errors::Error; end
class InvalidInstance < Fog::Errors::Error; end
class InvalidConfigurationRequest < Fog::Errors::Error; end
class PolicyNotFound < Fog::Errors::Error; end
class PolicyTypeNotFound < Fog::Errors::Error; end
class Throttled < Fog::Errors::Error; end
class TooManyPolicies < Fog::Errors::Error; end
class ValidationError < Fog::Errors::Error; end
requires :aws_access_key_id, :aws_secret_access_key
recognizes :region, :host, :path, :port, :scheme, :persistent, :use_iam_profile, :aws_session_token, :aws_credentials_expire_at, :version, :instrumentor, :instrumentor_name
request_path 'fog/aws/requests/elb'
request :configure_health_check
request :create_app_cookie_stickiness_policy
request :create_lb_cookie_stickiness_policy
request :create_load_balancer
request :create_load_balancer_listeners
request :create_load_balancer_policy
request :delete_load_balancer
request :delete_load_balancer_listeners
request :delete_load_balancer_policy
request :deregister_instances_from_load_balancer
request :describe_instance_health
request :describe_load_balancers
request :describe_load_balancer_attributes
request :describe_load_balancer_policies
request :describe_load_balancer_policy_types
request :disable_availability_zones_for_load_balancer
request :enable_availability_zones_for_load_balancer
request :modify_load_balancer_attributes
request :register_instances_with_load_balancer
request :set_load_balancer_listener_ssl_certificate
request :set_load_balancer_policies_of_listener
request :attach_load_balancer_to_subnets
request :detach_load_balancer_from_subnets
request :apply_security_groups_to_load_balancer
request :set_load_balancer_policies_for_backend_server
request :add_tags
request :describe_tags
request :remove_tags
model_path 'fog/aws/models/elb'
model :load_balancer
collection :load_balancers
model :policy
collection :policies
model :listener
collection :listeners
model :backend_server_description
collection :backend_server_descriptions
class Mock
require 'fog/aws/elb/policy_types'
def self.data
@data ||= Hash.new do |hash, region|
owner_id = Fog::AWS::Mock.owner_id
hash[region] = Hash.new do |region_hash, key|
region_hash[key] = {
:owner_id => owner_id,
:load_balancers => {},
:policy_types => Fog::AWS::ELB::Mock::POLICY_TYPES
}
end
end
end
def self.dns_name(name, region)
"#{name}-#{Fog::Mock.random_hex(8)}.#{region}.elb.amazonaws.com"
end
def self.reset
@data = nil
end
attr_reader :region
def initialize(options={})
@use_iam_profile = options[:use_iam_profile]
@region = options[:region] || 'us-east-1'
setup_credentials(options)
Fog::AWS.validate_region!(@region)
end
def setup_credentials(options)
@aws_access_key_id = options[:aws_access_key_id]
@aws_secret_access_key = options[:aws_secret_access_key]
@signer = Fog::AWS::SignatureV4.new( @aws_access_key_id, @aws_secret_access_key,@region,'elasticloadbalancing')
end
def data
self.class.data[@region][@aws_access_key_id]
end
def reset_data
self.class.data[@region].delete(@aws_access_key_id)
end
end
class Real
include Fog::AWS::CredentialFetcher::ConnectionMethods
# Initialize connection to ELB
#
# ==== Notes
# options parameter must include values for :aws_access_key_id and
# :aws_secret_access_key in order to create a connection
#
# ==== Examples
# elb = ELB.new(
# :aws_access_key_id => your_aws_access_key_id,
# :aws_secret_access_key => your_aws_secret_access_key
# )
#
# ==== Parameters
# * options<~Hash> - config arguments for connection. Defaults to {}.
# * region<~String> - optional region to use. For instance, 'eu-west-1', 'us-east-1', etc.
#
# ==== Returns
# * ELB object with connection to AWS.
def initialize(options={})
@use_iam_profile = options[:use_iam_profile]
@connection_options = options[:connection_options] || {}
@instrumentor = options[:instrumentor]
@instrumentor_name = options[:instrumentor_name] || 'fog.aws.elb'
options[:region] ||= 'us-east-1'
@region = options[:region]
@host = options[:host] || "elasticloadbalancing.#{@region}.amazonaws.com"
@path = options[:path] || '/'
@persistent = options[:persistent] || false
@port = options[:port] || 443
@scheme = options[:scheme] || 'https'
@connection = Fog::XML::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options)
@version ||= options[:version] || '2012-06-01'
setup_credentials(options)
end
attr_reader :region
def reload
@connection.reset
end
private
def setup_credentials(options={})
@aws_access_key_id = options[:aws_access_key_id]
@aws_secret_access_key = options[:aws_secret_access_key]
@aws_session_token = options[:aws_session_token]
@aws_credentials_expire_at = options[:aws_credentials_expire_at]
@signer = Fog::AWS::SignatureV4.new(@aws_access_key_id, @aws_secret_access_key, @region, 'elasticloadbalancing')
end
def request(params)
refresh_credentials_if_expired
idempotent = params.delete(:idempotent)
parser = params.delete(:parser)
body, headers = Fog::AWS.signed_params_v4(
params,
{ 'Content-Type' => 'application/x-www-form-urlencoded' },
{
:aws_session_token => @aws_session_token,
:signer => @signer,
:host => @host,
:path => @path,
:port => @port,
:version => @version,
:method => 'POST'
}
)
if @instrumentor
@instrumentor.instrument("#{@instrumentor_name}.request", params) do
_request(body, headers, idempotent, parser)
end
else
_request(body, headers, idempotent, parser)
end
end
def _request(body, headers, idempotent, parser)
@connection.request({
:body => body,
:expects => 200,
:headers => headers,
:idempotent => idempotent,
:method => 'POST',
:parser => parser
})
rescue Excon::Errors::HTTPStatusError => error
match = Fog::AWS::Errors.match_error(error)
raise if match.empty?
raise case match[:code]
when 'CertificateNotFound'
Fog::AWS::IAM::NotFound.slurp(error, match[:message])
when 'DuplicateLoadBalancerName'
Fog::AWS::ELB::IdentifierTaken.slurp(error, match[:message])
when 'DuplicatePolicyName'
Fog::AWS::ELB::DuplicatePolicyName.slurp(error, match[:message])
when 'InvalidInstance'
Fog::AWS::ELB::InvalidInstance.slurp(error, match[:message])
when 'InvalidConfigurationRequest'
# when do they fucking use this shit?
Fog::AWS::ELB::InvalidConfigurationRequest.slurp(error, match[:message])
when 'LoadBalancerNotFound'
Fog::AWS::ELB::NotFound.slurp(error, match[:message])
when 'PolicyNotFound'
Fog::AWS::ELB::PolicyNotFound.slurp(error, match[:message])
when 'PolicyTypeNotFound'
Fog::AWS::ELB::PolicyTypeNotFound.slurp(error, match[:message])
when 'Throttling'
Fog::AWS::ELB::Throttled.slurp(error, match[:message])
when 'TooManyPolicies'
Fog::AWS::ELB::TooManyPolicies.slurp(error, match[:message])
when 'ValidationError'
Fog::AWS::ELB::ValidationError.slurp(error, match[:message])
else
Fog::AWS::ELB::Error.slurp(error, "#{match[:code]} => #{match[:message]}")
end
end
end
end
end
end
|
fog/fog-aws
|
lib/fog/aws/elb.rb
|
Ruby
|
mit
| 9,277
|
# gdown
[](https://www.npmjs.com/package/gdown)
github项目下载工具,支持多项目单文件下载以及多级目录下载。
# Installation
$ npm install gdown -g
# Usage
$ gdown huanz/gulp-devserver/lib
// or dirs
$ gdown huanz/gulp-devserver/lib huanz/seajs-cache
// or dirs and files
$ gdown huanz/gulp-devserver/lib huanz/seajs-cache huanz/gdown/bin/gdown huanz/urlParse/urlparse.js
|
huanz/gdown
|
README.md
|
Markdown
|
mit
| 447
|
import { LocationDetecter } from "./infra"
import { ConvertLocationResult } from "./data"
export function backgroundLocationDetecter<T>(
result: ConvertLocationResult<T>,
): LocationDetecter<T> {
return () => result
}
export type LocationSearchParam = [string, string]
export function encodeLocationSearchQuery(params: LocationSearchParam[]): string {
return params
.map((param) => {
const [key, value] = param
return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
})
.join("&")
}
|
getto-systems/getto-css
|
lib/z_vendor/getto-application/location/helper.ts
|
TypeScript
|
mit
| 555
|
---
layout: page
title: Beltran Exquisite Air Trade Fair
date: 2016-05-24
author: Kelly Bond
tags: weekly links, java
status: published
summary: Integer interdum justo quis nulla vehicula vestibulum. Ut.
banner: images/banner/people.jpg
booking:
startDate: 05/26/2016
endDate: 05/28/2016
ctyhocn: CHADNHX
groupCode: BEATF
published: true
---
Nunc ullamcorper condimentum odio, eget suscipit velit euismod vitae. Sed maximus pulvinar dignissim. Nulla sed magna nec urna hendrerit scelerisque eu ac est. In velit lectus, suscipit et odio vel, feugiat pharetra dolor. Donec risus ante, varius ultricies tortor id, dignissim lacinia nibh. Curabitur aliquam fringilla velit. Pellentesque vitae venenatis est, et ultrices ex. Nam eget finibus velit. Fusce ut posuere tellus. Nullam eget mollis quam, eu lacinia arcu. Vestibulum nulla ipsum, luctus vitae ultrices sit amet, faucibus convallis nisl. Etiam tristique nec mi sodales accumsan. Curabitur varius justo magna, eu rutrum enim scelerisque in. Ut neque lectus, imperdiet ut urna aliquam, ornare luctus nisl.
Donec et ligula ac erat gravida congue ac non ex. Duis pharetra molestie purus, ut faucibus sapien posuere et. Vestibulum auctor lacus nec nulla blandit, ac condimentum lorem sagittis. Praesent non libero enim. Pellentesque non dapibus sapien, ac euismod tellus. Maecenas vitae interdum enim. Duis non purus eget leo dictum euismod nec sit amet velit. Aliquam non diam elit. Quisque lobortis dapibus quam, ut pretium magna imperdiet sit amet. Vivamus condimentum aliquam urna. Praesent condimentum malesuada leo id hendrerit.
* Vivamus vel nunc at arcu mattis feugiat ac eu tortor
* Praesent et magna et massa finibus volutpat quis nec nunc.
Nulla a euismod mi. Duis placerat lectus ut accumsan consectetur. Nulla imperdiet justo eget faucibus finibus. Suspendisse cursus tincidunt condimentum. Morbi euismod est massa, sed viverra risus molestie et. Pellentesque ornare dictum ex in auctor. Ut varius at massa eu tincidunt. Nam lobortis sodales eros ac viverra.
Pellentesque sit amet dolor tempus leo volutpat blandit eu vitae purus. In feugiat justo et malesuada tincidunt. Aliquam feugiat ultrices nunc, eget aliquam risus. Duis sollicitudin felis nunc, quis iaculis neque aliquet et. Ut nibh risus, rutrum id rutrum eget, placerat at velit. Suspendisse ac tortor justo. Morbi hendrerit nisl sit amet rhoncus scelerisque.
|
KlishGroup/prose-pogs
|
pogs/C/CHADNHX/BEATF/index.md
|
Markdown
|
mit
| 2,393
|
#ifndef ESPASYNCUDP_H
#define ESPASYNCUDP_H
#include "IPAddress.h"
#include "Print.h"
#include <functional>
class AsyncUDP;
class AsyncUDPPacket;
class AsyncUDPMessage;
struct udp_pcb;
struct pbuf;
struct ip_addr;
typedef struct ip_addr ip_addr_t;
class AsyncUDPMessage : public Print
{
protected:
uint8_t *_buffer;
size_t _index;
size_t _size;
public:
AsyncUDPMessage(size_t size=1460);
virtual ~AsyncUDPMessage();
size_t write(const uint8_t *data, size_t len);
size_t write(uint8_t data);
size_t space();
uint8_t * data();
size_t length();
void flush();
operator bool()
{
return _buffer != NULL;
}
};
class AsyncUDPPacket : public Print
{
protected:
AsyncUDP *_udp;
ip_addr_t *_localIp;
uint16_t _localPort;
ip_addr_t *_remoteIp;
uint16_t _remotePort;
uint8_t *_data;
size_t _len;
public:
AsyncUDPPacket(AsyncUDP *udp, ip_addr_t *localIp, uint16_t localPort, ip_addr_t *remoteIp, uint16_t remotePort, uint8_t *data, size_t len);
virtual ~AsyncUDPPacket();
uint8_t * data();
size_t length();
bool isBroadcast();
bool isMulticast();
IPAddress localIP();
uint16_t localPort();
IPAddress remoteIP();
uint16_t remotePort();
size_t send(AsyncUDPMessage &message);
size_t write(const uint8_t *data, size_t len);
size_t write(uint8_t data);
};
typedef std::function<void(AsyncUDPPacket& packet)> AuPacketHandlerFunction;
typedef std::function<void(void * arg, AsyncUDPPacket& packet)> AuPacketHandlerFunctionWithArg;
class AsyncUDP : public Print
{
protected:
udp_pcb *_pcb;
bool _connected;
AuPacketHandlerFunction _handler;
void _recv(udp_pcb *upcb, pbuf *pb, ip_addr_t *addr, uint16_t port);
static void _s_recv(void *arg, udp_pcb *upcb, pbuf *p, struct ip_addr *addr, uint16_t port);
public:
AsyncUDP();
virtual ~AsyncUDP();
void onPacket(AuPacketHandlerFunctionWithArg cb, void * arg=NULL);
void onPacket(AuPacketHandlerFunction cb);
bool listen(ip_addr_t *addr, uint16_t port);
bool listen(const IPAddress addr, uint16_t port);
bool listen(uint16_t port);
bool listenMulticast(ip_addr_t *addr, uint16_t port, uint8_t ttl=1);
bool listenMulticast(const IPAddress addr, uint16_t port, uint8_t ttl=1);
bool connect(ip_addr_t *addr, uint16_t port);
bool connect(const IPAddress addr, uint16_t port);
void close();
size_t writeTo(const uint8_t *data, size_t len, ip_addr_t *addr, uint16_t port);
size_t writeTo(const uint8_t *data, size_t len, const IPAddress addr, uint16_t port);
size_t write(const uint8_t *data, size_t len);
size_t write(uint8_t data);
size_t broadcastTo(uint8_t *data, size_t len, uint16_t port);
size_t broadcastTo(const char * data, uint16_t port);
size_t broadcast(uint8_t *data, size_t len);
size_t broadcast(const char * data);
size_t sendTo(AsyncUDPMessage &message, ip_addr_t *addr, uint16_t port);
size_t sendTo(AsyncUDPMessage &message, const IPAddress addr, uint16_t port);
size_t send(AsyncUDPMessage &message);
size_t broadcastTo(AsyncUDPMessage &message, uint16_t port);
size_t broadcast(AsyncUDPMessage &message);
bool connected();
operator bool();
};
#endif
|
kuzyasun/AquaSmart
|
esp8266_app/lib/ESPAsyncUDP/ESPAsyncUDP.h
|
C
|
mit
| 3,285
|
// 23: class - accessors
// To do: make all tests pass, leave the assert lines unchanged!
// Follow the hints of the failure messages!
describe('Class accessors (getter and setter)', () => {
it('a getter is defined like a method prefixed with `get`', () => {
class MyAccount {
//// get money() { return Infinity; }
get balance() { return Infinity; }
}
assert.equal(new MyAccount().balance, Infinity);
});
it('a setter has the prefix `set`', () => {
class MyAccount {
get balance() { return this.amount; }
set balance(amount) { this.amount = amount; }
}
const account = new MyAccount();
//// account.balance = 42;
account.balance = 23;
assert.equal(account.balance, 23);
});
describe('dynamic accessors', () => {
it('a dynamic getter name is enclosed in `[]`', function() {
//// const balance = 'yourMoney';
const getterName = 'yourMoney';
class YourAccount {
get [getterName]() { return -Infinity; }
}
assert.equal(new YourAccount().yourMoney, -Infinity);
});
it('a dynamic setter name as well', function() {
const propertyName = 'balance';
class MyAccount {
get [propertyName]() { return this.amount; }
//// set propertyName(amount) { this.amount = 23; }
set [propertyName](amount) { this.amount = 23; }
}
const account = new MyAccount();
account.balance = 42;
assert.equal(account.balance, 23);
});
});
});
|
tddbin/katas
|
katas/es6/language/class/accessors.js
|
JavaScript
|
mit
| 1,499
|
<!DOCTYPE HTML>
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (11.0.10) on Thu Apr 15 10:34:57 CEST 2021 -->
<title>Uses of Class com.wrapper.spotify.requests.data.player.SkipUsersPlaybackToPreviousTrackRequest (Spotify Web API Java Client 6.5.3 API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2021-04-15">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../../../jquery/jquery-ui.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
<script type="text/javascript" src="../../../../../../../jquery/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="../../../../../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script>
<!--[if IE]>
<script type="text/javascript" src="../../../../../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script>
<![endif]-->
<script type="text/javascript" src="../../../../../../../jquery/jquery-3.5.1.js"></script>
<script type="text/javascript" src="../../../../../../../jquery/jquery-ui.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.wrapper.spotify.requests.data.player.SkipUsersPlaybackToPreviousTrackRequest (Spotify Web API Java Client 6.5.3 API)";
}
}
catch(err) {
}
//-->
var pathtoroot = "../../../../../../../";
var useModuleDirectories = true;
loadScripts(document, 'script');</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<header role="banner">
<nav role="navigation">
<div class="fixedNav">
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a id="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a id="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../index.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../SkipUsersPlaybackToPreviousTrackRequest.html" title="class in com.wrapper.spotify.requests.data.player">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses.html">All Classes</a></li>
</ul>
<ul class="navListSearch">
<li><label for="search">SEARCH:</label>
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">
</li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<a id="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
</div>
<div class="navPadding"> </div>
<script type="text/javascript"><!--
$('.navPadding').css('padding-top', $('.fixedNav').css("height"));
//-->
</script>
</nav>
</header>
<main role="main">
<div class="header">
<h2 title="Uses of Class com.wrapper.spotify.requests.data.player.SkipUsersPlaybackToPreviousTrackRequest" class="title">Uses of Class<br>com.wrapper.spotify.requests.data.player.SkipUsersPlaybackToPreviousTrackRequest</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary">
<caption><span>Packages that use <a href="../SkipUsersPlaybackToPreviousTrackRequest.html" title="class in com.wrapper.spotify.requests.data.player">SkipUsersPlaybackToPreviousTrackRequest</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<th class="colFirst" scope="row"><a href="#com.wrapper.spotify.requests.data.player">com.wrapper.spotify.requests.data.player</a></th>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList">
<section role="region"><a id="com.wrapper.spotify.requests.data.player">
<!-- -->
</a>
<h3>Uses of <a href="../SkipUsersPlaybackToPreviousTrackRequest.html" title="class in com.wrapper.spotify.requests.data.player">SkipUsersPlaybackToPreviousTrackRequest</a> in <a href="../package-summary.html">com.wrapper.spotify.requests.data.player</a></h3>
<table class="useSummary">
<caption><span>Methods in <a href="../package-summary.html">com.wrapper.spotify.requests.data.player</a> that return <a href="../SkipUsersPlaybackToPreviousTrackRequest.html" title="class in com.wrapper.spotify.requests.data.player">SkipUsersPlaybackToPreviousTrackRequest</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colSecond" scope="col">Method</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../SkipUsersPlaybackToPreviousTrackRequest.html" title="class in com.wrapper.spotify.requests.data.player">SkipUsersPlaybackToPreviousTrackRequest</a></code></td>
<th class="colSecond" scope="row"><span class="typeNameLabel">SkipUsersPlaybackToPreviousTrackRequest.Builder.</span><code><span class="memberNameLink"><a href="../SkipUsersPlaybackToPreviousTrackRequest.Builder.html#build()">build</a></span>()</code></th>
<td class="colLast">
<div class="block">The request build method.</div>
</td>
</tr>
</tbody>
</table>
</section>
</li>
</ul>
</li>
</ul>
</div>
</main>
<footer role="contentinfo">
<nav role="navigation">
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a id="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a id="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../index.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../SkipUsersPlaybackToPreviousTrackRequest.html" title="class in com.wrapper.spotify.requests.data.player">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<a id="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</nav>
<p class="legalCopy"><small>Copyright © 2021. All rights reserved.</small></p>
</footer>
</body>
</html>
|
thelinmichael/spotify-web-api-java
|
docs/com/wrapper/spotify/requests/data/player/class-use/SkipUsersPlaybackToPreviousTrackRequest.html
|
HTML
|
mit
| 7,778
|
module Ludicrousby
VERSION = '1.1.0'
end
|
Chiether/ludicrousby
|
lib/ludicrousby/version.rb
|
Ruby
|
mit
| 43
|
#
#
#
from __future__ import absolute_import, division, print_function, \
unicode_literals
from mock import Mock, call
from os.path import dirname, join
from requests import HTTPError
from requests_mock import ANY, mock as requests_mock
from unittest import TestCase
from octodns.record import Record
from octodns.provider.dnsimple import DnsimpleClientNotFound, DnsimpleProvider
from octodns.provider.yaml import YamlProvider
from octodns.zone import Zone
class TestDnsimpleProvider(TestCase):
expected = Zone('unit.tests.', [])
source = YamlProvider('test', join(dirname(__file__), 'config'))
source.populate(expected)
# Our test suite differs a bit, add our NS and remove the simple one
expected.add_record(Record.new(expected, 'under', {
'ttl': 3600,
'type': 'NS',
'values': [
'ns1.unit.tests.',
'ns2.unit.tests.',
]
}))
for record in list(expected.records):
if record.name == 'sub' and record._type == 'NS':
expected._remove_record(record)
break
def test_populate(self):
provider = DnsimpleProvider('test', 'token', 42)
# Bad auth
with requests_mock() as mock:
mock.get(ANY, status_code=401,
text='{"message": "Authentication failed"}')
with self.assertRaises(Exception) as ctx:
zone = Zone('unit.tests.', [])
provider.populate(zone)
self.assertEquals('Unauthorized', ctx.exception.message)
# General error
with requests_mock() as mock:
mock.get(ANY, status_code=502, text='Things caught fire')
with self.assertRaises(HTTPError) as ctx:
zone = Zone('unit.tests.', [])
provider.populate(zone)
self.assertEquals(502, ctx.exception.response.status_code)
# Non-existant zone doesn't populate anything
with requests_mock() as mock:
mock.get(ANY, status_code=404,
text='{"message": "Domain `foo.bar` not found"}')
zone = Zone('unit.tests.', [])
provider.populate(zone)
self.assertEquals(set(), zone.records)
# No diffs == no changes
with requests_mock() as mock:
base = 'https://api.dnsimple.com/v2/42/zones/unit.tests/' \
'records?page='
with open('tests/fixtures/dnsimple-page-1.json') as fh:
mock.get('{}{}'.format(base, 1), text=fh.read())
with open('tests/fixtures/dnsimple-page-2.json') as fh:
mock.get('{}{}'.format(base, 2), text=fh.read())
zone = Zone('unit.tests.', [])
provider.populate(zone)
self.assertEquals(14, len(zone.records))
changes = self.expected.changes(zone, provider)
self.assertEquals(0, len(changes))
# 2nd populate makes no network calls/all from cache
again = Zone('unit.tests.', [])
provider.populate(again)
self.assertEquals(14, len(again.records))
# bust the cache
del provider._zone_records[zone.name]
# test handling of invalid content
with requests_mock() as mock:
with open('tests/fixtures/dnsimple-invalid-content.json') as fh:
mock.get(ANY, text=fh.read())
zone = Zone('unit.tests.', [])
provider.populate(zone)
self.assertEquals(set([
Record.new(zone, '', {
'ttl': 3600,
'type': 'SSHFP',
'values': []
}),
Record.new(zone, '_srv._tcp', {
'ttl': 600,
'type': 'SRV',
'values': []
}),
Record.new(zone, 'naptr', {
'ttl': 600,
'type': 'NAPTR',
'values': []
}),
]), zone.records)
def test_apply(self):
provider = DnsimpleProvider('test', 'token', 42)
resp = Mock()
resp.json = Mock()
provider._client._request = Mock(return_value=resp)
# non-existant domain, create everything
resp.json.side_effect = [
DnsimpleClientNotFound, # no zone in populate
DnsimpleClientNotFound, # no domain during apply
]
plan = provider.plan(self.expected)
# No root NS, no ignored
n = len(self.expected.records) - 2
self.assertEquals(n, len(plan.changes))
self.assertEquals(n, provider.apply(plan))
provider._client._request.assert_has_calls([
# created the domain
call('POST', '/domains', data={'name': 'unit.tests'}),
# created at least one of the record with expected data
call('POST', '/zones/unit.tests/records', data={
'content': '20 30 foo-1.unit.tests.',
'priority': 10,
'type': 'SRV',
'name': '_srv._tcp',
'ttl': 600
}),
])
# expected number of total calls
self.assertEquals(26, provider._client._request.call_count)
provider._client._request.reset_mock()
# delete 1 and update 1
provider._client.records = Mock(return_value=[
{
'id': 11189897,
'name': 'www',
'content': '1.2.3.4',
'ttl': 300,
'type': 'A',
},
{
'id': 11189898,
'name': 'www',
'content': '2.2.3.4',
'ttl': 300,
'type': 'A',
},
{
'id': 11189899,
'name': 'ttl',
'content': '3.2.3.4',
'ttl': 600,
'type': 'A',
}
])
# Domain exists, we don't care about return
resp.json.side_effect = ['{}']
wanted = Zone('unit.tests.', [])
wanted.add_record(Record.new(wanted, 'ttl', {
'ttl': 300,
'type': 'A',
'value': '3.2.3.4'
}))
plan = provider.plan(wanted)
self.assertEquals(2, len(plan.changes))
self.assertEquals(2, provider.apply(plan))
# recreate for update, and deletes for the 2 parts of the other
provider._client._request.assert_has_calls([
call('POST', '/zones/unit.tests/records', data={
'content': '3.2.3.4',
'type': 'A',
'name': 'ttl',
'ttl': 300
}),
call('DELETE', '/zones/unit.tests/records/11189899'),
call('DELETE', '/zones/unit.tests/records/11189897'),
call('DELETE', '/zones/unit.tests/records/11189898')
], any_order=True)
|
h-hwang/octodns
|
tests/test_octodns_provider_dnsimple.py
|
Python
|
mit
| 6,915
|
import 'antd-mobile/lib/swipe-action/style/index';
|
joe-sky/flarej
|
src/components/antd-mobile/swipeAction/component/style/index.js
|
JavaScript
|
mit
| 50
|
// Generated by : ImageConverter BW Online
// Generated from : oshw_logo.png
// Time generated : Thu, 11 Aug 11 20:28:44 +0200 (Server timezone: CET)
// Image Size : 56x48 pixels
// Memory usage : 336 bytes
#include <avr/pgmspace.h>
uint8_t oshw_logo[] PROGMEM={
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xC0, 0x80, 0x00, // 0x0010 (16) pixels
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFE, 0x06, 0x06, 0x06, 0x06, 0x06, 0xFE, // 0x0020 (32) pixels
0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xC0, 0xC0, 0x80, 0x00, 0x00, // 0x0030 (48) pixels
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 0x0040 (64) pixels
0x0C, 0x1E, 0x7F, 0xE3, 0xC1, 0x81, 0x01, 0x03, 0x07, 0x0E, 0x0C, 0x0E, 0x06, 0x07, 0x03, 0x03, // 0x0050 (80) pixels
0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x03, 0x07, 0x06, 0x06, 0x0E, 0x0E, 0x07, // 0x0060 (96) pixels
0x03, 0x03, 0x01, 0x80, 0xE1, 0xF3, 0x3F, 0x1E, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 0x0070 (112) pixels
0x00, 0x00, 0x00, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xF8, 0x7E, 0x0F, 0x03, 0x00, 0x00, // 0x0080 (128) pixels
0x00, 0x00, 0x00, 0x00, 0x80, 0xE0, 0xF0, 0x38, 0x18, 0x1C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1C, // 0x0090 (144) pixels
0x18, 0x38, 0xF0, 0xE0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x0F, 0x7E, 0x78, 0x60, // 0x00A0 (160) pixels
0xE0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x7F, 0x60, 0x60, 0x60, // 0x00B0 (176) pixels
0x60, 0xE0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0xFF, 0xC0, 0x80, // 0x00C0 (192) pixels
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xE0, 0xFF, 0x3F, 0x00, 0x00, 0x00, // 0x00D0 (208) pixels
0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xE0, 0x60, 0x70, 0x70, 0x30, 0x30, 0x3F, 0x3F, 0x00, 0x00, // 0x00E0 (224) pixels
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x87, 0xFF, 0xFC, 0x30, 0x00, 0x00, // 0x00F0 (240) pixels
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC1, 0xFB, 0x7F, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, // 0x0100 (256) pixels
0x3F, 0xFB, 0xE1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0xFF, 0xE3, 0x80, // 0x0110 (272) pixels
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 0x0120 (288) pixels
0x0E, 0x1F, 0x3B, 0x71, 0x60, 0x70, 0x30, 0x38, 0x1C, 0x0C, 0x0C, 0x1C, 0x18, 0x1F, 0x0F, 0x01, // 0x0130 (304) pixels
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x1F, 0x1C, 0x1C, 0x0E, 0x06, // 0x0140 (320) pixels
0x0E, 0x1C, 0x38, 0x70, 0x60, 0x70, 0x3B, 0x1F, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 0x0150 (336) pixels
};
|
herbstmensch/BrewDuino
|
libraries/LCD5110_Basic/examples/LCD5110_Bitmap/oshw_logo.c
|
C
|
mit
| 2,813
|
/** @flow */
import type { t } from '../types'
/**
*
* @param sources
* @param target
*/
export function applyAverage (sources: t[], target: t): void {
const source = sources[0]
if (!source || sources.length === 0) return
if (sources.length === 1) {
target.data.set(source.data, 0)
return
}
const quantity = sources.length
const width = source.width
const height = source.height
const pointsLength = width * height
let matrixIndex
let pointIndex
let currentSum
for (pointIndex = 0; pointIndex < pointsLength; pointIndex++) {
currentSum = 0
for (matrixIndex = 0; matrixIndex < quantity; matrixIndex++) {
currentSum += sources[matrixIndex].data[pointIndex]
}
target.data[pointIndex] = currentSum / quantity
}
}
|
MaverickBySigma/gimagedata
|
src/mutations/applyAverage.js
|
JavaScript
|
mit
| 774
|
---
layout: post
title: "How to Calculate Mortgage Payment Schedule in R"
date: 2018-11-20
comments: true
categories: r
keywords: "R, financial calculator, mortgage calculator, amortization schedule, amortization schedule calculator, mortgage payment schedule, repayment, principal, interest, outstanding principal, balance, mortgage loan amount, APR, interest rate, housing price, down payment"
published: true
share: true
ads: true
---
Suppose you want to buy a $350,000 house, and you plan to get a 30-year fixed mortage (interest rate 4.87%) with a 20% down payment. What's your monthly repayment? How much of it will go towards interest and how much will go towards the principal?
Notice the mortgage amount you are borrowing is $280,000 (80% of the house price), and there're 360 monthly payments you need to make.
The calculation of the monthly payment involves 2 steps conceptually:
1. Calculate the simple monthly rate by dividing the interest rate by 12. This is because the quoted interest rate is (almost always) an annual rate (APR).
2. The mortgage amount, monthly payment amount and monthly rate are related by the [present value formula for annuities](https://en.wikipedia.org/wiki/Annuity). Knowing any two of them, we can easily solve for the 3rd one.
These 2 steps are carried out in the following R code block.
{% highlight r %}
# calculate simple monthly rate
monthly_rate = 4.87 / 100 / 12
# calculate (constant) contractual monthly payment amount
# derived from the present value formula for annuities
r = (1 + monthly_rate) ^ 360 - 1
payment = 280000 * monthly_rate * (r + 1) / r
{% endhighlight %}
So every month, you're expected to make a payment of \$1480.93 back to your lender. The interest is calculated by multiplying the outstanding principal at the beginning of the month by the monthly rate, and the reducible amount of principal is obtained by subtracting interest from the monthly payment \$1480.93. The following code block calculates the payment schedule (also called amortization schedule) for the first 12 payment months.
{% highlight r %}
payment_months = 12
# initialize output variables
interest = principal = balance = vector("numeric", payment_months)
# calc amortization schedule
outstanding_principal = 280000
for (i in 1:payment_months) {
intr = outstanding_principal * monthly_rate # interest to be paid
prnp = payment - intr # principal to be paid
outstanding_principal = outstanding_principal - prnp # principal left
interest[i] = intr
principal[i] = prnp
balance[i] = outstanding_principal
}
knitr::kable(data.frame(month = 1:payment_months, interest, principal, balance),
caption = "Payment schedule for first 12 months")
{% endhighlight %}
| month| interest| principal| balance|
|-----:|--------:|---------:|--------:|
| 1| 1136.333| 344.6000| 279655.4|
| 2| 1134.935| 345.9985| 279309.4|
| 3| 1133.531| 347.4027| 278962.0|
| 4| 1132.121| 348.8126| 278613.2|
| 5| 1130.705| 350.2282| 278263.0|
| 6| 1129.284| 351.6495| 277911.3|
| 7| 1127.857| 353.0766| 277558.2|
| 8| 1126.424| 354.5096| 277203.7|
| 9| 1124.985| 355.9483| 276847.8|
| 10| 1123.541| 357.3928| 276490.4|
| 11| 1122.090| 358.8432| 276131.5|
| 12| 1120.634| 360.2995| 275771.2|
The R code I give above should be very comfortable to you. If you ask 10 R users to program a mortgage payment schedule calculator, 8 of them probably will give you something similar. However, if you understand the behavior of R environments and `<<-`, you can code it up differently. In the next blog post, I'll explain how environments work and code up the same calculator in a different fashion using `<<-`.
PS: I've put the above code pieces in a function for ease of use.
{% highlight r %}
amortize = function(loan_amt = 200000, term = 360, APR = 4.87/100) {
# calculate simple monthly rate
monthly_rate = APR / 12
# calculate (constant) contractual monthly payment amount
# derived from the present value formula for annuities
# https://en.wikipedia.org/wiki/Annuity
r = (1 + monthly_rate) ^ term - 1
payment = loan_amt * monthly_rate * (r + 1) / r
# initialize output variables
interest = principal = balance = vector("numeric", term)
# calc amortization schedule
outstanding_principal = loan_amt
for (i in 1:term) {
intr = outstanding_principal * monthly_rate
prnp = payment - intr
outstanding_principal = outstanding_principal - prnp
interest[i] = intr
principal[i] = prnp
balance[i] = outstanding_principal
}
data.frame(month = 1:term, interest, principal, balance)
}
{% endhighlight %}
|
gmlang/masterr
|
_posts/r/2018-11-20-calculate-mortgage-payment-schedule.md
|
Markdown
|
mit
| 4,929
|
var app = app || {};
(function(){
app.TestButton = React.createClass({displayName: "TestButton",
handleClick: function() {
this.props.submitTestTask(this.props.btnType);
},
render: function() {
return ( React.createElement("button", {onClick: this.handleClick,
className: "btn btn-test"}, " ", React.createElement("span", {className: "btn-test-text"}, " ", this.props.btn_name, " ")) );
}
});
app.CodeEditor = React.createClass({displayName: "CodeEditor",
handleType:function(){
this.props.updateCode(this.editor.session.getValue());
},
componentDidMount:function(){
this.editor = ace.edit("codeeditor");
this.editor.setTheme("ace/theme/clouds_midnight");
this.editor.setOptions({
fontSize: "1.2em"
});
this.editor.session.setMode("ace/mode/"+this.props.language);
},
render:function(){
return (
React.createElement("div", {id: "codeeditor", onKeyUp: this.handleType})
);
}
});
app.TokenEditor = React.createClass({displayName: "TokenEditor",
handleChange:function(){
var new_token = this.refs.tokenInput.value;
this.props.updateToken(new_token);
},
render: function(){
return (
React.createElement("input", {className: "input-url", onChange: this.handleChange, ref: "tokenInput", placeholder: "Input Server Access Token"})
);
}
});
app.UrlEditor = React.createClass({displayName: "UrlEditor",
getInitialState: function(){
return {
url_vaild:true
}
},
handleChange:function(){
//if url valid, update state, if not, warn
var url_str = this.refs.urlInput.value;
if (app.isUrl(url_str)){
this.setState({url_vaild:true});
//this.probs.updateUrl(url_str)
}else{
this.setState({url_vaild:false});
}
this.props.updateUrl(url_str);
},
classNames:function(){
return 'input-url ' + ((this.state.url_vaild) ? 'input-right':'input-error');
},
render: function(){
return (
React.createElement("input", {className: this.classNames(), onChange: this.handleChange, ref: "urlInput", placeholder: "Type Server or App URL"})
);
}
});
app.ResultDisplay = React.createClass({displayName: "ResultDisplay",
getInitialState:function(){
return {'level':-1, test_type:0, 'steps':[]}
},
displayResult:function(res_dict){
var test_type = res_dict.test_type
this.setState({'test_type':test_type})
if (test_type == 0){
this.setState({'level':res_dict.level});
}
this.setState({'steps':res_dict['steps']});
},
render: function(){
return (
React.createElement("div", {className: "result-container"},
React.createElement("div", {className: "result-head"}, React.createElement("span", {className: "area-title area-title-black"}, "Test Type: "), " ", React.createElement("span", null, this.props.testType)),
React.createElement("div", {className: "detail-result"},
React.createElement("div", {className: "result-sum"},
this.state.test_type == 0 ? React.createElement("h3", null, "Level: ", this.state.level) : null
),
this.state
)
)
)
}
});
var StepDisplay = app.StepDisplay = React.createClass({displayName: "StepDisplay",
getInitialState: function(){
return {
is_img_hide:true,
is_modal_show:false
}
},
handleTextClick:function(){
this.setState({is_img_hide:!this.state.is_img_hide});
},
handleShowFullImage:function(event){
event.stopPropagation();
this.setState({is_modal_show:true});
},
handleHideModal(){
this.setState({is_modal_show:false});
},
handleShowModal(){
this.setState({is_modal_show: true});
},
showSteps: function(steps){
},
render:function(){
return (
React.createElement("div", {className: "step-brief step-brief-success", onClick: this.handleTextClick},
React.createElement("div", null, React.createElement("span", {className: "step-brief-text"}, "This is a step info")),
React.createElement("div", {hidden: this.state.is_img_hide, className: "step-img-block"},
React.createElement("button", {onClick: this.handleShowFullImage, className: "btn btn-primary"}, "Full Image"),
React.createElement("img", {className: "img-responsive img-rounded step-img", src: "../img/1.png"})
),
this.state.is_modal_show ? React.createElement(Modal, {handleHideModal: this.handleHideModal, title: "Step Image", content: React.createElement(FullImageArea, {img_src: "../img/1.png"})}) : null
)
);
}
});
var FullImageArea = app.FullImageArea = React.createClass({displayName: "FullImageArea",
render:function(){
return(
React.createElement("img", {src: this.props.img_src, className: "img-responsive"})
);
}
});
var Modal = app.Modal = React.createClass({displayName: "Modal",
componentDidMount(){
$(ReactDOM.findDOMNode(this)).modal('show');
$(ReactDOM.findDOMNode(this)).on('hidden.bs.modal', this.props.handleHideModal);
},
render:function(){
return (
React.createElement("div", {className: "modal modal-wide fade"},
React.createElement("div", {className: "modal-dialog"},
React.createElement("div", {className: "modal-content"},
React.createElement("div", {className: "modal-header"},
React.createElement("button", {type: "button", className: "close", "data-dismiss": "modal", "aria-label": "Close"}, React.createElement("span", {"aria-hidden": "true"}, "×")),
React.createElement("h4", {className: "modal-title"}, this.props.title)
),
React.createElement("div", {className: "modal-body"},
this.props.content
),
React.createElement("div", {className: "modal-footer text-center"},
React.createElement("button", {className: "btn btn-primary center-block", "data-dismiss": "modal"}, "Close")
)
)
)
)
);
}
});
})();
|
ideaworld/FHIR_Tester
|
FHIR_Tester_statics/js/build/.module-cache/71eaa56ca6a2f3b81e2145d9d8e1f4217ee88529.js
|
JavaScript
|
mit
| 7,312
|
export class Layout1ViewModel {
el: Element;
attached() {
this.el.classList.remove('view-only');
this.el.classList.add('layout-1');
}
activate(params: any) {
this.activate = params;
}
}
|
aurelia/templating-router
|
test/routes/layout-1.ts
|
TypeScript
|
mit
| 208
|
#include "precomp.h"
#include "Gtp/GtpCore.h"
using namespace std;
namespace Gtp {
GtpCore::GtpCore(ostream &out, istream &in, ostream &console)
: m_out(out)
, m_console(console)
, m_in(in)
{
}
void GtpCore::write(const std::string &line) {
m_out << line;
}
void GtpCore::flush() {
m_out.flush();
}
void GtpCore::writeConsoleLn(const std::string &line) {
m_console << line << endl;
}
void GtpCore::sendGtp(const std::string &command) {
write("= " + command + "\n\n");
flush();
}
bool GtpCore::isEndOfInput() {
return m_in.fail();
}
bool GtpCore::getLine(std::string &line) {
return !getline(m_in, line).fail();
}
bool GtpCore::getCommand(std::vector<std::string> &parsed_commands) {
parsed_commands.clear();
string line;
if (!getLine(line)) return false;
char tmp[10240];
strcpy(tmp, line.c_str());
char *tmp1 = strtok(tmp, " \r\n");
while (tmp1 != NULL) {
parsed_commands.push_back(tmp1);
tmp1 = strtok(NULL, " \r\n");
}
return true;
}
}
|
omochi64/ComputerGO_MCTS
|
Gtp/GtpCore.cpp
|
C++
|
mit
| 1,066
|
/****************************************************************************
** Meta object code from reading C++ file 'bitcoinamountfield.h'
**
** Created: Fri Jun 6 19:51:20 2014
** by: The Qt Meta Object Compiler version 63 (Qt 4.8.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../src/qt/bitcoinamountfield.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'bitcoinamountfield.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_BitcoinAmountField[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
2, 14, // methods
1, 24, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: signature, parameters, type, tag, flags
20, 19, 19, 19, 0x05,
// slots: signature, parameters, type, tag, flags
38, 34, 19, 19, 0x08,
// properties: name, type, flags
62, 55, 0x04595103,
// properties: notify_signal_id
0,
0 // eod
};
static const char qt_meta_stringdata_BitcoinAmountField[] = {
"BitcoinAmountField\0\0textChanged()\0idx\0"
"unitChanged(int)\0qint64\0value\0"
};
void BitcoinAmountField::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Q_ASSERT(staticMetaObject.cast(_o));
BitcoinAmountField *_t = static_cast<BitcoinAmountField *>(_o);
switch (_id) {
case 0: _t->textChanged(); break;
case 1: _t->unitChanged((*reinterpret_cast< int(*)>(_a[1]))); break;
default: ;
}
}
}
const QMetaObjectExtraData BitcoinAmountField::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject BitcoinAmountField::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_BitcoinAmountField,
qt_meta_data_BitcoinAmountField, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &BitcoinAmountField::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *BitcoinAmountField::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *BitcoinAmountField::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_BitcoinAmountField))
return static_cast<void*>(const_cast< BitcoinAmountField*>(this));
return QWidget::qt_metacast(_clname);
}
int BitcoinAmountField::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 2)
qt_static_metacall(this, _c, _id, _a);
_id -= 2;
}
#ifndef QT_NO_PROPERTIES
else if (_c == QMetaObject::ReadProperty) {
void *_v = _a[0];
switch (_id) {
case 0: *reinterpret_cast< qint64*>(_v) = value(); break;
}
_id -= 1;
} else if (_c == QMetaObject::WriteProperty) {
void *_v = _a[0];
switch (_id) {
case 0: setValue(*reinterpret_cast< qint64*>(_v)); break;
}
_id -= 1;
} else if (_c == QMetaObject::ResetProperty) {
_id -= 1;
} else if (_c == QMetaObject::QueryPropertyDesignable) {
_id -= 1;
} else if (_c == QMetaObject::QueryPropertyScriptable) {
_id -= 1;
} else if (_c == QMetaObject::QueryPropertyStored) {
_id -= 1;
} else if (_c == QMetaObject::QueryPropertyEditable) {
_id -= 1;
} else if (_c == QMetaObject::QueryPropertyUser) {
_id -= 1;
}
#endif // QT_NO_PROPERTIES
return _id;
}
// SIGNAL 0
void BitcoinAmountField::textChanged()
{
QMetaObject::activate(this, &staticMetaObject, 0, 0);
}
QT_END_MOC_NAMESPACE
|
YourCoin-project/YourCoin
|
build/moc_bitcoinamountfield.cpp
|
C++
|
mit
| 4,258
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("LightClaw.TeamServer.Server.ConsoleFrontend")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Yannic Steenbeck")]
[assembly: AssemblyProduct("LightClaw.TeamServer.Server.ConsoleFrontend")]
[assembly: AssemblyCopyright("Copyright © Yannic Steenbeck 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("b86b3d20-e0ff-48c2-81d9-fd785d01a1c0")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
LightClaw/Engine
|
Source/TeamServer/LightClaw.TeamServer.Server.Frontend.Console/Properties/AssemblyInfo.cs
|
C#
|
mit
| 1,599
|
<?php
/**
* Tests for the Layout class
*
* @package Owl
* @author Dave Widmer <dwidmer@bgsu.edu>
*/
class LayoutTest extends PHPUnit_Framework_TestCase
{
/**
* @var \Owl\Layout The layout to use in the tests.
*/
public $layout;
/**
* @var \Owl\View The base view
*/
public $view;
/**
* Set the template path
*/
public function setUp()
{
$path = __DIR__.DIRECTORY_SEPARATOR."views".DIRECTORY_SEPARATOR;
$finder = new \Owl\Finder\FileSystem($path);
\Owl\View::setFinder($finder);
$this->layout = new LayoutView;
$this->view = new BaseView;
parent::setUp();
}
/**
* Test the fetching of content.
*/
public function testContent()
{
// View content...
$this->layout->setContent($this->view);
$this->assertInstanceOf("Owl\\View", $this->layout->getContent());
// Raw html
$this->layout->setContent("<h1>Hello World</h1>");
$this->assertInternalType("string", $this->layout->getContent());
}
/**
* Testing the setting of the content
*/
public function testContentPartial()
{
$this->layout->setContent($this->view);
$this->assertArrayHasKey("content", $this->layout->getPartials());
}
/**
* Make sure that the layout can access the variables of the content.
*/
public function testContentPassthru()
{
$this->layout->setContent($this->view);
$this->assertTrue(isset($this->layout->name));
$this->assertRegExp("/<title>Owl Testing!<\/title>/", $this->layout->render());
}
/**
* Making sure that the added to layout function is working correctly.
*/
public function testAddedToLayout()
{
$this->layout->setContent($this->view);
$this->assertCount(1, $this->layout->css); // Added from the BaseView
}
public function testRenderWithHTML()
{
$this->layout->setContent("<h1>Injected HTML</h1>");
$this->assertRegExp("/<h1>Injected HTML<\/h1>/", $this->layout->render());
}
}
|
daveWid/Owl
|
tests/LayoutTest.php
|
PHP
|
mit
| 1,886
|
<?php
namespace BrowserStart\Browser;
use BrowserStart\Process;
class PhantomjsTest extends \PHPUnit_Framework_TestCase {
protected static $phantomjs;
protected $url;
public static function setUpBeforeClass() {
$process = new Process();
self::$phantomjs = new Phantomjs($process);
}
public function testStartBrowser() {
$this->url = self::$phantomjs->startBrowser();
$this->assertJson(
$this->execCurl($this->url . "/status")
);
}
/**
* @depends testStartBrowser
*/
public function testGetDriverLogs() {
$this->assertContains(
"GhostDriver - Main - running on port", self::$phantomjs->getDriverLogs()
);
}
/**
* @depends testGetDriverLogs
*/
public function testClose() {
self::$phantomjs->closeBrowser();
$this->assertRegExp(
"~Could.* resolve host~i", $this->execCurl($this->url . "status")
);
}
protected function execCurl($url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOBODY, false);
$ret = curl_exec($ch);
$ret .= curl_error($ch);
curl_close($ch);
return $ret;
}
}
|
pawel-5/BrowserDriver
|
tests/functional/Browser/PhantomjsTest.php
|
PHP
|
mit
| 1,302
|
---
layout: contributor-profile
credit-name: Kate Dollarhyde
first-name: Kate
last-name: Dollarhyde
file-as: d
role: Author
role-2: Editor
role-3:
title: Kate Dollarhyde — Work in Fireside
description: Guest Editor, Aug–Oct 2020
twitter-handle: katedollarhyde
profile-pic: kate-dollarhyde.png
website-url:
short-name: kate-dollarhyde
permalink: kate-dollarhyde
bio-spanish:
---
Kate Dollarhyde is a WGA, BAFTA, and Nebula Award-nominated writer of speculative fiction. Her stories have been published in _Fireside Magazine_, _Lackington’s Magazine_, _Beneath Ceaseless Skies_, and other magazines. She is a former editor-in-chief of the short fiction magazine _Strange Horizons_. She is also a narrative designer at Obsidian Entertainment, where she’s worked on _The Outer Worlds_ and the _Pillars of Eternity_ series. Though she lives in California, her true home is on the internet.
|
firesidefiction/firesidefiction.github.io
|
_contributors/kate-dollarhyde.md
|
Markdown
|
mit
| 894
|
// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "signverifymessagedialog.h"
#include "ui_signverifymessagedialog.h"
#include "addressbookpage.h"
#include "base58.h"
#include "guiutil.h"
#include "init.h"
#include "main.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include "wallet.h"
#include <QClipboard>
#include <string>
#include <vector>
SignVerifyMessageDialog::SignVerifyMessageDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SignVerifyMessageDialog),
model(0)
{
ui->setupUi(this);
#if (QT_VERSION >= 0x040700)
/* Do not move this to the XML file, Qt before 4.7 will choke on it */
ui->addressIn_SM->setPlaceholderText(tr("Enter a Errorcoin address (e.g. Eb27qnrCmU1nQwNMCwFGtzcQTJh62tMe28)"));
ui->signatureOut_SM->setPlaceholderText(tr("Click \"Sign Message\" to generate signature"));
ui->addressIn_VM->setPlaceholderText(tr("Enter a Errorcoin address (e.g. Eb27qnrCmU1nQwNMCwFGtzcQTJh62tMe28)"));
ui->signatureIn_VM->setPlaceholderText(tr("Enter Errorcoin signature"));
#endif
GUIUtil::setupAddressWidget(ui->addressIn_SM, this);
GUIUtil::setupAddressWidget(ui->addressIn_VM, this);
ui->addressIn_SM->installEventFilter(this);
ui->messageIn_SM->installEventFilter(this);
ui->signatureOut_SM->installEventFilter(this);
ui->addressIn_VM->installEventFilter(this);
ui->messageIn_VM->installEventFilter(this);
ui->signatureIn_VM->installEventFilter(this);
ui->signatureOut_SM->setFont(GUIUtil::bitcoinAddressFont());
ui->signatureIn_VM->setFont(GUIUtil::bitcoinAddressFont());
}
SignVerifyMessageDialog::~SignVerifyMessageDialog()
{
delete ui;
}
void SignVerifyMessageDialog::setModel(WalletModel *model)
{
this->model = model;
}
void SignVerifyMessageDialog::setAddress_SM(const QString &address)
{
ui->addressIn_SM->setText(address);
ui->messageIn_SM->setFocus();
}
void SignVerifyMessageDialog::setAddress_VM(const QString &address)
{
ui->addressIn_VM->setText(address);
ui->messageIn_VM->setFocus();
}
void SignVerifyMessageDialog::showTab_SM(bool fShow)
{
ui->tabWidget->setCurrentIndex(0);
if (fShow)
this->show();
}
void SignVerifyMessageDialog::showTab_VM(bool fShow)
{
ui->tabWidget->setCurrentIndex(1);
if (fShow)
this->show();
}
void SignVerifyMessageDialog::on_addressBookButton_SM_clicked()
{
if (model && model->getAddressTableModel())
{
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::ReceivingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec())
{
setAddress_SM(dlg.getReturnValue());
}
}
}
void SignVerifyMessageDialog::on_pasteButton_SM_clicked()
{
setAddress_SM(QApplication::clipboard()->text());
}
void SignVerifyMessageDialog::on_signMessageButton_SM_clicked()
{
/* Clear old signature to ensure users don't get confused on error with an old signature displayed */
ui->signatureOut_SM->clear();
CBitcoinAddress addr(ui->addressIn_SM->text().toStdString());
if (!addr.IsValid())
{
ui->addressIn_SM->setValid(false);
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
return;
}
CKeyID keyID;
if (!addr.GetKeyID(keyID))
{
ui->addressIn_SM->setValid(false);
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
return;
}
WalletModel::UnlockContext ctx(model->requestUnlock());
if (!ctx.isValid())
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("Wallet unlock was cancelled."));
return;
}
CKey key;
if (!pwalletMain->GetKey(keyID, key))
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("Private key for the entered address is not available."));
return;
}
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << ui->messageIn_SM->document()->toPlainText().toStdString();
std::vector<unsigned char> vchSig;
if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig))
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signing failed.") + QString("</nobr>"));
return;
}
ui->statusLabel_SM->setStyleSheet("QLabel { color: green; }");
ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>"));
ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size())));
}
void SignVerifyMessageDialog::on_copySignatureButton_SM_clicked()
{
QApplication::clipboard()->setText(ui->signatureOut_SM->text());
}
void SignVerifyMessageDialog::on_clearButton_SM_clicked()
{
ui->addressIn_SM->clear();
ui->messageIn_SM->clear();
ui->signatureOut_SM->clear();
ui->statusLabel_SM->clear();
ui->addressIn_SM->setFocus();
}
void SignVerifyMessageDialog::on_addressBookButton_VM_clicked()
{
if (model && model->getAddressTableModel())
{
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec())
{
setAddress_VM(dlg.getReturnValue());
}
}
}
void SignVerifyMessageDialog::on_verifyMessageButton_VM_clicked()
{
CBitcoinAddress addr(ui->addressIn_VM->text().toStdString());
if (!addr.IsValid())
{
ui->addressIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
return;
}
CKeyID keyID;
if (!addr.GetKeyID(keyID))
{
ui->addressIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
return;
}
bool fInvalid = false;
std::vector<unsigned char> vchSig = DecodeBase64(ui->signatureIn_VM->text().toStdString().c_str(), &fInvalid);
if (fInvalid)
{
ui->signatureIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The signature could not be decoded.") + QString(" ") + tr("Please check the signature and try again."));
return;
}
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << ui->messageIn_VM->document()->toPlainText().toStdString();
CPubKey pubkey;
if (!pubkey.RecoverCompact(Hash(ss.begin(), ss.end()), vchSig))
{
ui->signatureIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The signature did not match the message digest.") + QString(" ") + tr("Please check the signature and try again."));
return;
}
if (!(CBitcoinAddress(pubkey.GetID()) == addr))
{
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verification failed.") + QString("</nobr>"));
return;
}
ui->statusLabel_VM->setStyleSheet("QLabel { color: green; }");
ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verified.") + QString("</nobr>"));
}
void SignVerifyMessageDialog::on_clearButton_VM_clicked()
{
ui->addressIn_VM->clear();
ui->signatureIn_VM->clear();
ui->messageIn_VM->clear();
ui->statusLabel_VM->clear();
ui->addressIn_VM->setFocus();
}
bool SignVerifyMessageDialog::eventFilter(QObject *object, QEvent *event)
{
if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::FocusIn)
{
if (ui->tabWidget->currentIndex() == 0)
{
/* Clear status message on focus change */
ui->statusLabel_SM->clear();
/* Select generated signature */
if (object == ui->signatureOut_SM)
{
ui->signatureOut_SM->selectAll();
return true;
}
}
else if (ui->tabWidget->currentIndex() == 1)
{
/* Clear status message on focus change */
ui->statusLabel_VM->clear();
}
}
return QDialog::eventFilter(object, event);
}
|
error-dev/ErrorCoin
|
src/qt/signverifymessagedialog.cpp
|
C++
|
mit
| 8,988
|
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';
import { MatToolbarModule, MatButtonModule, MatListModule } from '@angular/material';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ProfileComponent } from './profile/profile.component';
import { MsalModule, MsalInterceptor } from '@azure/msal-angular';
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
export const protectedResourceMap: [string, string[]][] = [
['https://graph.microsoft.com/v1.0/me', ['user.read']]
];
const isIE = window.navigator.userAgent.indexOf("MSIE ") > -1 || window.navigator.userAgent.indexOf("Trident/") > -1;
@NgModule({
declarations: [
AppComponent,
ProfileComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
HttpClientModule,
MatToolbarModule,
MatButtonModule,
MatListModule,
AppRoutingModule,
MsalModule.forRoot({
auth: {
clientId: '6226576d-37e9-49eb-b201-ec1eeb0029b6',
authority: "https://login.microsoftonline.com/common/",
validateAuthority: true,
redirectUri: "http://localhost:4200/",
postLogoutRedirectUri: "http://localhost:4200/",
navigateToLoginRequestUrl: true,
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: isIE, // set to true for IE 11
},
},
{
popUp: !isIE,
consentScopes: [
"user.read",
"openid",
"profile",
"api://a88bb933-319c-41b5-9f04-eff36d985612/access_as_user"
],
unprotectedResources: ["https://www.microsoft.com/en-us/"],
protectedResourceMap,
extraQueryParameters: {}
}
)
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: MsalInterceptor,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
|
AzureAD/microsoft-authentication-library-for-js
|
samples/msal-angular-samples/angular7-sample-app/src/app/app.module.ts
|
TypeScript
|
mit
| 2,070
|
---
layout: default
title: 404 Error | Sorry, this page does not exist.
---
<div class="error">
<h1>Four, oh, Four</h1>
<p class="lead"><a href="/" title="The greatest site in the world">Try this?</a></p>
</div>
|
bsmitty5000/bsmitty5000.github.io
|
404.html
|
HTML
|
mit
| 232
|
class DropOwnerships < ActiveRecord::Migration[5.0]
def change
remove_index :ownerships, name: 'index_ownerships_on_uniqueness'
remove_index :ownerships, name: 'index_ownerships_on_package_uniqueness'
drop_table :ownerships do |t|
t.references :user, foreign_key: true
t.references :package, foreign_key: true
t.timestamps null: false
end
end
end
|
djsegal/julia_observer
|
db/migrate/20161218062422_drop_ownerships.rb
|
Ruby
|
mit
| 387
|
package types
// DO NOT EDIT. THIS FILE WAS AUTOMATICALLY GENERATED
// SoftLayer_Product_Package_Order_Configuration - This datatype describes the item categories that are
// required for each package to be ordered. For instance, for package 2, there will be many required
// categories. When submitting an order for a server, there must be at most 1 price for each category
// whose "isRequired" is set. Examples of required categories: - server - ram - bandwidth - disk0 There
// are others, but these are the main ones. For each required category, a SoftLayer_Product_Item_Price
// must be chosen that is valid for the package.
type SoftLayer_Product_Package_Order_Configuration struct {
// ErrorMessage - The error message displayed if the submitted order does not contain this item
// category, if it is required.
ErrorMessage string `json:"errorMessage,omitempty"`
// Id - no documentation
Id int `json:"id,omitempty"`
// IsRequired - This is a flag which tells SoftLayer_Product_Order::verifyOrder() whether or not this
// category is required. If this is set, then the order submitted must contain a
// SoftLayer_Product_Item_Price with this category as part of the order.
IsRequired int `json:"isRequired,omitempty"`
// ItemCategoryId - no documentation
ItemCategoryId int `json:"itemCategoryId,omitempty"`
// OrderStepId - The order step ID for this particular option in the package.
OrderStepId int `json:"orderStepId,omitempty"`
// PackageId - no documentation
PackageId int `json:"packageId,omitempty"`
// Sort - This is an integer used to show the order in which each item Category should be displayed.
// This is merely the suggested order.
Sort int `json:"sort,omitempty"`
// ItemCategory - no documentation
ItemCategory *SoftLayer_Product_Item_Category `json:"itemCategory,omitempty"`
// Package - no documentation
Package *SoftLayer_Product_Package `json:"package,omitempty"`
// Step - no documentation
Step *SoftLayer_Product_Package_Order_Step `json:"step,omitempty"`
}
func (softlayer_product_package_order_configuration *SoftLayer_Product_Package_Order_Configuration) String() string {
return "SoftLayer_Product_Package_Order_Configuration"
}
|
sudorandom/softlayer-go-gen
|
types/gen_softlayer_product_package_order_configuration.go
|
GO
|
mit
| 2,203
|
//using System;
//
//using NUnit.Framework;
//
//using SoundCloud.Api.Utils;
//
//namespace SoundCloud.Api.Test.Utils
//{
// [TestFixture]
// public class UriExtensionTest
// {
// [Test]
// public void Test_AppendCredentials_AccessToken()
// {
// var credentials = new SoundCloudCredentials();
// credentials.AccessToken = "token";
//
// var uri = new Uri("http://test.com/?");
// uri = uri.AppendCredentials(credentials);
//
// Assert.That(uri.ToString(), Is.EqualTo("http://test.com/?oauth_token=token"));
// }
//
// [Test]
// public void Test_AppendCredentials_Ampersand_Delimiter()
// {
// var credentials = new SoundCloudCredentials();
// credentials.ClientId = "clientId";
//
// var uri = new Uri("http://test.com/?query=value");
// uri = uri.AppendCredentials(credentials);
//
// Assert.That(uri.ToString(), Is.EqualTo("http://test.com/?query=value&client_id=clientId"));
// }
//
// [Test]
// public void Test_AppendCredentials_ClientId()
// {
// var credentials = new SoundCloudCredentials();
// credentials.ClientId = "clientId";
//
// var uri = new Uri("http://test.com/?");
// uri = uri.AppendCredentials(credentials);
//
// Assert.That(uri.ToString(), Is.EqualTo("http://test.com/?client_id=clientId"));
// }
//
// [Test]
// public void Test_AppendCredentials_No_Credentials()
// {
// var credentials = new SoundCloudCredentials();
//
// var uri = new Uri("http://test.com/?");
// uri = uri.AppendCredentials(credentials);
//
// Assert.That(uri.ToString(), Is.EqualTo("http://test.com/?"));
// }
//
// [Test]
// public void Test_AppendCredentials_No_Query()
// {
// var credentials = new SoundCloudCredentials();
// credentials.ClientId = "clientId";
//
// var uri = new Uri("http://test.com/");
// uri = uri.AppendCredentials(credentials);
//
// Assert.That(uri.ToString(), Is.EqualTo("http://test.com/?client_id=clientId"));
// }
// }
//}
|
prayzzz/SoundCloud.Api
|
test/SoundCloud.Api.Test/Utils/UriExtensionTest.cs
|
C#
|
mit
| 2,273
|
---
redirect_from: /docs/1.0.16/interfaces/state.statedeclaration.html
---
<!doctype html>
<html class="default no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>StateDeclaration | @uirouter/angularjs</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../assets/css/main.css">
<link rel="stylesheet" href="../assets/css/uirouter.css">
<script src="../assets/js/modernizr.js"></script>
<script src="../assets/js/reset.js"></script>
</head>
<body>
<header>
<div class="tsd-page-toolbar">
<div class="container">
<div class="table-wrap">
<div class="table-cell" id="tsd-search" data-index="../assets/js/search.js" data-base="..">
<div class="field">
<label for="tsd-search-field" class="tsd-widget search no-caption">Search</label>
<input id="tsd-search-field" type="text" />
</div>
<ul class="results">
<li class="state loading">Preparing search index...</li>
<li class="state failure">The search index is not available</li>
</ul>
<a href="../index.html" class="title">@uirouter/angularjs</a>
</div>
<div class="table-cell" id="tsd-widgets">
<div id="tsd-filter">
<a href="#" class="tsd-widget options no-caption" data-toggle="options">Options</a>
<div class="tsd-filter-group">
<!--
<div class="tsd-select" id="tsd-filter-visibility">
<span class="tsd-select-label">All</span>
<ul class="tsd-select-list">
<li data-value="public">Public</li>
<li data-value="protected">Public/Protected</li>
<li data-value="private" class="selected">All</li>
</ul>
</div>
<input type="checkbox" id="tsd-filter-inherited" checked />
<label class="tsd-widget" for="tsd-filter-inherited">Inherited</label>
-->
<input type="checkbox" id="tsd-filter-externals" checked />
<label class="tsd-widget" for="tsd-filter-externals">Internal UI-Router API</label>
<!--
<input type="checkbox" id="tsd-filter-only-exported" />
<label class="tsd-widget" for="tsd-filter-only-exported">Only exported</label>
-->
</div>
</div>
<a href="#" class="tsd-widget menu no-caption" data-toggle="menu">Menu</a>
</div>
</div>
</div>
</div>
<div class="tsd-page-title">
<div class="container">
<ul class="tsd-breadcrumb">
<li>
<a href="../index.html">@uirouter/angularjs</a>
</li>
<li>
<a href="../modules/state.html">state</a>
</li>
<li>
<a href="state.statedeclaration.html">StateDeclaration</a>
</li>
</ul>
<h1>Interface StateDeclaration</h1>
</div>
</div>
</header>
<div class="container container-main">
<div class="row">
<div class="col-8 col-content">
<section class="tsd-panel tsd-comment">
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>The StateDeclaration object is used to define a state or nested state.</p>
</div>
<p>Note: Each implementation of UI-Router (for a specific framework)
extends this interface as necessary.</p>
<h4 id="example-">Example:</h4>
<pre><code class="lang-js"><span class="hljs-comment">// StateDeclaration object</span>
<span class="hljs-keyword">var</span> foldersState = {
<span class="hljs-attr">name</span>: <span class="hljs-string">'folders'</span>,
<span class="hljs-attr">url</span>: <span class="hljs-string">'/folders'</span>,
<span class="hljs-attr">component</span>: FoldersComponent,
<span class="hljs-attr">resolve</span>: {
<span class="hljs-attr">allfolders</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">FolderService</span>) </span>{
<span class="hljs-keyword">return</span> FolderService.list();
}
},
}
registry.register(foldersState);
</code></pre>
<p>A state declaration may also be an ES6 class which implements the StateDeclaration interface
and has a <code>@State()</code> decorator</p>
<h4 id="example-">Example:</h4>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { State } <span class="hljs-keyword">from</span> <span class="hljs-string">"@uirouter/core"</span>
<span class="hljs-keyword">import</span> { FolderService } <span class="hljs-keyword">from</span> <span class="hljs-string">"../folder.service"</span>
<span class="hljs-comment">// StateDeclaration class</span>
@State()
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FoldersState</span> <span class="hljs-title">implements</span> <span class="hljs-title">StateDeclaration</span> </span>{
name: <span class="hljs-string">'folders'</span>,
<span class="hljs-attr">url</span>: <span class="hljs-string">'/folders'</span>,
<span class="hljs-attr">component</span>: FoldersComponent
@Resolve({ <span class="hljs-attr">deps</span>: [ FolderService ] })
allfolders(FolderService) {
<span class="hljs-keyword">return</span> FolderService.list();
},
}
registry.register(FoldersState);
</code></pre>
</div>
</section>
<section class="tsd-panel tsd-hierarchy">
<h3>Hierarchy</h3>
<ul class="tsd-hierarchy">
<li>
<span class="target">StateDeclaration</span>
</li>
</ul>
</section>
<section class="tsd-panel-group tsd-index-group">
<h2>Index</h2>
<section class="tsd-panel tsd-index-panel">
<div class="tsd-index-content">
<section class="tsd-index-section ">
<h3>Properties</h3>
<ul class="tsd-index-list">
<li class="tsd-kind-property tsd-parent-kind-interface"><a href="state.statedeclaration.html#__state" class="tsd-kind-icon">$$state</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><a href="state.statedeclaration.html#abstract" class="tsd-kind-icon">abstract</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><a href="state.statedeclaration.html#data" class="tsd-kind-icon">data</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><a href="state.statedeclaration.html#lazyload" class="tsd-kind-icon">lazy<wbr>Load</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><a href="state.statedeclaration.html#name" class="tsd-kind-icon">name</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><a href="state.statedeclaration.html#onenter" class="tsd-kind-icon">on<wbr>Enter</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><a href="state.statedeclaration.html#onexit" class="tsd-kind-icon">on<wbr>Exit</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><a href="state.statedeclaration.html#onretain" class="tsd-kind-icon">on<wbr>Retain</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><a href="state.statedeclaration.html#params" class="tsd-kind-icon">params</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><a href="state.statedeclaration.html#parent" class="tsd-kind-icon">parent</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><a href="state.statedeclaration.html#redirectto" class="tsd-kind-icon">redirect<wbr>To</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><a href="state.statedeclaration.html#reloadonsearch" class="tsd-kind-icon">reload<wbr>OnSearch</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><a href="state.statedeclaration.html#resolve" class="tsd-kind-icon">resolve</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><a href="state.statedeclaration.html#resolvepolicy" class="tsd-kind-icon">resolve<wbr>Policy</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><a href="state.statedeclaration.html#url" class="tsd-kind-icon">url</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><a href="state.statedeclaration.html#views" class="tsd-kind-icon">views</a></li>
</ul>
</section>
</div>
</section>
</section>
<section class="tsd-panel-group tsd-member-group ">
<h2>Properties</h2>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface">
<a name="__state" class="tsd-anchor"></a>
<!--
<h3><span class="tsd-flag ts-flagOptional">Optional</span> $$state</h3>
-->
<div class="tsd-signature tsd-kind-icon">$$state<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">function</span> <div class="tsd-header">
<p> Gets the internal State object API </p>
</div>
</div>
<div class="tsd-declaration">
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>Gets the internal State object API</p>
</div>
<p>Gets the <em>internal API</em> for a registered state.</p>
<p>Note: the internal <a href="../classes/state.stateobject.html">StateObject</a> API is subject to change without notice</p>
</div>
</div>
<div class="tsd-type-declaration">
<h4>Type declaration</h4>
<ul class="tsd-parameters">
<li class="tsd-parameter-siganture">
<ul class="tsd-signatures tsd-kind-type-literal tsd-parent-kind-property tsd-is-not-exported">
<li class="tsd-signature tsd-kind-icon"><span class="tsd-signature-symbol">(</span><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol">: </span><a href="../classes/state.stateobject.html" class="tsd-signature-type">StateObject</a></li>
</ul>
<ul class="tsd-descriptions">
<li class="tsd-description">
<div class="tsd-returns">
<h4 class="tsd-returns-title">Returns <a href="../classes/state.stateobject.html" class="tsd-signature-type">StateObject</a></h4>
</div>
</li>
</ul>
</li>
</ul>
</div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/ui-router/core/blob/9bb7287/src/state/interface.ts#L190">ui-router-core/src/state/interface.ts:190</a></li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface">
<a name="abstract" class="tsd-anchor"></a>
<!--
<h3><span class="tsd-flag ts-flagOptional">Optional</span> abstract</h3>
-->
<div class="tsd-signature tsd-kind-icon">abstract<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">boolean</span> <div class="tsd-header">
<p> Abstract state indicator </p>
</div>
</div>
<div class="tsd-declaration">
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>Abstract state indicator</p>
</div>
<p>An abstract state can never be directly activated.
Use an abstract state to provide inherited properties (url, resolve, data, etc) to children states.</p>
</div>
</div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/ui-router/core/blob/9bb7287/src/state/interface.ts#L155">ui-router-core/src/state/interface.ts:155</a></li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface">
<a name="data" class="tsd-anchor"></a>
<!--
<h3><span class="tsd-flag ts-flagOptional">Optional</span> data</h3>
-->
<div class="tsd-signature tsd-kind-icon">data<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">any</span> <div class="tsd-header">
<p> An inherited property to store state data </p>
</div>
</div>
<div class="tsd-declaration">
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>An inherited property to store state data</p>
</div>
<p>This is a spot for you to store inherited state metadata.
Child states' <code>data</code> object will prototypally inherit from their parent state.</p>
<p>This is a good spot to put metadata such as <code>requiresAuth</code>.</p>
<p>Note: because prototypal inheritance is used, changes to parent <code>data</code> objects reflect in the child <code>data</code> objects.
Care should be taken if you are using <code>hasOwnProperty</code> on the <code>data</code> object.
Properties from parent objects will return false for <code>hasOwnProperty</code>.</p>
</div>
</div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/ui-router/core/blob/9bb7287/src/state/interface.ts#L439">ui-router-core/src/state/interface.ts:439</a></li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface">
<a name="lazyload" class="tsd-anchor"></a>
<!--
<h3><span class="tsd-flag ts-flagOptional">Optional</span> lazy<wbr>Load</h3>
-->
<div class="tsd-signature tsd-kind-icon">lazy<wbr>Load<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">function</span> <div class="tsd-header">
<p> A function used to lazy load code </p>
</div>
</div>
<div class="tsd-declaration">
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>A function used to lazy load code</p>
</div>
<p>The <code>lazyLoad</code> function is invoked before the state is activated.
The transition waits while the code is loading.</p>
<p>The function should load the code that is required to activate the state.
For example, it may load a component class, or some service code.
The function must return a promise which resolves when loading is complete.</p>
<p>For example, this code lazy loads a service before the <code>abc</code> state is activated:</p>
<pre><code>.<span class="hljs-keyword">state</span>('abc', {
lazyLoad: (transition, <span class="hljs-keyword">state</span>) => System.import('./abcService')
}
</code></pre><p>The <code>abcService</code> file is imported and loaded
(it is assumed that the <code>abcService</code> file knows how to register itself as a service).</p>
<h4 id="lifecycle">Lifecycle</h4>
<ul>
<li>The <code>lazyLoad</code> function is invoked if a transition is going to enter the state.</li>
<li>The function is invoked before the transition starts (using an <code>onBefore</code> transition hook).</li>
<li>The function is only invoked once; while the <code>lazyLoad</code> function is loading code, it will not be invoked again.
For example, if the user double clicks a ui-sref, <code>lazyLoad</code> is only invoked once even though there were two transition attempts.
Instead, the existing lazy load promise is re-used.</li>
<li>When the promise resolves successfully, the <code>lazyLoad</code> property is deleted from the state declaration.</li>
<li>If the promise resolves to a <a href="state.lazyloadresult.html">LazyLoadResult</a> which has an array of <code>states</code>, those states are registered.</li>
<li><p>The original transition is retried (this time without the <code>lazyLoad</code> property present).</p>
</li>
<li><p>If the <code>lazyLoad</code> function fails, then the transition also fails.
The failed transition (and the <code>lazyLoad</code> function) could potentially be retried by the user.</p>
</li>
</ul>
<h3 id="lazy-loading-state-definitions-future-states-">Lazy loading state definitions (Future States)</h3>
<p>State definitions can also be lazy loaded.
This might be desirable when building large, multi-module applications.</p>
<p>To lazy load state definitions, a Future State should be registered as a placeholder.
When the state definitions are lazy loaded, the Future State is deregistered.</p>
<p>A future state can act as a placeholder for a single state, or for an entire module of states and substates.
A future state should have:</p>
<ul>
<li>A <code>name</code> which ends in <code>.**</code>.
A future state's <code>name</code> property acts as a wildcard <a href="../classes/core.glob.html">Glob</a>.
It matches any state name that starts with the <code>name</code> (including child states that are not yet loaded).</li>
<li>A <code>url</code> prefix.
A future state's <code>url</code> property acts as a wildcard.
UI-Router matches all paths that begin with the <code>url</code>.
It effectively appends <code>.*</code> to the internal regular expression.
When the prefix matches, the future state will begin loading.</li>
<li>A <code>lazyLoad</code> function.
This function should should return a Promise to lazy load the code for one or more <a href="state.statedeclaration.html">StateDeclaration</a> objects.
It should return a <a href="state.lazyloadresult.html">LazyLoadResult</a>.
Generally, one of the lazy loaded states should have the same name as the future state.
The new state will then <strong>replace the future state placeholder</strong> in the registry.</li>
</ul>
<h3 id="additional-resources">Additional resources</h3>
<p>For in depth information on lazy loading and Future States, see the <a href="https://ui-router.github.io/guides/lazyload">Lazy Loading Guide</a>.</p>
<h4 id="example-states-js">Example: states.js</h4>
<pre><code class="lang-js">
<span class="hljs-comment">// This child state is a lazy loaded future state</span>
<span class="hljs-comment">// The `lazyLoad` function loads the final state definition</span>
{
<span class="hljs-attr">name</span>: <span class="hljs-string">'parent.**'</span>,
<span class="hljs-attr">url</span>: <span class="hljs-string">'/parent'</span>,
<span class="hljs-attr">lazyLoad</span>: <span class="hljs-function"><span class="hljs-params">()</span> =></span> System.import(<span class="hljs-string">'./lazy.states.js'</span>)
}
</code></pre>
<h4 id="example-lazy-states-js">Example: lazy.states.js</h4>
<p>This file is lazy loaded. It exports an array of states.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> {ChildComponent} <span class="hljs-keyword">from</span> <span class="hljs-string">"./child.component.js"</span>;
<span class="hljs-keyword">import</span> {ParentComponent} <span class="hljs-keyword">from</span> <span class="hljs-string">"./parent.component.js"</span>;
<span class="hljs-comment">// This fully defined state replaces the future state</span>
<span class="hljs-keyword">let</span> parentState = {
<span class="hljs-comment">// the name should match the future state</span>
name: <span class="hljs-string">'parent'</span>,
<span class="hljs-attr">url</span>: <span class="hljs-string">'/parent/:parentId'</span>,
<span class="hljs-attr">component</span>: ParentComponent,
<span class="hljs-attr">resolve</span>: {
<span class="hljs-attr">parentData</span>: <span class="hljs-function">(<span class="hljs-params">$transition$, ParentService</span>) =></span>
ParentService.get($transition$.params().parentId)
}
}
<span class="hljs-keyword">let</span> childState = {
<span class="hljs-attr">name</span>: <span class="hljs-string">'parent.child'</span>,
<span class="hljs-attr">url</span>: <span class="hljs-string">'/child/:childId'</span>,
<span class="hljs-attr">params</span>: {
<span class="hljs-attr">childId</span>: <span class="hljs-string">"default"</span>
},
<span class="hljs-attr">resolve</span>: {
<span class="hljs-attr">childData</span>: <span class="hljs-function">(<span class="hljs-params">$transition$, ChildService</span>) =></span>
ChildService.get($transition$.params().childId)
}
};
<span class="hljs-comment">// This array of states will be registered by the lazyLoad hook</span>
<span class="hljs-keyword">let</span> lazyLoadResults = {
<span class="hljs-attr">states</span>: [ parentState, childState ]
};
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> lazyLoadResults;
</code></pre>
<dl class="tsd-comment-tags">
<dt>param</dt>
<dd><p>the <a href="../classes/transition.transition-1.html">Transition</a> that is activating the future state</p>
</dd>
<dt>param</dt>
<dd><p>the <a href="state.statedeclaration.html">StateDeclaration</a> that the <code>lazyLoad</code> function is declared on</p>
</dd>
<dt>returns</dt>
<dd><p>a Promise to load the states.
Optionally, if the promise resolves to a <a href="state.lazyloadresult.html">LazyLoadResult</a>,
the states will be registered with the <a href="../classes/state.stateregistry.html">StateRegistry</a>.</p>
</dd>
</dl>
</div>
</div>
<div class="tsd-type-declaration">
<h4>Type declaration</h4>
<ul class="tsd-parameters">
<li class="tsd-parameter-siganture">
<ul class="tsd-signatures tsd-kind-type-literal tsd-parent-kind-property tsd-is-not-exported">
<li class="tsd-signature tsd-kind-icon"><span class="tsd-signature-symbol">(</span>transition<span class="tsd-signature-symbol">: </span><a href="../classes/transition.transition-1.html" class="tsd-signature-type">Transition</a>, state<span class="tsd-signature-symbol">: </span><a href="state.statedeclaration.html" class="tsd-signature-type">StateDeclaration</a><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">Promise</span><span class="tsd-signature-symbol"><</span><a href="state.lazyloadresult.html" class="tsd-signature-type">LazyLoadResult</a><span class="tsd-signature-symbol">></span></li>
</ul>
<ul class="tsd-descriptions">
<li class="tsd-description">
<h4 class="tsd-parameters-title">Parameters</h4>
<ul class="tsd-parameters">
<li>
<h5>transition <a href="../classes/transition.transition-1.html" class="tsd-signature-type">Transition</a></h5>
</li>
<li>
<h5>state <a href="state.statedeclaration.html" class="tsd-signature-type">StateDeclaration</a></h5>
</li>
</ul>
<div class="tsd-returns">
<h4 class="tsd-returns-title">Returns <span class="tsd-signature-type">Promise</span><span class="tsd-signature-symbol"><</span><a href="state.lazyloadresult.html" class="tsd-signature-type">LazyLoadResult</a><span class="tsd-signature-symbol">></span></h4>
</div>
</li>
</ul>
</li>
</ul>
</div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/ui-router/core/blob/9bb7287/src/state/interface.ts#L700">ui-router-core/src/state/interface.ts:700</a></li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface">
<a name="name" class="tsd-anchor"></a>
<!--
<h3><span class="tsd-flag ts-flagOptional">Optional</span> name</h3>
-->
<div class="tsd-signature tsd-kind-icon">name<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">string</span> <div class="tsd-header">
<p> The state name (required) </p>
</div>
</div>
<div class="tsd-declaration">
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>The state name (required)</p>
</div>
<p>A unique state name, e.g. <code>"home"</code>, <code>"about"</code>, <code>"contacts"</code>.
To create a parent/child state use a dot, e.g. <code>"about.sales"</code>, <code>"home.newest"</code>.</p>
<p>Note: [State] objects require unique names.
The name is used like an id.</p>
</div>
</div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/ui-router/core/blob/9bb7287/src/state/interface.ts#L147">ui-router-core/src/state/interface.ts:147</a></li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface">
<a name="onenter" class="tsd-anchor"></a>
<!--
<h3><span class="tsd-flag ts-flagOptional">Optional</span> on<wbr>Enter</h3>
-->
<div class="tsd-signature tsd-kind-icon">on<wbr>Enter<span class="tsd-signature-symbol">:</span> <a href="transition.transitionstatehookfn.html" class="tsd-signature-type">TransitionStateHookFn</a> <div class="tsd-header">
<p> A Transition Hook called with the state is being entered. See: <a href="transition.ihookregistry.html#onenter">IHookRegistry.onEnter</a> </p>
</div>
</div>
<div class="tsd-declaration">
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>A Transition Hook called with the state is being entered. See: <a href="transition.ihookregistry.html#onenter">IHookRegistry.onEnter</a></p>
</div>
<h4 id="example-">Example:</h4>
<pre><code class="lang-js">.state({
<span class="hljs-attr">name</span>: <span class="hljs-string">'mystate'</span>,
<span class="hljs-attr">onEnter</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">trans, state</span>) </span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Entering "</span> + state.name);
}
});
</code></pre>
<p>Note: The above <code>onEnter</code> on the state declaration is effectively sugar for:</p>
<pre><code class="lang-js">transitionService.onEnter({ <span class="hljs-attr">entering</span>: <span class="hljs-string">'mystate'</span> }, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">trans, state</span>) </span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Entering "</span> + state.name);
});
</code></pre>
</div>
</div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/ui-router/core/blob/9bb7287/src/state/interface.ts#L532">ui-router-core/src/state/interface.ts:532</a></li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface">
<a name="onexit" class="tsd-anchor"></a>
<!--
<h3><span class="tsd-flag ts-flagOptional">Optional</span> on<wbr>Exit</h3>
-->
<div class="tsd-signature tsd-kind-icon">on<wbr>Exit<span class="tsd-signature-symbol">:</span> <a href="transition.transitionstatehookfn.html" class="tsd-signature-type">TransitionStateHookFn</a> <div class="tsd-header">
<p> A Transition Hook called with the state is being exited. See: <a href="transition.ihookregistry.html#onexit">IHookRegistry.onExit</a> </p>
</div>
</div>
<div class="tsd-declaration">
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>A Transition Hook called with the state is being exited. See: <a href="transition.ihookregistry.html#onexit">IHookRegistry.onExit</a></p>
</div>
<h4 id="example-">Example:</h4>
<pre><code class="lang-js">.state({
<span class="hljs-attr">name</span>: <span class="hljs-string">'mystate'</span>,
<span class="hljs-attr">onExit</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">trans, state</span>) </span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Leaving "</span> + state.name);
}
});
</code></pre>
<p>Note: The above <code>onRetain</code> on the state declaration is effectively sugar for:</p>
<pre><code class="lang-js">transitionService.onExit({ <span class="hljs-attr">exiting</span>: <span class="hljs-string">'mystate'</span> }, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">trans, state</span>) </span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Leaving "</span> + state.name);
});
</code></pre>
</div>
</div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/ui-router/core/blob/9bb7287/src/state/interface.ts#L576">ui-router-core/src/state/interface.ts:576</a></li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface">
<a name="onretain" class="tsd-anchor"></a>
<!--
<h3><span class="tsd-flag ts-flagOptional">Optional</span> on<wbr>Retain</h3>
-->
<div class="tsd-signature tsd-kind-icon">on<wbr>Retain<span class="tsd-signature-symbol">:</span> <a href="transition.transitionstatehookfn.html" class="tsd-signature-type">TransitionStateHookFn</a> <div class="tsd-header">
<p> A <a href="transition.transitionstatehookfn.html">TransitionStateHookFn</a> called with the state is being retained/kept. See: <a href="transition.ihookregistry.html#onretain">IHookRegistry.onRetain</a> </p>
</div>
</div>
<div class="tsd-declaration">
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>A <a href="transition.transitionstatehookfn.html">TransitionStateHookFn</a> called with the state is being retained/kept. See: <a href="transition.ihookregistry.html#onretain">IHookRegistry.onRetain</a></p>
</div>
<h4 id="example-">Example:</h4>
<pre><code class="lang-js">.state({
<span class="hljs-attr">name</span>: <span class="hljs-string">'mystate'</span>,
<span class="hljs-attr">onRetain</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">trans, state</span>) </span>{
<span class="hljs-built_in">console</span>.log(state.name + <span class="hljs-string">" is still active!"</span>);
}
});
</code></pre>
<p>Note: The above <code>onRetain</code> on the state declaration is effectively sugar for:</p>
<pre><code class="lang-js">transitionService.onRetain({ <span class="hljs-attr">retained</span>: <span class="hljs-string">'mystate'</span> }, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">trans, state</span>) </span>{
<span class="hljs-built_in">console</span>.log(state.name + <span class="hljs-string">" is still active!"</span>);
});
</code></pre>
</div>
</div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/ui-router/core/blob/9bb7287/src/state/interface.ts#L554">ui-router-core/src/state/interface.ts:554</a></li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface">
<a name="params" class="tsd-anchor"></a>
<!--
<h3><span class="tsd-flag ts-flagOptional">Optional</span> params</h3>
-->
<div class="tsd-signature tsd-kind-icon">params<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">object</span> <div class="tsd-header">
<p> Params configuration </p>
</div>
</div>
<div class="tsd-declaration">
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>Params configuration</p>
</div>
<p>An object which optionally configures parameters declared in the url, or defines additional non-url
parameters. For each parameter being configured, add a <a href="params.paramdeclaration.html">ParamDeclaration</a> keyed to the name of the parameter.</p>
<h4 id="example-">Example:</h4>
<pre><code class="lang-js">params: {
<span class="hljs-attr">param1</span>: {
<span class="hljs-attr">type</span>: <span class="hljs-string">"int"</span>,
<span class="hljs-attr">array</span>: <span class="hljs-literal">true</span>,
<span class="hljs-attr">value</span>: []
},
<span class="hljs-attr">param2</span>: {
<span class="hljs-attr">value</span>: <span class="hljs-string">"index"</span>
}
}
</code></pre>
</div>
</div>
<div class="tsd-type-declaration">
<h4>Type declaration</h4>
<ul class="tsd-parameters">
<li class="tsd-parameter-index-signature">
<h5><span class="tsd-signature-symbol">[</span>key: <span class="tsd-signature-type">string</span><span class="tsd-signature-symbol">]: </span><a href="params.paramdeclaration.html" class="tsd-signature-type">ParamDeclaration</a><span class="tsd-signature-symbol"> | </span><span class="tsd-signature-type">any</span></h5>
</li>
</ul>
</div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/ui-router/core/blob/9bb7287/src/state/interface.ts#L378">ui-router-core/src/state/interface.ts:378</a></li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface">
<a name="parent" class="tsd-anchor"></a>
<!--
<h3><span class="tsd-flag ts-flagOptional">Optional</span> parent</h3>
-->
<div class="tsd-signature tsd-kind-icon">parent<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">string</span><span class="tsd-signature-symbol"> | </span><a href="state.statedeclaration.html" class="tsd-signature-type">StateDeclaration</a> <div class="tsd-header">
<p> The parent state </p>
</div>
</div>
<div class="tsd-declaration">
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>The parent state</p>
</div>
<p>Normally, a state's parent is implied from the state's <a href="state.statedeclaration.html#name">name</a>, e.g., <code>"parentstate.childstate"</code>.</p>
<p>Alternatively, you can explicitly set the parent state using this property.
This allows shorter state names, e.g., <code><a ui-sref="childstate">Child</a></code>
instead of `<a ui-sref="parentstate.childstate">Child</a></p>
<p>When using this property, the state's name should not have any dots in it.</p>
<h4 id="example-">Example:</h4>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> parentstate = {
<span class="hljs-attr">name</span>: <span class="hljs-string">'parentstate'</span>
}
<span class="hljs-keyword">var</span> childstate = {
<span class="hljs-attr">name</span>: <span class="hljs-string">'childstate'</span>,
<span class="hljs-attr">parent</span>: <span class="hljs-string">'parentstate'</span>
<span class="hljs-comment">// or use a JS var which is the parent StateDeclaration, i.e.:</span>
<span class="hljs-comment">// parent: parentstate</span>
}
</code></pre>
</div>
</div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/ui-router/core/blob/9bb7287/src/state/interface.ts#L181">ui-router-core/src/state/interface.ts:181</a></li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface">
<a name="redirectto" class="tsd-anchor"></a>
<!--
<h3><span class="tsd-flag ts-flagOptional">Optional</span> redirect<wbr>To</h3>
-->
<div class="tsd-signature tsd-kind-icon">redirect<wbr>To<span class="tsd-signature-symbol">:</span> <a href="../modules/state.html#redirecttoresult" class="tsd-signature-type">RedirectToResult</a><span class="tsd-signature-symbol"> | </span><span class="tsd-signature-type">function</span><span class="tsd-signature-symbol"> | </span><span class="tsd-signature-type">function</span> <div class="tsd-header">
<p> Synchronously or asynchronously redirects Transitions to a different state/params </p>
</div>
</div>
<div class="tsd-declaration">
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>Synchronously or asynchronously redirects Transitions to a different state/params</p>
</div>
<p>If this property is defined, a Transition directly to this state will be redirected based on the property's value.</p>
<ul>
<li><p>If the value is a <code>string</code>, the Transition is redirected to the state named by the string.</p>
</li>
<li><p>If the property is an object with a <code>state</code> and/or <code>params</code> property,
the Transition is redirected to the named <code>state</code> and/or <code>params</code>.</p>
</li>
<li><p>If the value is a <a href="../classes/state.targetstate.html">TargetState</a> the Transition is redirected to the <code>TargetState</code></p>
</li>
<li><p>If the property is a function:</p>
<ul>
<li>The function is called with the current <a href="../classes/transition.transition-1.html">Transition</a></li>
<li>The return value is processed using the previously mentioned rules.</li>
<li>If the return value is a promise, the promise is waited for, then the resolved async value is processed using the same rules.</li>
</ul>
</li>
</ul>
<p>Note: <code>redirectTo</code> is processed as an <code>onStart</code> hook, before <code>LAZY</code> resolves.
If your redirect function relies on resolve data, get the <a href="../classes/transition.transition-1.html#injector">Transition.injector</a> and get a
promise for the resolve data using <a href="core.uiinjector.html#getasync">UIInjector.getAsync</a>.</p>
<h4 id="example-">Example:</h4>
<pre><code class="lang-js"><span class="hljs-comment">// a string</span>
.state(<span class="hljs-string">'A'</span>, {
<span class="hljs-attr">redirectTo</span>: <span class="hljs-string">'A.B'</span>
})
<span class="hljs-comment">// a {state, params} object</span>
.state(<span class="hljs-string">'C'</span>, {
<span class="hljs-attr">redirectTo</span>: { <span class="hljs-attr">state</span>: <span class="hljs-string">'C.D'</span>, <span class="hljs-attr">params</span>: { <span class="hljs-attr">foo</span>: <span class="hljs-string">'index'</span> } }
})
<span class="hljs-comment">// a fn</span>
.state(<span class="hljs-string">'E'</span>, {
<span class="hljs-attr">redirectTo</span>: <span class="hljs-function"><span class="hljs-params">()</span> =></span> <span class="hljs-string">"A"</span>
})
<span class="hljs-comment">// a fn conditionally returning a {state, params}</span>
.state(<span class="hljs-string">'F'</span>, {
<span class="hljs-attr">redirectTo</span>: <span class="hljs-function">(<span class="hljs-params">trans</span>) =></span> {
<span class="hljs-keyword">if</span> (trans.params().foo < <span class="hljs-number">10</span>)
<span class="hljs-keyword">return</span> { <span class="hljs-attr">state</span>: <span class="hljs-string">'F'</span>, <span class="hljs-attr">params</span>: { <span class="hljs-attr">foo</span>: <span class="hljs-number">10</span> } };
}
})
<span class="hljs-comment">// a fn returning a promise for a redirect</span>
.state(<span class="hljs-string">'G'</span>, {
<span class="hljs-attr">redirectTo</span>: <span class="hljs-function">(<span class="hljs-params">trans</span>) =></span> {
<span class="hljs-keyword">let</span> svc = trans.injector().get(<span class="hljs-string">'SomeAsyncService'</span>)
<span class="hljs-keyword">let</span> promise = svc.getAsyncRedirectTo(trans.params.foo);
<span class="hljs-keyword">return</span> promise;
}
})
<span class="hljs-comment">// a fn that fetches resolve data</span>
.state(<span class="hljs-string">'G'</span>, {
<span class="hljs-attr">redirectTo</span>: <span class="hljs-function">(<span class="hljs-params">trans</span>) =></span> {
<span class="hljs-comment">// getAsync tells the resolve to load</span>
<span class="hljs-keyword">let</span> resolvePromise = trans.injector().getAsync(<span class="hljs-string">'SomeResolve'</span>)
<span class="hljs-keyword">return</span> resolvePromise.then(<span class="hljs-function"><span class="hljs-params">resolveData</span> =></span> resolveData === <span class="hljs-string">'login'</span> ? <span class="hljs-string">'login'</span> : <span class="hljs-literal">null</span>);
}
})
</code></pre>
</div>
</div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/ui-router/core/blob/9bb7287/src/state/interface.ts#L506">ui-router-core/src/state/interface.ts:506</a></li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface">
<a name="reloadonsearch" class="tsd-anchor"></a>
<!--
<h3><span class="tsd-flag ts-flagOptional">Optional</span> reload<wbr>OnSearch</h3>
-->
<div class="tsd-signature tsd-kind-icon">reload<wbr>OnSearch<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">boolean</span></div>
<div class="tsd-declaration">
<div class="tsd-comment tsd-typography">
<dl class="tsd-comment-tags">
<dt>deprecated</dt>
<dd><p>define individual parameters as <a href="params.paramdeclaration.html#dynamic">ParamDeclaration.dynamic</a></p>
</dd>
</dl>
</div>
</div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/ui-router/core/blob/9bb7287/src/state/interface.ts#L705">ui-router-core/src/state/interface.ts:705</a></li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface">
<a name="resolve" class="tsd-anchor"></a>
<!--
<h3><span class="tsd-flag ts-flagOptional">Optional</span> resolve</h3>
-->
<div class="tsd-signature tsd-kind-icon">resolve<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">ResolveTypes[]</span><span class="tsd-signature-symbol"> | </span><span class="tsd-signature-type">object</span> <div class="tsd-header">
<p> Resolve - a mechanism to asynchronously fetch data, participating in the Transition lifecycle </p>
</div>
</div>
<div class="tsd-declaration">
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>Resolve - a mechanism to asynchronously fetch data, participating in the Transition lifecycle</p>
</div>
<p>The <code>resolve:</code> property defines data (or other dependencies) to be fetched asynchronously when the state is being entered.
After the data is fetched, it may be used in views, transition hooks or other resolves that belong to this state.
The data may also be used in any views or resolves that belong to nested states.</p>
<h3 id="as-an-array">As an array</h3>
<p>Each array element should be a <a href="resolve.resolvableliteral.html">ResolvableLiteral</a> object.</p>
<h4 id="example-">Example:</h4>
<p>The <code>user</code> resolve injects the current <code>Transition</code> and the <code>UserService</code> (using its token, which is a string).
The [[ResolvableLiteral.resolvePolicy]] sets how the resolve is processed.
The <code>user</code> data, fetched asynchronously, can then be used in a view.</p>
<pre><code class="lang-js">var state = {
name: 'user',
url: '/user/:userId
resolve: [
{
token: 'user',
policy: { when: 'EAGER' },
deps: ['UserService', Transition],
resolveFn: (userSvc, trans) => userSvc.fetchUser(trans.params().userId) },
}
]
}
</code></pre>
<p>Note: an Angular 2 style <a href="https://angular.io/docs/ts/latest/cookbook/dependency-injection.html#!#provide"><code>useFactory</code> provider literal</a>
may also be used. See <a href="resolve.providerlike.html">ProviderLike</a>.</p>
<h4 id="example-">Example:</h4>
<pre><code><span class="hljs-string">resolve:</span> [
{ <span class="hljs-string">provide:</span> <span class="hljs-string">'token'</span>, <span class="hljs-string">useFactory:</span> (http) => http.get(<span class="hljs-string">'/'</span>), <span class="hljs-string">deps:</span> [ Http ] },
]
</code></pre><h3 id="as-an-object">As an object</h3>
<p>The <code>resolve</code> property may be an object where:</p>
<ul>
<li>Each key (string) is the name of the dependency.</li>
<li>Each value (function) is an injectable function which returns the dependency, or a promise for the dependency.</li>
</ul>
<p>This style is based on AngularJS injectable functions, but can be used with any UI-Router implementation.
If your code will be minified, the function should be <a href="https://docs.angularjs.org/guide/di#dependency-annotation">"annotated" in the AngularJS manner</a>.</p>
<h4 id="angularjs-example-">AngularJS Example:</h4>
<pre><code class="lang-js">resolve: {
<span class="hljs-comment">// If you inject `myStateDependency` into a controller, you'll get "abc"</span>
myStateDependency: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">return</span> <span class="hljs-string">"abc"</span>;
},
<span class="hljs-comment">// Dependencies are annotated in "Inline Array Annotation"</span>
myAsyncData: [<span class="hljs-string">'$http'</span>, <span class="hljs-string">'$transition$'</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">$http, $transition$</span>) </span>{
<span class="hljs-comment">// Return a promise (async) for the data</span>
<span class="hljs-keyword">return</span> $http.get(<span class="hljs-string">"/foos/"</span> + $transition$.params().foo);
}]
}
</code></pre>
<p>Note: You cannot specify a policy for each Resolvable, nor can you use non-string
tokens when using the object style <code>resolve:</code> block.</p>
<h3 id="lifecycle">Lifecycle</h3>
<p>Since a resolve function can return a promise, the router will delay entering the state until the promises are ready.
If any of the promises are rejected, the Transition is aborted with an Error.</p>
<p>By default, resolves for a state are fetched just before that state is entered.
Note that only states which are being <em>entered</em> during the <code>Transition</code> have their resolves fetched.
States that are "retained" do not have their resolves re-fetched.</p>
<p>If you are currently in a parent state <code>parent</code> and are transitioning to a child state <code>parent.child</code>, the
previously resolved data for state <code>parent</code> can be injected into <code>parent.child</code> without delay.</p>
<p>Any resolved data for <code>parent.child</code> is retained until <code>parent.child</code> is exited, e.g., by transitioning back to the <code>parent</code> state.</p>
<p>Because of this scoping and lifecycle, resolves are a great place to fetch your application's primary data.</p>
<h3 id="injecting-resolves-into-other-things">Injecting resolves into other things</h3>
<p>During a transition, Resolve data can be injected into:</p>
<ul>
<li>Views (the components which fill a <code>ui-view</code> tag)</li>
<li>Transition Hooks</li>
<li>Other resolves (a resolve may depend on asynchronous data from a different resolve)</li>
</ul>
<h3 id="injecting-other-things-into-resolves">Injecting other things into resolves</h3>
<p>Resolve functions usually have dependencies on some other API(s).
The dependencies are usually declared and injected into the resolve function.
A common pattern is to inject a custom service such as <code>UserService</code>.
The resolve then delegates to a service method, such as <code>UserService.list()</code>;</p>
<h4 id="special-injectable-tokens">Special injectable tokens</h4>
<ul>
<li><code>UIRouter</code>: The <a href="ng1.__uirouter_core_lib_router_.uirouter.html">UIRouter</a> instance which has references to all the UI-Router services.</li>
<li><code>Transition</code>: The current <a href="../classes/transition.transition-1.html">Transition</a> object; information and API about the current transition, such as
"to" and "from" State Parameters and transition options.</li>
<li><code>'$transition$'</code>: A string alias for the <code>Transition</code> injectable</li>
<li><code>'$state$'</code>: For <code>onEnter</code>/<code>onExit</code>/<code>onRetain</code>, the state being entered/exited/retained.</li>
<li>Other resolve tokens: A resolve can depend on another resolve, either from the same state, or from any parent state.</li>
</ul>
<h4 id="example-">Example:</h4>
<pre><code class="lang-js"><span class="hljs-comment">// Injecting a resolve into another resolve</span>
resolve: [
<span class="hljs-comment">// Define a resolve 'allusers' which delegates to the UserService.list()</span>
<span class="hljs-comment">// which returns a promise (async) for all the users</span>
{ <span class="hljs-attr">provide</span>: <span class="hljs-string">'allusers'</span>, <span class="hljs-attr">useFactory</span>: <span class="hljs-function">(<span class="hljs-params">UserService</span>) =></span> UserService.list(), <span class="hljs-attr">deps</span>: [UserService] },
<span class="hljs-comment">// Define a resolve 'user' which depends on the allusers resolve.</span>
<span class="hljs-comment">// This resolve function is not called until 'allusers' is ready.</span>
{ <span class="hljs-attr">provide</span>: <span class="hljs-string">'user'</span>, (allusers, trans) => _.find(allusers, trans.params().userId, <span class="hljs-attr">deps</span>: [<span class="hljs-string">'allusers'</span>, Transition] }
}
</code></pre>
</div>
</div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/ui-router/core/blob/9bb7287/src/state/interface.ts#L312">ui-router-core/src/state/interface.ts:312</a></li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface">
<a name="resolvepolicy" class="tsd-anchor"></a>
<!--
<h3><span class="tsd-flag ts-flagOptional">Optional</span> resolve<wbr>Policy</h3>
-->
<div class="tsd-signature tsd-kind-icon">resolve<wbr>Policy<span class="tsd-signature-symbol">:</span> <a href="resolve.resolvepolicy.html" class="tsd-signature-type">ResolvePolicy</a> <div class="tsd-header">
<p> Sets the resolve policy defaults for all resolves on this state </p>
</div>
</div>
<div class="tsd-declaration">
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>Sets the resolve policy defaults for all resolves on this state</p>
</div>
<p>This should be an <a href="resolve.resolvepolicy.html">ResolvePolicy</a> object.</p>
<p>It can contain the following optional keys/values:</p>
<ul>
<li><code>when</code>: (optional) defines when the resolve is fetched. Accepted values: "LAZY" or "EAGER"</li>
<li><code>async</code>: (optional) if the transition waits for the resolve. Accepted values: "WAIT", "NOWAIT", "RXWAIT"</li>
</ul>
<p>See <a href="resolve.resolvepolicy.html">ResolvePolicy</a> for more details.</p>
</div>
</div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/ui-router/core/blob/9bb7287/src/state/interface.ts#L326">ui-router-core/src/state/interface.ts:326</a></li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface">
<a name="url" class="tsd-anchor"></a>
<!--
<h3><span class="tsd-flag ts-flagOptional">Optional</span> url</h3>
-->
<div class="tsd-signature tsd-kind-icon">url<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">string</span> <div class="tsd-header">
<p> The url fragment for the state </p>
</div>
</div>
<div class="tsd-declaration">
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>The url fragment for the state</p>
</div>
<p>A URL fragment (with optional parameters) which is used to match the browser location with this state.</p>
<p>This fragment will be appended to the parent state's URL in order to build up the overall URL for this state.
See <a href="../classes/url.urlmatcher.html">UrlMatcher</a> for details on acceptable patterns.</p>
<dl class="tsd-comment-tags">
<dt>examples</dt>
<dd><pre><code class="lang-js">
url: <span class="hljs-string">"/home"</span>
<span class="hljs-comment">// Define a parameter named 'userid'</span>
url: <span class="hljs-string">"/users/:userid"</span>
<span class="hljs-comment">// param 'bookid' has a custom regexp</span>
url: <span class="hljs-string">"/books/{bookid:[a-zA-Z_-]}"</span>
<span class="hljs-comment">// param 'categoryid' is of type 'int'</span>
url: <span class="hljs-string">"/books/{categoryid:int}"</span>
<span class="hljs-comment">// two parameters for this state</span>
url: <span class="hljs-string">"/books/{publishername:string}/{categoryid:int}"</span>
<span class="hljs-comment">// Query parameters</span>
url: <span class="hljs-string">"/messages?before&after"</span>
<span class="hljs-comment">// Query parameters of type 'date'</span>
url: <span class="hljs-string">"/messages?{before:date}&{after:date}"</span>
<span class="hljs-comment">// Path and query parameters</span>
url: <span class="hljs-string">"/messages/:mailboxid?{before:date}&{after:date}"</span>
</code></pre>
</dd>
</dl>
</div>
</div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/ui-router/core/blob/9bb7287/src/state/interface.ts#L356">ui-router-core/src/state/interface.ts:356</a></li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface">
<a name="views" class="tsd-anchor"></a>
<!--
<h3><span class="tsd-flag ts-flagOptional">Optional</span> views</h3>
-->
<div class="tsd-signature tsd-kind-icon">views<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">object</span> <div class="tsd-header">
<p> Named views </p>
</div>
</div>
<div class="tsd-declaration">
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>Named views</p>
</div>
<p>An optional object which defines multiple views, or explicitly targets specific named ui-views.</p>
<ul>
<li>What is a view config</li>
<li>What is a ui-view</li>
<li>Shorthand controller/template</li>
<li><p>Incompatible with ^</p>
<p>Examples:</p>
<p>Targets three named ui-views in the parent state's template</p>
</li>
</ul>
<h4 id="example-">Example:</h4>
<pre><code class="lang-js">views: {
<span class="hljs-attr">header</span>: {
<span class="hljs-attr">controller</span>: <span class="hljs-string">"headerCtrl"</span>,
<span class="hljs-attr">templateUrl</span>: <span class="hljs-string">"header.html"</span>
}, <span class="hljs-attr">body</span>: {
<span class="hljs-attr">controller</span>: <span class="hljs-string">"bodyCtrl"</span>,
<span class="hljs-attr">templateUrl</span>: <span class="hljs-string">"body.html"</span>
}, <span class="hljs-attr">footer</span>: {
<span class="hljs-attr">controller</span>: <span class="hljs-string">"footCtrl"</span>,
<span class="hljs-attr">templateUrl</span>: <span class="hljs-string">"footer.html"</span>
}
}
</code></pre>
<dl class="tsd-comment-tags">
<dt>example</dt>
<dd><pre><code class="lang-js"><span class="hljs-comment">// Targets named ui-view="header" from ancestor state 'top''s template, and</span>
<span class="hljs-comment">// named `ui-view="body" from parent state's template.</span>
views: {
<span class="hljs-string">'header@top'</span>: {
<span class="hljs-attr">controller</span>: <span class="hljs-string">"msgHeaderCtrl"</span>,
<span class="hljs-attr">templateUrl</span>: <span class="hljs-string">"msgHeader.html"</span>
}, <span class="hljs-string">'body'</span>: {
<span class="hljs-attr">controller</span>: <span class="hljs-string">"messagesCtrl"</span>,
<span class="hljs-attr">templateUrl</span>: <span class="hljs-string">"messages.html"</span>
}
}
</code></pre>
</dd>
</dl>
</div>
</div>
<div class="tsd-type-declaration">
<h4>Type declaration</h4>
<ul class="tsd-parameters">
<li class="tsd-parameter-index-signature">
<h5><span class="tsd-signature-symbol">[</span>key: <span class="tsd-signature-type">string</span><span class="tsd-signature-symbol">]: </span><a href="state._viewdeclaration.html" class="tsd-signature-type">_ViewDeclaration</a></h5>
</li>
</ul>
</div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/ui-router/core/blob/9bb7287/src/state/interface.ts#L425">ui-router-core/src/state/interface.ts:425</a></li>
</ul>
</aside>
</section>
</section>
</div>
<div class="col-4 col-menu menu-sticky-wrap menu-highlight">
<nav class="tsd-navigation primary">
<ul>
<li class="globals ">
<a href="../index.html"><em>@uirouter/angularjs</em></a>
</li>
<li class="label tsd-is-external">
<span>Public API</span>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/core.html">core</a>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/injectables.html">injectables</a>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/ng1.html">ng1</a>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/ng1_state_events.html">ng1_<wbr>state_<wbr>events</a>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/params.html">params</a>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/resolve.html">resolve</a>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/transition.html">transition</a>
</li>
<li class="label tsd-is-external">
<span>Internal UI-<wbr><wbr>Router API</span>
</li>
<li class=" tsd-kind-external-module tsd-is-external">
<a href="../modules/common.html">common</a>
</li>
<li class=" tsd-kind-external-module tsd-is-external">
<a href="../modules/common_hof.html">common_<wbr>hof</a>
</li>
<li class=" tsd-kind-external-module tsd-is-external">
<a href="../modules/common_predicates.html">common_<wbr>predicates</a>
</li>
<li class=" tsd-kind-external-module tsd-is-external">
<a href="../modules/common_strings.html">common_<wbr>strings</a>
</li>
<li class=" tsd-kind-external-module tsd-is-external">
<a href="../modules/directives.html">directives</a>
</li>
<li class=" tsd-kind-external-module tsd-is-external">
<a href="../modules/hooks.html">hooks</a>
</li>
<li class=" tsd-kind-external-module tsd-is-external">
<a href="../modules/path.html">path</a>
</li>
<li class="current tsd-kind-external-module tsd-is-external">
<a href="../modules/state.html">state</a>
</li>
<li class=" tsd-kind-external-module tsd-is-external">
<a href="../modules/trace.html">trace</a>
</li>
<li class=" tsd-kind-external-module tsd-is-external">
<a href="../modules/url.html">url</a>
</li>
<li class=" tsd-kind-external-module tsd-is-external">
<a href="../modules/vanilla.html">vanilla</a>
</li>
<li class=" tsd-kind-external-module tsd-is-external">
<a href="../modules/view.html">view</a>
</li>
</ul>
</nav>
<nav class="tsd-navigation secondary menu-sticky">
<ul class="before-current">
<li class=" tsd-kind-class tsd-parent-kind-external-module tsd-is-external">
<a href="../classes/state.statebuilder.html" class="tsd-kind-icon">State<wbr>Builder</a>
</li>
<li class=" tsd-kind-class tsd-parent-kind-external-module tsd-is-external">
<a href="../classes/state.statematcher.html" class="tsd-kind-icon">State<wbr>Matcher</a>
</li>
<li class=" tsd-kind-class tsd-parent-kind-external-module">
<a href="../classes/state.stateobject.html" class="tsd-kind-icon">State<wbr>Object</a>
</li>
<li class=" tsd-kind-class tsd-parent-kind-external-module tsd-is-external">
<a href="../classes/state.statequeuemanager.html" class="tsd-kind-icon">State<wbr>Queue<wbr>Manager</a>
</li>
<li class=" tsd-kind-class tsd-parent-kind-external-module">
<a href="../classes/state.stateregistry.html" class="tsd-kind-icon">State<wbr>Registry</a>
</li>
<li class=" tsd-kind-class tsd-parent-kind-external-module">
<a href="../classes/state.stateservice.html" class="tsd-kind-icon">State<wbr>Service</a>
</li>
<li class=" tsd-kind-class tsd-parent-kind-external-module">
<a href="../classes/state.targetstate.html" class="tsd-kind-icon">Target<wbr>State</a>
</li>
<li class=" tsd-kind-interface tsd-parent-kind-external-module tsd-is-external tsd-is-not-exported">
<a href="state.builders.html" class="tsd-kind-icon">Builders</a>
</li>
<li class=" tsd-kind-interface tsd-parent-kind-external-module">
<a href="state.hrefoptions.html" class="tsd-kind-icon">Href<wbr>Options</a>
</li>
<li class=" tsd-kind-interface tsd-parent-kind-external-module">
<a href="state.lazyloadresult.html" class="tsd-kind-icon">Lazy<wbr>Load<wbr>Result</a>
</li>
</ul>
<ul class="current">
<li class="current tsd-kind-interface tsd-parent-kind-external-module">
<a href="state.statedeclaration.html" class="tsd-kind-icon">State<wbr>Declaration</a>
<ul>
<li class=" tsd-kind-property tsd-parent-kind-interface">
<a href="state.statedeclaration.html#__state" class="tsd-kind-icon">$$state</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface">
<a href="state.statedeclaration.html#abstract" class="tsd-kind-icon">abstract</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface">
<a href="state.statedeclaration.html#data" class="tsd-kind-icon">data</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface">
<a href="state.statedeclaration.html#lazyload" class="tsd-kind-icon">lazy<wbr>Load</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface">
<a href="state.statedeclaration.html#name" class="tsd-kind-icon">name</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface">
<a href="state.statedeclaration.html#onenter" class="tsd-kind-icon">on<wbr>Enter</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface">
<a href="state.statedeclaration.html#onexit" class="tsd-kind-icon">on<wbr>Exit</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface">
<a href="state.statedeclaration.html#onretain" class="tsd-kind-icon">on<wbr>Retain</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface">
<a href="state.statedeclaration.html#params" class="tsd-kind-icon">params</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface">
<a href="state.statedeclaration.html#parent" class="tsd-kind-icon">parent</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface">
<a href="state.statedeclaration.html#redirectto" class="tsd-kind-icon">redirect<wbr>To</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface">
<a href="state.statedeclaration.html#reloadonsearch" class="tsd-kind-icon">reload<wbr>OnSearch</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface">
<a href="state.statedeclaration.html#resolve" class="tsd-kind-icon">resolve</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface">
<a href="state.statedeclaration.html#resolvepolicy" class="tsd-kind-icon">resolve<wbr>Policy</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface">
<a href="state.statedeclaration.html#url" class="tsd-kind-icon">url</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface">
<a href="state.statedeclaration.html#views" class="tsd-kind-icon">views</a>
</li>
</ul>
</li>
</ul>
<ul class="after-current">
<li class=" tsd-kind-interface tsd-parent-kind-external-module">
<a href="state.targetstatedef.html" class="tsd-kind-icon">Target<wbr>State<wbr>Def</a>
</li>
<li class=" tsd-kind-interface tsd-parent-kind-external-module tsd-is-external">
<a href="state.transitionpromise.html" class="tsd-kind-icon">Transition<wbr>Promise</a>
</li>
<li class=" tsd-kind-interface tsd-parent-kind-external-module tsd-is-external">
<a href="state._viewdeclaration.html" class="tsd-kind-icon">_<wbr>View<wbr>Declaration</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-external-module tsd-is-external">
<a href="../modules/state.html#builderfunction" class="tsd-kind-icon">Builder<wbr>Function</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-external-module">
<a href="../modules/state.html#oninvalidcallback" class="tsd-kind-icon">On<wbr>Invalid<wbr>Callback</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-external-module">
<a href="../modules/state.html#redirecttoresult" class="tsd-kind-icon">Redirect<wbr>ToResult</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-external-module">
<a href="../modules/state.html#resolvetypes" class="tsd-kind-icon">Resolve<wbr>Types</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-external-module">
<a href="../modules/state.html#stateorname" class="tsd-kind-icon">State<wbr>OrName</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-external-module">
<a href="../modules/state.html#stateregistrylistener" class="tsd-kind-icon">State<wbr>Registry<wbr>Listener</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-external-module">
<a href="../modules/state.html#_statedeclaration" class="tsd-kind-icon">_<wbr>State<wbr>Declaration</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-external-module tsd-is-external tsd-is-not-exported">
<a href="../modules/state.html#databuilder" class="tsd-kind-icon">data<wbr>Builder</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-external-module tsd-is-external tsd-is-not-exported">
<a href="../modules/state.html#getnavigablebuilder" class="tsd-kind-icon">get<wbr>Navigable<wbr>Builder</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-external-module tsd-is-external tsd-is-not-exported">
<a href="../modules/state.html#getparamsbuilder" class="tsd-kind-icon">get<wbr>Params<wbr>Builder</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-external-module tsd-is-external tsd-is-not-exported">
<a href="../modules/state.html#geturlbuilder" class="tsd-kind-icon">get<wbr>Url<wbr>Builder</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-external-module tsd-is-external tsd-is-not-exported">
<a href="../modules/state.html#includesbuilder" class="tsd-kind-icon">includes<wbr>Builder</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-external-module tsd-is-external tsd-is-not-exported">
<a href="../modules/state.html#namebuilder" class="tsd-kind-icon">name<wbr>Builder</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-external-module tsd-is-external tsd-is-not-exported">
<a href="../modules/state.html#parseurl" class="tsd-kind-icon">parse<wbr>Url</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-external-module tsd-is-external tsd-is-not-exported">
<a href="../modules/state.html#pathbuilder" class="tsd-kind-icon">path<wbr>Builder</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-external-module tsd-is-external">
<a href="../modules/state.html#resolvablesbuilder" class="tsd-kind-icon">resolvables<wbr>Builder</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-external-module tsd-is-external tsd-is-not-exported">
<a href="../modules/state.html#selfbuilder" class="tsd-kind-icon">self<wbr>Builder</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<footer class="with-border-bottom">
<div class="container">
<h2>Legend</h2>
<div class="tsd-legend-group">
<ul class="tsd-legend">
<li class="tsd-kind-module"><span class="tsd-kind-icon">Module</span></li>
<li class="tsd-kind-object-literal"><span class="tsd-kind-icon">Object literal</span></li>
<li class="tsd-kind-variable"><span class="tsd-kind-icon">Variable</span></li>
<li class="tsd-kind-function"><span class="tsd-kind-icon">Function</span></li>
<li class="tsd-kind-function tsd-has-type-parameter"><span class="tsd-kind-icon">Function with type parameter</span></li>
<li class="tsd-kind-index-signature"><span class="tsd-kind-icon">Index signature</span></li>
<li class="tsd-kind-type-alias"><span class="tsd-kind-icon">Type alias</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-enum"><span class="tsd-kind-icon">Enumeration</span></li>
<li class="tsd-kind-enum-member"><span class="tsd-kind-icon">Enumeration member</span></li>
<li class="tsd-kind-property tsd-parent-kind-enum"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-enum"><span class="tsd-kind-icon">Method</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-interface"><span class="tsd-kind-icon">Interface</span></li>
<li class="tsd-kind-interface tsd-has-type-parameter"><span class="tsd-kind-icon">Interface with type parameter</span></li>
<li class="tsd-kind-constructor tsd-parent-kind-interface"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-interface"><span class="tsd-kind-icon">Method</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-interface"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-class"><span class="tsd-kind-icon">Class</span></li>
<li class="tsd-kind-class tsd-has-type-parameter"><span class="tsd-kind-icon">Class with type parameter</span></li>
<li class="tsd-kind-constructor tsd-parent-kind-class"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class"><span class="tsd-kind-icon">Method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class"><span class="tsd-kind-icon">Accessor</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-class"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-constructor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static property</span></li>
<li class="tsd-kind-call-signature tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static method</span></li>
</ul>
</div>
</div>
</footer>
<div class="container tsd-generator">
<p>Generated using <a href="http://typedoc.io" target="_blank">TypeDoc</a></p>
</div>
<div class="overlay"></div>
<script src="../assets/js/main.js"></script>
<script>if (location.protocol == 'file:') document.write('<script src="../assets/js/search.js"><' + '/script>');</script>
</body>
</html>
|
ui-router/ui-router.github.io
|
_ng1_docs/1.0.16/interfaces/state.statedeclaration.html
|
HTML
|
mit
| 74,961
|
from components.base.automotive_component import AutomotiveComponent
from config import project_registration as proj
from tools.ecu_logging import ECULogger as L
import random
class AbstractECU(AutomotiveComponent):
'''
This abstract class defines the interface of
an ECU as it is found in an automotive network
'''
def __init__(self, sim_env, ecu_id, data_rate):
''' Constructor
Input: sim_env simpy.Environment environment of this component
ecu_id string id of the corresponding AbstractECU
data_rate float datarate of the ecu
Output: -
'''
AutomotiveComponent.__init__(self, sim_env)
self._ABSTRACT_ECU = True
self._ecu_id = ecu_id # ID of the ECU
self.ecuSW = None # what is done
self.ecuHW = None # what is used to make it happen
self.MessageClass = proj.BUS_MSG_CLASS # what kind of messages are exchanged
self.connected_bus = None # Bus that is connected to the ECU
self.data_rate = proj.BUS_ECU_DATARATE # Datarate with which bits are put on the bus
self._effective_datarate = 0 # Bit per second
self._effective_bittime = 0 # seconds
self._jitter = 1
self.startup_delay = False
def set_startup_delay(self, start_time):
''' this method sets the startup delay. When this delay is set
this ECU is activated after the defined start time
Input: start_time float time when the ECU starts running
Output: -
'''
self.startup_delay = start_time
if start_time:
self.ecuHW.transceiver.ecu_is_active = False
def set_jitter(self, jitter_range):
''' sets the jitter which will be multiplied onto each
timeout value. It will be within jitter_range
e.g. jitter_range of 0.1 means that any random value
between 1.0 and 1.1 will be used
Input: jitter_range: float dispersion from 1.0
Output: -
'''
# determine jitter
self._jitter = 1 + (random.random() * jitter_range)
# apply jitter on layers
try: self.ecuSW.comm_mod.physical_lay.transceiver._jitter = self._jitter
except: pass
try: self.ecuSW.comm_mod._jitter = self._jitter
except: pass
try: self.ecuSW.comm_mod.transp_lay._jitter = self._jitter
except: pass
try: self.ecuSW.comm_mod.datalink_lay._jitter = self._jitter
except: pass
try: self.ecuSW.comm_mod.physical_lay.transceiver._jitter = self._jitter
except: pass
try: self.ecuSW.app_lay._jitter = self._jitter
except: pass
def _connect_hw_sw(self):
''' connect all hardware components with their
associated software connections
Input: -
Output: -
'''
# application Layer
self.ecuSW.app_lay.microcontroller = self.ecuHW.mic_controller
# physical and data link layer '''
self.ecuSW.comm_mod.datalink_lay.controller = self.ecuHW.controller
self.ecuSW.comm_mod.physical_lay.transceiver = self.ecuHW.transceiver
self.ecuSW.comm_mod.datalink_lay.effective_bittime = self._effective_bittime
def connect_to(self, bus):
''' connects the bus to the ECU
Input: bus CANBus Bus that will be connected
Output: -
'''
self.ecuHW.transceiver.connect_bus(bus)
self.connected_bus = bus
def get_type_id(self):
''' returns the id of this ECU type
Input: -
Output: ecu_type string type of this ECU; e.g.'TLSECU'
'''
raise NotImplementedError(" get_type_id() was not implemented by class %s" % self.__class__)
def get_rec_buffer_items(self):
''' returns the current content of the receiving buffer
Input: -
Output: rec_buffer list list of items in the receiving buffer
'''
return self.ecuHW.controller.receive_buffer.items
def get_trans_buffer_items(self):
''' returns the current content of the transmit buffer
Input: -
Output: trans_buffer list list of items in the transmit buffer
'''
return self.ecuHW.controller.transmit_buffer.items
def install_hw_filter(self, allowed_items_list):
''' installs a hardware filter that filters all
message ids that are not defined in the passed
list. This filter is applied on the transceiver
Input: allowed_items_list list list of message_ids that are let pass by the transceiver
Output: -
'''
try:
self.ecuHW.transceiver.install_filter(allowed_items_list)
except:
L().log_err(300)
def _GET_ABSTRACT_ECU(self):
''' marker that this is a AbstractECU '''
return self._ABSTRACT_ECU
@property
def ecu_id(self):
return self._ecu_id
@ecu_id.setter
def ecu_id(self, value):
self._ecu_id = value
def set_monitor(self, monitor):
self.monitor = monitor
|
PhilippMundhenk/IVNS
|
ECUSimulation/components/base/ecu/types/abst_ecu.py
|
Python
|
mit
| 5,802
|
---
layout: post
title: "My Trip to India - Day Four"
date: 2015-03-06 11:36:00
categories: travel
tags: india perk
---
Today was probably the best Friday I've had at work in a long while, I didn't get to do a single bit of programming at all, but I am actually okay with that. Today we joined the Bangalore team in a game of cricket. It was a tad hot outside, I'm not a huge heat or sun kinda guy, but overall it was a blast. I still am not sure how to play cricket, but I was able to earn the "American" team a few runs, and I to my understanding we won.. and even if we didn't, I'm still gonna count it as a spiritual win.


After the cricket game, we went to the nearby mall to grab lunch in the food court, and I actually wound up getting McDonalds. First thing I noticed and was quickly reminded of, all the items were chicken or vegetable based due to beef not being sold, so I went with a McChicken instead of my usual Big Mac. After that it was off to the office.
I knew today was Holi, and was expecting to be covered in color at some point in time. What I wasn't expecting was being ambushed by the Bangalore team and being just covered head to toe in the bright neon chalk. Either way, it was awesome, and such an amazing experience and celebration. Thanks to Abin for the following photos from the celebration.


After Holi celebrations, and a much needed shower, I finally got a chance to go to the rooftop bar to get a drink or two and check out the bar. Let me tell you, this bar looks awesome. Some of the designs I would totally but in my house... if I lived in a house instead of an apartment... and if I could even afford the decorations.. let alone the house. It was definitely a nice place to chill and hang out with a few coworkers before dinner.



But after a nice dinner and conversation with my boss and the company CEO, I am tired and ready to head to bed. We have a long day tomorrow visiting an orphanage, and swinging by the office to get some work done. Oh and I think some fun, playtime things as well after working... though I find programming fun so work is in itself pretty fun.
|
hskrasek/hskrasek.github.io
|
_posts/2015-03-06-my-trip-to-india-day-four.markdown
|
Markdown
|
mit
| 3,081
|
import Ember from 'ember';
import RouteChildrenMixin from '../../../mixins/route-children';
import { module, test } from 'qunit';
module('Unit | Mixin | route children');
// Replace this with your real tests.
test('it works', function(assert) {
var RouteChildrenObject = Ember.Object.extend(RouteChildrenMixin);
var subject = RouteChildrenObject.create();
assert.ok(subject);
});
|
dhilipsiva/test
|
emdj/tests/unit/mixins/route-children-test.js
|
JavaScript
|
mit
| 388
|
<?php
// HealthSystem\HealthSystemBundle\Form\Type\Base\TreatmentTypeBase.php
/************************************************************************************************
** THIS IS AN AUTOMATICALLY GENERATED BASE FILE AND SHOULD NOT BE MANUALLY EDITED **
** All user content should be placed within <user-additions part="(name)"></user-additions> **
************************************************************************************************/
/*
* This file was automatically generated with 'Autocode'
* by Jose Diaz-Angulo <jose@diazangulo.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with the package's source code.
*/
namespace HealthSystem\HealthSystemBundle\Form\Type\Base;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use HealthSystem\HealthSystemBundle\Form\Type\SymptomType;
use HealthSystem\HealthSystemBundle\Form\Type\IllnessType;
abstract class TreatmentTypeBase extends AbstractType
{
/**
* @var array Form fields
*/
protected $fields = [];
/**
* @var string
*/
protected $defaultOptionsDataClass = 'HealthSystem\HealthSystemBundle\Entity\Treatment';
/**
* @var null|string|callable
*/
protected $defaultOptionsEmptyData;
/**
* @param array $arguments Arguments to pass down to the ParentFormConstructor method
*
* @return SymptomType
*/
protected function getSymptomNameFieldParentFormConstructor($arguments)
{
return new SymptomType();
}
/**
* @param array $arguments Arguments to pass down to the ParentFormConstructor method
*
* @return array
*/
public function getSymptomNameField($arguments = [])
{
return [
'name' => 'symptomName',
'type' => 'entity',
'options' => [
'class' => 'HealthSystemBundle:Symptom',
'max_length' => 50,
'multiple' => false, // ManyToOne
'error_bubbling' => true
]
];
}
/**
* @param array $arguments Arguments to pass down to the ParentFormConstructor method
*
* @return IllnessType
*/
protected function getIllnessCodeFieldParentFormConstructor($arguments)
{
return new IllnessType();
}
/**
* @param array $arguments Arguments to pass down to the ParentFormConstructor method
*
* @return array
*/
public function getIllnessCodeField($arguments = [])
{
return [
'name' => 'illnessCode',
'type' => 'entity',
'options' => [
'class' => 'HealthSystemBundle:Illness',
'max_length' => 20,
'multiple' => false, // ManyToOne
'error_bubbling' => true
]
];
}
/**
* @return array
*/
public function getMedicationField()
{
return [
'name' => 'medication',
'type' => 'text',
'options' => [
'required' => false,
'max_length' => 100,
'error_bubbling' => true
]
];
}
/**
* @return array
*/
public function getInstructionsField()
{
return [
'name' => 'instructions',
'type' => 'textarea',
'options' => [
'required' => false,
'error_bubbling' => true
]
];
}
/**
* @return array
*/
public function getSymptomSeverityField()
{
return [
'name' => 'symptomSeverity',
'type' => 'textarea',
'options' => [
'required' => false,
'error_bubbling' => true
]
];
}
/**
* @param string $defaultOptionsDataClass
*/
public function setDefaultOptionsDataClass($defaultOptionsDataClass)
{
$this->defaultOptionsDataClass = $defaultOptionsDataClass;
}
/**
* @return string
*/
public function getDefaultOptionsDataClass()
{
return $this->defaultOptionsDataClass;
}
/**
* @param null|string|callable $defaultOptionsEmptyData
*/
public function setDefaultOptionsEmptyData($defaultOptionsEmptyData)
{
$this->defaultOptionsEmptyData = $defaultOptionsEmptyData;
}
/**
* @return null|string|callable
*/
public function getDefaultOptionsEmptyData()
{
return $this->defaultOptionsEmptyData;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
foreach ($this->fields as $field) {
$builder->add(
$field['name'],
$field['type'],
$field['options']
);
}
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$defaults = [
'data_class' => $this->getDefaultOptionsDataClass()
];
if (null !== $this->getDefaultOptionsEmptyData()) {
$defaults['empty_data'] = $this->getDefaultOptionsEmptyData();
}
$resolver->setDefaults($defaults);
}
public function getName()
{
return 'healthsystem_healthsystem_treatment';
}
public function getFields()
{
return $this->fields;
}
}
|
j-d/draggy-demo
|
src/HealthSystem/HealthSystemBundle/Form/Type/Base/TreatmentTypeBase.php
|
PHP
|
mit
| 5,597
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/api/atom_api_app.h"
#include <string>
#include <vector>
#include "atom/browser/api/atom_api_menu.h"
#include "atom/browser/api/atom_api_session.h"
#include "atom/browser/api/atom_api_web_contents.h"
#include "atom/browser/atom_browser_context.h"
#include "atom/browser/atom_browser_main_parts.h"
#include "atom/browser/browser.h"
#include "atom/browser/login_handler.h"
#include "atom/browser/net/atom_network_delegate.h"
#include "atom/browser/relauncher.h"
#include "atom/common/atom_command_line.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/net_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/node_includes.h"
#include "atom/common/options_switches.h"
#include "atom/common/pepper_flash_util.h"
#include "base/command_line.h"
#include "base/environment.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/path_service.h"
#include "base/strings/string_util.h"
#include "brave/browser/brave_content_browser_client.h"
#include "brightray/browser/brightray_paths.h"
#include "chrome/common/chrome_paths.h"
#include "components/component_updater/component_updater_paths.h"
#include "content/browser/plugin_service_impl.h"
#include "content/public/browser/browser_accessibility_state.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/client_certificate_delegate.h"
#include "content/public/browser/gpu_data_manager.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/render_frame_host.h"
#include "chrome/browser/browser_process.h"
#include "content/public/common/content_switches.h"
#include "native_mate/dictionary.h"
#include "native_mate/object_template_builder.h"
#include "net/ssl/ssl_cert_request_info.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/image/image.h"
#include "base/threading/thread_restrictions.h"
#if defined(OS_WIN)
#include "atom/browser/ui/win/jump_list.h"
#include "base/strings/utf_string_conversions.h"
#endif
#if defined(ENABLE_EXTENSIONS)
#include "atom/browser/api/atom_api_extension.h"
#include "chrome/browser/chrome_notification_types.h"
#include "content/public/browser/notification_types.h"
#endif
using atom::Browser;
namespace mate {
#if defined(OS_WIN)
template<>
struct Converter<Browser::UserTask> {
static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
Browser::UserTask* out) {
mate::Dictionary dict;
if (!ConvertFromV8(isolate, val, &dict))
return false;
if (!dict.Get("program", &(out->program)) ||
!dict.Get("title", &(out->title)))
return false;
if (dict.Get("iconPath", &(out->icon_path)) &&
!dict.Get("iconIndex", &(out->icon_index)))
return false;
dict.Get("arguments", &(out->arguments));
dict.Get("description", &(out->description));
return true;
}
};
using atom::JumpListItem;
using atom::JumpListCategory;
using atom::JumpListResult;
template<>
struct Converter<JumpListItem::Type> {
static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
JumpListItem::Type* out) {
std::string item_type;
if (!ConvertFromV8(isolate, val, &item_type))
return false;
if (item_type == "task")
*out = JumpListItem::Type::TASK;
else if (item_type == "separator")
*out = JumpListItem::Type::SEPARATOR;
else if (item_type == "file")
*out = JumpListItem::Type::FILE;
else
return false;
return true;
}
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
JumpListItem::Type val) {
std::string item_type;
switch (val) {
case JumpListItem::Type::TASK:
item_type = "task";
break;
case JumpListItem::Type::SEPARATOR:
item_type = "separator";
break;
case JumpListItem::Type::FILE:
item_type = "file";
break;
}
return mate::ConvertToV8(isolate, item_type);
}
};
template<>
struct Converter<JumpListItem> {
static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
JumpListItem* out) {
mate::Dictionary dict;
if (!ConvertFromV8(isolate, val, &dict))
return false;
if (!dict.Get("type", &(out->type)))
return false;
switch (out->type) {
case JumpListItem::Type::TASK:
if (!dict.Get("program", &(out->path)) ||
!dict.Get("title", &(out->title)))
return false;
if (dict.Get("iconPath", &(out->icon_path)) &&
!dict.Get("iconIndex", &(out->icon_index)))
return false;
dict.Get("args", &(out->arguments));
dict.Get("description", &(out->description));
return true;
case JumpListItem::Type::SEPARATOR:
return true;
case JumpListItem::Type::FILE:
return dict.Get("path", &(out->path));
}
assert(false);
return false;
}
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
const JumpListItem& val) {
mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
dict.Set("type", val.type);
switch (val.type) {
case JumpListItem::Type::TASK:
dict.Set("program", val.path);
dict.Set("args", val.arguments);
dict.Set("title", val.title);
dict.Set("iconPath", val.icon_path);
dict.Set("iconIndex", val.icon_index);
dict.Set("description", val.description);
break;
case JumpListItem::Type::SEPARATOR:
break;
case JumpListItem::Type::FILE:
dict.Set("path", val.path);
break;
}
return dict.GetHandle();
}
};
template<>
struct Converter<JumpListCategory::Type> {
static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
JumpListCategory::Type* out) {
std::string category_type;
if (!ConvertFromV8(isolate, val, &category_type))
return false;
if (category_type == "tasks")
*out = JumpListCategory::Type::TASKS;
else if (category_type == "frequent")
*out = JumpListCategory::Type::FREQUENT;
else if (category_type == "recent")
*out = JumpListCategory::Type::RECENT;
else if (category_type == "custom")
*out = JumpListCategory::Type::CUSTOM;
else
return false;
return true;
}
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
JumpListCategory::Type val) {
std::string category_type;
switch (val) {
case JumpListCategory::Type::TASKS:
category_type = "tasks";
break;
case JumpListCategory::Type::FREQUENT:
category_type = "frequent";
break;
case JumpListCategory::Type::RECENT:
category_type = "recent";
break;
case JumpListCategory::Type::CUSTOM:
category_type = "custom";
break;
}
return mate::ConvertToV8(isolate, category_type);
}
};
template<>
struct Converter<JumpListCategory> {
static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
JumpListCategory* out) {
mate::Dictionary dict;
if (!ConvertFromV8(isolate, val, &dict))
return false;
if (dict.Get("name", &(out->name)) && out->name.empty())
return false;
if (!dict.Get("type", &(out->type))) {
if (out->name.empty())
out->type = JumpListCategory::Type::TASKS;
else
out->type = JumpListCategory::Type::CUSTOM;
}
if ((out->type == JumpListCategory::Type::TASKS) ||
(out->type == JumpListCategory::Type::CUSTOM)) {
if (!dict.Get("items", &(out->items)))
return false;
}
return true;
}
};
// static
template<>
struct Converter<JumpListResult> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, JumpListResult val) {
std::string result_code;
switch (val) {
case JumpListResult::SUCCESS:
result_code = "ok";
break;
case JumpListResult::ARGUMENT_ERROR:
result_code = "argumentError";
break;
case JumpListResult::GENERIC_ERROR:
result_code = "error";
break;
case JumpListResult::CUSTOM_CATEGORY_SEPARATOR_ERROR:
result_code = "invalidSeparatorError";
break;
case JumpListResult::MISSING_FILE_TYPE_REGISTRATION_ERROR:
result_code = "fileTypeRegistrationError";
break;
case JumpListResult::CUSTOM_CATEGORY_ACCESS_DENIED_ERROR:
result_code = "customCategoryAccessDeniedError";
break;
}
return ConvertToV8(isolate, result_code);
}
};
#endif
template<>
struct Converter<Browser::LoginItemSettings> {
static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
Browser::LoginItemSettings* out) {
mate::Dictionary dict;
if (!ConvertFromV8(isolate, val, &dict))
return false;
dict.Get("openAtLogin", &(out->open_at_login));
dict.Get("openAsHidden", &(out->open_as_hidden));
return true;
}
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
Browser::LoginItemSettings val) {
mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
dict.Set("openAtLogin", val.open_at_login);
dict.Set("openAsHidden", val.open_as_hidden);
dict.Set("restoreState", val.restore_state);
dict.Set("wasOpenedAtLogin", val.opened_at_login);
dict.Set("wasOpenedAsHidden", val.opened_as_hidden);
return dict.GetHandle();
}
};
template<>
struct Converter<content::CertificateRequestResultType> {
static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
content::CertificateRequestResultType* out) {
std::string item_type;
if (!ConvertFromV8(isolate, val, &item_type))
return false;
if (item_type == "continue")
*out = content::CertificateRequestResultType::CERTIFICATE_REQUEST_RESULT_TYPE_CONTINUE;
else if (item_type == "cancel")
*out = content::CertificateRequestResultType::CERTIFICATE_REQUEST_RESULT_TYPE_CANCEL;
else if (item_type == "deny")
*out = content::CertificateRequestResultType::CERTIFICATE_REQUEST_RESULT_TYPE_DENY;
else
return false;
return true;
}
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
content::CertificateRequestResultType val) {
std::string item_type;
switch (val) {
case content::CertificateRequestResultType::CERTIFICATE_REQUEST_RESULT_TYPE_CONTINUE:
item_type = "continue";
break;
case content::CertificateRequestResultType::CERTIFICATE_REQUEST_RESULT_TYPE_CANCEL:
item_type = "cancel";
break;
case content::CertificateRequestResultType::CERTIFICATE_REQUEST_RESULT_TYPE_DENY:
item_type = "deny";
break;
}
return mate::ConvertToV8(isolate, item_type);
}
};
} // namespace mate
namespace atom {
namespace api {
namespace {
// Return the path constant from string.
int GetPathConstant(const std::string& name) {
if (name == "appData")
return brightray::DIR_APP_DATA;
else if (name == "userData")
return brightray::DIR_USER_DATA;
else if (name == "cache")
return brightray::DIR_CACHE;
else if (name == "userCache")
return brightray::DIR_USER_CACHE;
else if (name == "home")
return base::DIR_HOME;
else if (name == "temp")
return base::DIR_TEMP;
else if (name == "userDesktop" || name == "desktop")
return base::DIR_USER_DESKTOP;
else if (name == "exe")
return base::FILE_EXE;
else if (name == "module")
return base::FILE_MODULE;
else if (name == "documents")
return chrome::DIR_USER_DOCUMENTS;
else if (name == "downloads")
return chrome::DIR_DEFAULT_DOWNLOADS;
else if (name == "music")
return chrome::DIR_USER_MUSIC;
else if (name == "pictures")
return chrome::DIR_USER_PICTURES;
else if (name == "videos")
return chrome::DIR_USER_VIDEOS;
else if (name == "pepperFlashSystemPlugin")
return chrome::FILE_PEPPER_FLASH_SYSTEM_PLUGIN;
else if (name == "widevineCDMAdapter")
return chrome::FILE_WIDEVINE_CDM_ADAPTER;
else if (name == "extensionsDir")
return component_updater::DIR_COMPONENT_USER;
else
return -1;
}
bool NotificationCallbackWrapper(
const ProcessSingleton::NotificationCallback& callback,
const base::CommandLine::StringVector& cmd,
const base::FilePath& cwd) {
// Make sure the callback is called after app gets ready.
if (Browser::Get()->is_ready()) {
callback.Run(cmd, cwd);
} else {
scoped_refptr<base::SingleThreadTaskRunner> task_runner(
base::ThreadTaskRunnerHandle::Get());
task_runner->PostTask(
FROM_HERE, base::Bind(base::IgnoreResult(callback), cmd, cwd));
}
// ProcessSingleton needs to know whether current process is quiting.
return !Browser::Get()->is_shutting_down();
}
void OnClientCertificateSelected(
v8::Isolate* isolate,
std::shared_ptr<content::ClientCertificateDelegate> delegate,
mate::Arguments* args) {
mate::Dictionary cert_data;
if (!args->GetNext(&cert_data)) {
args->ThrowError();
return;
}
std::string data;
if (!cert_data.Get("data", &data))
return;
auto certs = net::X509Certificate::CreateCertificateListFromBytes(
data.c_str(), data.length(), net::X509Certificate::FORMAT_AUTO);
if (certs.size() > 0)
delegate->ContinueWithCertificate(certs[0].get());
}
void PassLoginInformation(scoped_refptr<LoginHandler> login_handler,
mate::Arguments* args) {
base::string16 username, password;
if (args->GetNext(&username) && args->GetNext(&password))
login_handler->Login(username, password);
else
login_handler->CancelAuth();
}
#if defined(USE_NSS_CERTS)
int ImportIntoCertStore(
CertificateManagerModel* model,
const base::DictionaryValue& options) {
std::string file_data, cert_path;
base::string16 password;
net::CertificateList imported_certs;
int rv = -1;
options.GetString("certificate", &cert_path);
options.GetString("password", &password);
if (!cert_path.empty()) {
if (base::ReadFileToString(base::FilePath(cert_path), &file_data)) {
auto module = model->cert_db()->GetPublicModule();
rv = model->ImportFromPKCS12(module,
file_data,
password,
true,
&imported_certs);
if (imported_certs.size() > 1) {
auto it = imported_certs.begin();
++it; // skip first which would be the client certificate.
for (; it != imported_certs.end(); ++it)
rv &= model->SetCertTrust(it->get(),
net::CA_CERT,
net::NSSCertDatabase::TRUSTED_SSL);
}
}
}
return rv;
}
#endif
} // namespace
App::App(v8::Isolate* isolate) {
static_cast<brave::BraveContentBrowserClient*>(
brave::BraveContentBrowserClient::Get())->set_delegate(this);
Browser::Get()->AddObserver(this);
// content::GpuDataManager::GetInstance()->AddObserver(this);
Init(isolate);
g_browser_process->set_app(this);
#if defined(ENABLE_EXTENSIONS)
registrar_.Add(this,
content::NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED,
content::NotificationService::AllBrowserContextsAndSources());
registrar_.Add(this,
chrome::NOTIFICATION_PROFILE_CREATED,
content::NotificationService::AllBrowserContextsAndSources());
#endif
}
// TOOD(bridiver) - move this to api_extension?
void App::Observe(
int type, const content::NotificationSource& source,
const content::NotificationDetails& details) {
switch (type) {
case content::NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED: {
content::WebContents* web_contents =
content::Source<content::WebContents>(source).ptr();
auto browser_context = web_contents->GetBrowserContext();
auto url = web_contents->GetURL();
#if defined(ENABLE_EXTENSIONS)
// make sure background pages get a webcontents
// api wrapper so they can communicate via IPC
if (Extension::IsBackgroundPageUrl(url, browser_context)) {
WebContents::CreateFrom(isolate(), web_contents);
}
#endif
break;
}
case chrome::NOTIFICATION_PROFILE_CREATED: {
AtomBrowserContext* browser_context =
content::Source<AtomBrowserContext>(source).ptr();
auto session = Session::CreateFrom(isolate(), browser_context);
Emit("browser-context-created", session);
break;
}
}
}
App::~App() {
static_cast<brave::BraveContentBrowserClient*>(
brave::BraveContentBrowserClient::Get())->set_delegate(nullptr);
Browser::Get()->RemoveObserver(this);
net::NetworkChangeNotifier::RemoveMaxBandwidthObserver(this);
content::GpuDataManager::GetInstance()->RemoveObserver(this);
}
void App::OnBeforeQuit(bool* prevent_default) {
*prevent_default = Emit("before-quit");
}
void App::OnWillQuit(bool* prevent_default) {
*prevent_default = Emit("will-quit");
}
void App::OnWindowAllClosed() {
Emit("window-all-closed");
}
void App::OnQuit() {
int exitCode = AtomBrowserMainParts::Get()->GetExitCode();
Emit("quit", exitCode);
if (process_singleton_.get()) {
process_singleton_->Cleanup();
process_singleton_.reset();
}
}
void App::OnOpenFile(bool* prevent_default, const std::string& file_path) {
*prevent_default = Emit("open-file", file_path);
}
void App::OnOpenURL(const std::string& url) {
Emit("open-url", url);
}
void App::OnActivate(bool has_visible_windows) {
Emit("activate", has_visible_windows);
}
void App::OnWillFinishLaunching() {
Emit("will-finish-launching");
}
void App::OnFinishLaunching(const base::DictionaryValue& launch_info) {
// observer can't be added until after PostMainMessageLoopStart
net::NetworkChangeNotifier::AddMaxBandwidthObserver(this);
Emit("ready", launch_info);
}
void App::OnAccessibilitySupportChanged() {
Emit("accessibility-support-changed", IsAccessibilitySupportEnabled());
}
#if defined(OS_MACOSX)
void App::OnContinueUserActivity(
bool* prevent_default,
const std::string& type,
const base::DictionaryValue& user_info) {
*prevent_default = Emit("continue-activity", type, user_info);
}
#endif
void App::OnLogin(LoginHandler* login_handler,
const base::DictionaryValue& request_details) {
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
bool prevent_default = Emit(
"login",
WebContents::CreateFrom(isolate(), login_handler->GetWebContents()),
request_details,
login_handler->auth_info(),
base::Bind(&PassLoginInformation, base::RetainedRef(login_handler)));
// Default behavior is to always cancel the auth.
if (!prevent_default)
login_handler->CancelAuth();
}
void App::AllowCertificateError(
content::WebContents* web_contents,
int cert_error,
const net::SSLInfo& ssl_info,
const GURL& request_url,
content::ResourceType resource_type,
bool overridable,
bool strict_enforcement,
bool expired_previous_decision,
const base::Callback<void(content::CertificateRequestResultType)>&
callback) {
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
// TODO(bridiver) handle CertificateRequestResultType
Emit("certificate-error",
WebContents::CreateFrom(isolate(), web_contents),
request_url,
net::ErrorToString(cert_error),
ssl_info.cert,
ResourceTypeToString(resource_type),
overridable,
strict_enforcement,
expired_previous_decision,
callback);
}
void App::SelectClientCertificate(
content::WebContents* web_contents,
net::SSLCertRequestInfo* cert_request_info,
std::unique_ptr<content::ClientCertificateDelegate> delegate) {
std::shared_ptr<content::ClientCertificateDelegate>
shared_delegate(delegate.release());
bool prevent_default =
Emit("select-client-certificate",
WebContents::CreateFrom(isolate(), web_contents),
cert_request_info->host_and_port.ToString(),
cert_request_info->client_certs,
base::Bind(&OnClientCertificateSelected,
isolate(),
shared_delegate));
// Default to first certificate from the platform store.
if (!prevent_default)
shared_delegate->ContinueWithCertificate(
cert_request_info->client_certs[0].get());
}
void App::OnMaxBandwidthChanged(
double max_bandwidth_mbps,
net::NetworkChangeNotifier::ConnectionType type) {
// for some reason NetworkObserver::OnNetworkConnected and
// NetworkObserver::OnNetworkDisconnected don't appear to
// be called so using the same method that BrowserOnlineStateObserver uses
bool online = type != net::NetworkChangeNotifier::CONNECTION_NONE;
if (online) {
Emit("network-connected");
} else {
Emit("network-disconnected");
}
}
void App::OnGpuProcessCrashed(base::TerminationStatus exit_code) {
Emit("gpu-process-crashed");
}
base::FilePath App::GetPath(mate::Arguments* args, const std::string& name) {
bool succeed = false;
base::FilePath path;
int key = GetPathConstant(name);
if (key >= 0)
succeed = PathService::Get(key, &path);
if (!succeed)
args->ThrowError("Failed to get path");
return path;
}
void App::SetPath(mate::Arguments* args,
const std::string& name,
const base::FilePath& path) {
if (!path.IsAbsolute()) {
args->ThrowError("path must be absolute");
return;
}
bool succeed = false;
int key = GetPathConstant(name);
if (key >= 0)
succeed = PathService::OverrideAndCreateIfNeeded(key, path, true, false);
if (!succeed)
args->ThrowError("Failed to set path");
}
void App::SetDesktopName(const std::string& desktop_name) {
#if defined(OS_LINUX)
std::unique_ptr<base::Environment> env(base::Environment::Create());
env->SetVar("CHROME_DESKTOP", desktop_name);
#endif
}
std::string App::GetLocale() {
return static_cast<brave::BraveContentBrowserClient*>(
brave::BraveContentBrowserClient::Get())->GetApplicationLocale();
}
void App::SetLocale(std::string locale) {
static_cast<brave::BraveContentBrowserClient*>(
brave::BraveContentBrowserClient::Get())->SetApplicationLocale(locale);
}
bool App::MakeSingleInstance(
const ProcessSingleton::NotificationCallback& callback) {
base::ThreadRestrictions::SetIOAllowed(true); // ugh electron
if (process_singleton_.get())
return false;
base::FilePath user_dir;
PathService::Get(brightray::DIR_USER_DATA, &user_dir);
process_singleton_.reset(new ProcessSingleton(
user_dir, base::Bind(NotificationCallbackWrapper, callback)));
switch (process_singleton_->NotifyOtherProcessOrCreate()) {
case ProcessSingleton::NotifyResult::LOCK_ERROR:
case ProcessSingleton::NotifyResult::PROFILE_IN_USE:
case ProcessSingleton::NotifyResult::PROCESS_NOTIFIED:
process_singleton_.reset();
return true;
case ProcessSingleton::NotifyResult::PROCESS_NONE:
default: // Shouldn't be needed, but VS warns if it is not there.
return false;
}
}
void App::ReleaseSingleInstance() {
if (process_singleton_.get()) {
process_singleton_->Cleanup();
process_singleton_.reset();
}
}
bool App::Relaunch(mate::Arguments* js_args) {
// Parse parameters.
bool override_argv = false;
base::FilePath exec_path;
relauncher::StringVector args;
mate::Dictionary options;
if (js_args->GetNext(&options)) {
if (options.Get("execPath", &exec_path) | options.Get("args", &args))
override_argv = true;
}
if (!override_argv) {
#if defined(OS_WIN)
const relauncher::StringVector& argv = atom::AtomCommandLine::wargv();
#else
const relauncher::StringVector& argv = atom::AtomCommandLine::argv();
#endif
return relauncher::RelaunchApp(argv);
}
relauncher::StringVector argv;
argv.reserve(1 + args.size());
if (exec_path.empty()) {
base::FilePath current_exe_path;
PathService::Get(base::FILE_EXE, ¤t_exe_path);
argv.push_back(current_exe_path.value());
} else {
argv.push_back(exec_path.value());
}
argv.insert(argv.end(), args.begin(), args.end());
return relauncher::RelaunchApp(argv);
}
void App::DisableHardwareAcceleration(mate::Arguments* args) {
if (Browser::Get()->is_ready()) {
args->ThrowError("app.disableHardwareAcceleration() can only be called "
"before app is ready");
return;
}
content::GpuDataManager::GetInstance()->DisableHardwareAcceleration();
}
bool App::IsAccessibilitySupportEnabled() {
auto ax_state = content::BrowserAccessibilityState::GetInstance();
return ax_state->IsAccessibleBrowser();
}
#if defined(USE_NSS_CERTS)
void App::ImportCertificate(
const base::DictionaryValue& options,
const net::CompletionCallback& callback) {
auto browser_context = AtomBrowserContext::From("", false);
if (!certificate_manager_model_) {
std::unique_ptr<base::DictionaryValue> copy = options.CreateDeepCopy();
CertificateManagerModel::Create(
browser_context.get(),
base::Bind(&App::OnCertificateManagerModelCreated,
base::Unretained(this),
base::Passed(©),
callback));
return;
}
int rv = ImportIntoCertStore(certificate_manager_model_.get(), options);
callback.Run(rv);
}
void App::OnCertificateManagerModelCreated(
std::unique_ptr<base::DictionaryValue> options,
const net::CompletionCallback& callback,
std::unique_ptr<CertificateManagerModel> model) {
certificate_manager_model_ = std::move(model);
int rv = ImportIntoCertStore(certificate_manager_model_.get(),
*(options.get()));
callback.Run(rv);
}
#endif
#if defined(OS_WIN)
v8::Local<v8::Value> App::GetJumpListSettings() {
JumpList jump_list(Browser::Get()->GetAppUserModelID());
int min_items = 10;
std::vector<JumpListItem> removed_items;
if (jump_list.Begin(&min_items, &removed_items)) {
// We don't actually want to change anything, so abort the transaction.
jump_list.Abort();
} else {
LOG(ERROR) << "Failed to begin Jump List transaction.";
}
auto dict = mate::Dictionary::CreateEmpty(isolate());
dict.Set("minItems", min_items);
dict.Set("removedItems", mate::ConvertToV8(isolate(), removed_items));
return dict.GetHandle();
}
JumpListResult App::SetJumpList(v8::Local<v8::Value> val,
mate::Arguments* args) {
std::vector<JumpListCategory> categories;
bool delete_jump_list = val->IsNull();
if (!delete_jump_list &&
!mate::ConvertFromV8(args->isolate(), val, &categories)) {
args->ThrowError("Argument must be null or an array of categories");
return JumpListResult::ARGUMENT_ERROR;
}
JumpList jump_list(Browser::Get()->GetAppUserModelID());
if (delete_jump_list) {
return jump_list.Delete()
? JumpListResult::SUCCESS
: JumpListResult::GENERIC_ERROR;
}
// Start a transaction that updates the JumpList of this application.
if (!jump_list.Begin())
return JumpListResult::GENERIC_ERROR;
JumpListResult result = jump_list.AppendCategories(categories);
// AppendCategories may have failed to add some categories, but it's better
// to have something than nothing so try to commit the changes anyway.
if (!jump_list.Commit()) {
LOG(ERROR) << "Failed to commit changes to custom Jump List.";
// It's more useful to return the earlier error code that might give
// some indication as to why the transaction actually failed, so don't
// overwrite it with a "generic error" code here.
if (result == JumpListResult::SUCCESS)
result = JumpListResult::GENERIC_ERROR;
}
return result;
}
#endif // defined(OS_WIN)
// static
mate::Handle<App> App::Create(v8::Isolate* isolate) {
return mate::CreateHandle(isolate, new App(isolate));
}
// static
void App::BuildPrototype(
v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "App"));
auto browser = base::Unretained(Browser::Get());
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("quit", base::Bind(&Browser::Quit, browser))
.SetMethod("exit", base::Bind(&Browser::Exit, browser))
.SetMethod("focus", base::Bind(&Browser::Focus, browser))
.SetMethod("getVersion", base::Bind(&Browser::GetVersion, browser))
.SetMethod("setVersion", base::Bind(&Browser::SetVersion, browser))
.SetMethod("getName", base::Bind(&Browser::GetName, browser))
.SetMethod("setName", base::Bind(&Browser::SetName, browser))
.SetMethod("isReady", base::Bind(&Browser::is_ready, browser))
.SetMethod("addRecentDocument",
base::Bind(&Browser::AddRecentDocument, browser))
.SetMethod("clearRecentDocuments",
base::Bind(&Browser::ClearRecentDocuments, browser))
.SetMethod("setAppUserModelId",
base::Bind(&Browser::SetAppUserModelID, browser))
.SetMethod("isDefaultProtocolClient",
base::Bind(&Browser::IsDefaultProtocolClient, browser))
.SetMethod("setAsDefaultProtocolClient",
base::Bind(&Browser::SetAsDefaultProtocolClient, browser))
.SetMethod("removeAsDefaultProtocolClient",
base::Bind(&Browser::RemoveAsDefaultProtocolClient, browser))
.SetMethod("setBadgeCount", base::Bind(&Browser::SetBadgeCount, browser))
.SetMethod("getBadgeCount", base::Bind(&Browser::GetBadgeCount, browser))
.SetMethod("getLoginItemSettings",
base::Bind(&Browser::GetLoginItemSettings, browser))
.SetMethod("setLoginItemSettings",
base::Bind(&Browser::SetLoginItemSettings, browser))
#if defined(OS_MACOSX)
.SetMethod("hide", base::Bind(&Browser::Hide, browser))
.SetMethod("show", base::Bind(&Browser::Show, browser))
.SetMethod("setUserActivity",
base::Bind(&Browser::SetUserActivity, browser))
.SetMethod("getCurrentActivityType",
base::Bind(&Browser::GetCurrentActivityType, browser))
#endif
#if defined(OS_WIN)
.SetMethod("setUserTasks", base::Bind(&Browser::SetUserTasks, browser))
.SetMethod("getJumpListSettings", &App::GetJumpListSettings)
.SetMethod("setJumpList", &App::SetJumpList)
#endif
#if defined(OS_LINUX)
.SetMethod("isUnityRunning",
base::Bind(&Browser::IsUnityRunning, browser))
#endif
.SetMethod("setPath", &App::SetPath)
.SetMethod("getPath", &App::GetPath)
.SetMethod("setDesktopName", &App::SetDesktopName)
.SetMethod("getLocale", &App::GetLocale)
.SetMethod("setLocale", &App::SetLocale)
#if defined(USE_NSS_CERTS)
.SetMethod("importCertificate", &App::ImportCertificate)
#endif
.SetMethod("makeSingleInstance", &App::MakeSingleInstance)
.SetMethod("releaseSingleInstance", &App::ReleaseSingleInstance)
.SetMethod("relaunch", &App::Relaunch)
.SetMethod("isAccessibilitySupportEnabled",
&App::IsAccessibilitySupportEnabled)
.SetMethod("disableHardwareAcceleration",
&App::DisableHardwareAcceleration);
}
} // namespace api
} // namespace atom
namespace {
void AppendSwitch(const std::string& switch_string, mate::Arguments* args) {
auto command_line = base::CommandLine::ForCurrentProcess();
if (base::EndsWith(switch_string, "-path",
base::CompareCase::INSENSITIVE_ASCII) ||
switch_string == switches::kLogNetLog) {
base::FilePath path;
args->GetNext(&path);
command_line->AppendSwitchPath(switch_string, path);
// load flash if the switch is added after
// AtomContentClient::AddPepperPlugins is called
if (switch_string == atom::switches::kPpapiFlashPath) {
std::vector<content::PepperPluginInfo> plugins;
atom::AddPepperFlashFromCommandLine(&plugins);
auto plugin_service = content::PluginServiceImpl::GetInstance();
for (size_t i = 0; i < plugins.size(); ++i) {
if (!plugin_service->
GetRegisteredPpapiPluginInfo(plugins[i].path)) {
plugin_service->
RegisterInternalPlugin(plugins[i].ToWebPluginInfo(), true);
}
}
}
return;
}
std::string value;
if (args->GetNext(&value))
command_line->AppendSwitchASCII(switch_string, value);
else
command_line->AppendSwitch(switch_string);
}
#if defined(OS_MACOSX)
int DockBounce(const std::string& type) {
int request_id = -1;
if (type == "critical")
request_id = Browser::Get()->DockBounce(Browser::BOUNCE_CRITICAL);
else if (type == "informational")
request_id = Browser::Get()->DockBounce(Browser::BOUNCE_INFORMATIONAL);
return request_id;
}
void DockSetMenu(atom::api::Menu* menu) {
Browser::Get()->DockSetMenu(menu->model());
}
#endif
void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
v8::Local<v8::Context> context, void* priv) {
v8::Isolate* isolate = context->GetIsolate();
auto command_line = base::CommandLine::ForCurrentProcess();
mate::Dictionary dict(isolate, exports);
dict.Set("App", atom::api::App::GetConstructor(isolate)->GetFunction());
dict.Set("app", atom::api::App::Create(isolate));
dict.SetMethod("appendSwitch", &AppendSwitch);
dict.SetMethod("appendArgument",
base::Bind(&base::CommandLine::AppendArg,
base::Unretained(command_line)));
#if defined(OS_MACOSX)
auto browser = base::Unretained(Browser::Get());
dict.SetMethod("dockBounce", &DockBounce);
dict.SetMethod("dockCancelBounce",
base::Bind(&Browser::DockCancelBounce, browser));
dict.SetMethod("dockDownloadFinished",
base::Bind(&Browser::DockDownloadFinished, browser));
dict.SetMethod("dockSetBadgeText",
base::Bind(&Browser::DockSetBadgeText, browser));
dict.SetMethod("dockGetBadgeText",
base::Bind(&Browser::DockGetBadgeText, browser));
dict.SetMethod("dockHide", base::Bind(&Browser::DockHide, browser));
dict.SetMethod("dockShow", base::Bind(&Browser::DockShow, browser));
dict.SetMethod("dockIsVisible", base::Bind(&Browser::DockIsVisible, browser));
dict.SetMethod("dockSetMenu", &DockSetMenu);
dict.SetMethod("dockSetIcon", base::Bind(&Browser::DockSetIcon, browser));
#endif
}
} // namespace
NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_app, Initialize)
|
posix4e/electron
|
atom/browser/api/atom_api_app.cc
|
C++
|
mit
| 35,181
|
Routines
========
In Tansa, routines are prewritten mission or motion plans that specify how all the drones should move. If you just want your drones to do some scripted maneuvers without responsiveness, this is for you.
|
dennisss/tansa
|
doc/Routines.md
|
Markdown
|
mit
| 222
|
#include "Shape.h"
Shape::Shape()
{
drawShape = GL_LINES;
numberOfDots = 0;
maxDots = 0;
pDots = NULL;
color = Color(1.0f, 0.0f, 0.0f);
}
Shape::~Shape()
{
delete[] pDots;
maxDots = numberOfDots = 0;
pDots = NULL;
}
void Shape::draw()
{
glBegin(drawShape);
color.use();
for(int i=0; i<numberOfDots; i++)
pDots[i].vertex();
glEnd();
}
void Shape::setColor(Color c)
{
color = c;
}
void Shape::addDot(float x, float y)
{
if(numberOfDots == maxDots)
return;
pDots[numberOfDots].setCoordinat(x, y);
numberOfDots++;
}
|
ByNeo/Snake2D
|
src/Shape.cpp
|
C++
|
mit
| 545
|
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<h3>Backups</h3>
<ul>
<li><a href="<?=base_url('backups?table=usuarios')?>"><i class="fa fa-download"></i> Backup de usuarios</a></li>
<li><a href="<?=base_url('backups?table=funcionarios')?>"><i class="fa fa-download"></i> Backup de funcionários</a></li>
<li><a href="<?=base_url('backups?table=empresas')?>"><i class="fa fa-download"></i> Backup de lotações</a></li>
<li><a href="<?=base_url('backups?table=remessa')?>"><i class="fa fa-download"></i> Backup de remessas</a></li>
<li><a href="<?=base_url('backups?table=completo')?>"><i class="fa fa-download"></i> backup completo</a></li>
</ul>
|
luizalbertobm/solucao
|
application/views/backups.php
|
PHP
|
mit
| 694
|
# <%=_packageName%>
---
## Installation
npm install <%=_packageName%>
or
yarn add <%=_packageName%>
## Publish
npm version <version>
git push --follw-tags
npm login -> npm run release
|
react-smart-component/generator-package
|
app/templates/README.md
|
Markdown
|
mit
| 194
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "rTCobros_Fechas"
'-------------------------------------------------------------------------------------------'
Partial Class rTCobros_Fechas
Inherits vis2formularios.frmReporte
Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia)
Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia)
Dim lcParametro1Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1))
Dim lcParametro1Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(1))
Dim lcParametro2Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(2))
Dim lcParametro2Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(2))
Dim lcParametro3Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(3))
Dim lcParametro3Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(3))
Dim lcParametro4Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(4))
Dim lcParametro4Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(4))
Dim lcParametro5Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(5))
Dim lcParametro5Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(5))
Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden
Dim loComandoSeleccionar As New StringBuilder()
loComandoSeleccionar.AppendLine(" SELECT DATEPART(YEAR, Fec_Ini) AS Año,")
loComandoSeleccionar.AppendLine(" DATEPART(MONTH, Fec_Ini) AS Mes,")
loComandoSeleccionar.AppendLine(" DATEPART(DAY, Fec_Ini) AS Dia,")
loComandoSeleccionar.AppendLine(" SUM(ISNULL(Mon_Net,0)) AS Mon_Net")
loComandoSeleccionar.AppendLine(" INTO #Temporal")
loComandoSeleccionar.AppendLine(" FROM Cuentas_Cobrar")
loComandoSeleccionar.AppendLine(" WHERE Cuentas_Cobrar.Cod_Tip IN ('Fact','ATD')")
loComandoSeleccionar.AppendLine(" AND Fec_Ini BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Cod_Cli BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Cod_Ven BETWEEN " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Cuentas_Cobrar.Status IN ('Afectado', 'Pagado')")
loComandoSeleccionar.AppendLine(" AND Cod_Mon BETWEEN " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Cod_Rev BETWEEN " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Cod_Suc BETWEEN " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" GROUP BY DATEPART(YEAR, Fec_Ini),DATEPART(MONTH, Fec_Ini), DATEPART(DAY, Fec_Ini) ")
loComandoSeleccionar.AppendLine(" SELECT DATEPART(YEAR, Cobros.fec_ini) AS Año,")
loComandoSeleccionar.AppendLine(" DATEPART(MONTH, Cobros.fec_ini)AS Mes,")
loComandoSeleccionar.AppendLine(" DATEPART(DAY, Cobros.fec_ini)AS Dia,")
loComandoSeleccionar.AppendLine(" SUM(CASE WHEN Detalles_Cobros.Tip_Ope = 'Efectivo' THEN Detalles_Cobros.Mon_Net ELSE 0 END) AS Efectivo, ")
loComandoSeleccionar.AppendLine(" SUM(CASE WHEN Detalles_Cobros.Tip_Ope = 'Ticket' THEN Detalles_Cobros.Mon_Net ELSE 0 END) AS Ticket, ")
loComandoSeleccionar.AppendLine(" SUM(CASE WHEN Detalles_Cobros.Tip_Ope = 'Cheque' THEN Detalles_Cobros.Mon_Net ELSE 0 END) AS Cheque, ")
loComandoSeleccionar.AppendLine(" SUM(CASE WHEN Detalles_Cobros.Tip_Ope = 'Tarjeta' THEN Detalles_Cobros.Mon_Net ELSE 0 END) AS Tarjeta, ")
loComandoSeleccionar.AppendLine(" SUM(CASE WHEN Detalles_Cobros.Tip_Ope = 'Deposito' THEN Detalles_Cobros.Mon_Net ELSE 0 END) AS Deposito, ")
loComandoSeleccionar.AppendLine(" SUM(CASE WHEN Detalles_Cobros.Tip_Ope = 'Transferencia' THEN Detalles_Cobros.Mon_Net ELSE 0 END) AS Transferencia ")
loComandoSeleccionar.AppendLine(" INTO #Temporal2 ")
loComandoSeleccionar.AppendLine(" FROM Cobros Cobros")
loComandoSeleccionar.AppendLine(" JOIN Vendedores AS Vendedores ON Vendedores.Cod_Ven = Cobros.Cod_Ven ")
loComandoSeleccionar.AppendLine(" JOIN Detalles_Cobros AS Detalles_Cobros ON Detalles_Cobros.Documento = Cobros.Documento")
loComandoSeleccionar.AppendLine(" WHERE Cobros.Fec_Ini BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Cobros.Cod_Cli BETWEEN " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Cobros.Cod_Ven BETWEEN " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Cobros.Status IN ('Confirmado')")
loComandoSeleccionar.AppendLine(" AND Cobros.Cod_Mon BETWEEN " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Cobros.Cod_Rev BETWEEN " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Cobros.Cod_Suc BETWEEN " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" GROUP BY DATEPART(YEAR, Cobros.Fec_Ini),DATEPART(MONTH, Cobros.Fec_Ini), DATEPART(DAY, Cobros.Fec_Ini)")
loComandoSeleccionar.AppendLine(" SELECT ISNULL(#temporal.Año, #temporal2.Año) AS Año, ")
loComandoSeleccionar.AppendLine(" ISNULL(#temporal.Mes, #temporal2.Mes) AS Mes, ")
loComandoSeleccionar.AppendLine(" ISNULL(#temporal.Dia, #temporal2.Dia) AS Dia, ")
loComandoSeleccionar.AppendLine(" ISNULL(#temporal.Mon_Net,0) AS Mon_Net, ")
loComandoSeleccionar.AppendLine(" (ISNULL(#temporal2.Efectivo,0)) AS Efectivo, ")
loComandoSeleccionar.AppendLine(" (ISNULL(#temporal2.Ticket,0)) AS Ticket, ")
loComandoSeleccionar.AppendLine(" (ISNULL(#temporal2.Cheque,0)) AS Cheque, ")
loComandoSeleccionar.AppendLine(" (ISNULL(#temporal2.Tarjeta,0)) AS Tarjeta, ")
loComandoSeleccionar.AppendLine(" (ISNULL(#temporal2.Deposito,0)) AS Deposito, ")
loComandoSeleccionar.AppendLine(" (ISNULL(#temporal2.Transferencia,0)) AS Transferencia,")
loComandoSeleccionar.AppendLine(" (ISNULL(#temporal2.Efectivo,0) + ISNULL(#temporal2.Cheque,0) + ISNULL(#temporal2.Tarjeta,0) + ISNULL(#temporal2.Deposito,0) + ISNULL(#temporal2.Transferencia,0) + ISNULL(#temporal2.Ticket,0)) AS Total_Cobros")
loComandoSeleccionar.AppendLine(" INTO #Temporal002 ")
loComandoSeleccionar.AppendLine(" FROM #Temporal #Temporal ")
loComandoSeleccionar.AppendLine(" FULL JOIN #temporal2 AS #temporal2 ON ((#temporal.Año = #temporal2.Año) AND (#temporal.Mes = #temporal2.Mes) AND (#temporal.Dia = #temporal2.Dia)) ")
loComandoSeleccionar.AppendLine(" SELECT 'Cuantos' AS Cuantos, ")
loComandoSeleccionar.AppendLine(" Año, ")
loComandoSeleccionar.AppendLine(" Mes, ")
loComandoSeleccionar.AppendLine(" Dia, ")
loComandoSeleccionar.AppendLine(" Mon_Net, ")
loComandoSeleccionar.AppendLine(" Efectivo, ")
loComandoSeleccionar.AppendLine(" Ticket, ")
loComandoSeleccionar.AppendLine(" Cheque, ")
loComandoSeleccionar.AppendLine(" Tarjeta, ")
loComandoSeleccionar.AppendLine(" Deposito, ")
loComandoSeleccionar.AppendLine(" Transferencia,")
loComandoSeleccionar.AppendLine(" Total_Cobros")
loComandoSeleccionar.AppendLine(" FROM #Temporal002 ")
loComandoSeleccionar.AppendLine(" ORDER BY " & lcOrdenamiento)
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString, "curReportes")
'-------------------------------------------------------------------------------------------------------
' Verificando si el select (tabla nº0) trae registros
'-------------------------------------------------------------------------------------------------------
If (laDatosReporte.Tables(0).Rows.Count <= 0) Then
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Información", _
"No se Encontraron Registros para los Parámetros Especificados. ", _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Informacion, _
"350px", _
"200px")
End If
loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rTCobros_Fechas", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvrTCobros_Fechas.ReportSource = loObjetoReporte
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
Try
loObjetoReporte.Close()
Catch loExcepcion As Exception
End Try
End Sub
End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo '
'-------------------------------------------------------------------------------------------'
' CMS: 08/07/09: Programacion inicial '
'-------------------------------------------------------------------------------------------'
' CMS: 20/07/09: Se agregaron las columnas ticket y transferencia '
'-------------------------------------------------------------------------------------------'
' RJG: 28/06/11: Corrección de agrupación de monto neto. '
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
rTCobros_Fechas.aspx.vb
|
Visual Basic
|
mit
| 13,148
|
VERSION = DEBUG
CC = ccache gcc
TEX = pdflatex
GENERIC_CFLAGS = -Wall -Wextra -pedantic -pthread -std=c99
PROFILE_CFLAGS = -pg
DEBUG_CFLAGS = -g
RELEASE_CFLAGS = -O2
SOURCES = $(filter-out exo4.c,$(wildcard *.c))
EXECS = $(SOURCES:%.c= %.bin)
X11LIB = `pkg-config --libs x11`
X11FLAGS = `pkg-config --cflags x11`
MATHFLAGS = -lm
ifeq "$(VERSION)" "PROFILE"
CFLAGS = $(GENERIC_CFLAGS) $(PROFILE_CFLAGS)
else
ifeq "$(VERSION)" "DEBUG"
CFLAGS = $(GENERIC_CFLAGS) $(DEBUG_CFLAGS)
else
ifeq "$(VERSION)" "RELEASE"
CFLAGS = $(GENERIC_CFLAGS) $(RELEASE_CFLAGS)
endif
endif
endif
all: $(EXECS) exo4.bin
doc: outs rapport.pdf
exo1.bin: exo1.c
$(CC) $(CFLAGS) $< -o $@
exo2.bin: exo2.c
$(CC) $(CFLAGS) $< -o $@
exo3.bin: exo3.c
$(CC) $(CFLAGS) $< -o $@
exo4.bin: exo4.c
$(CC) $(CFLAGS) $< -o $@ $(X11LIB) $(X11FLAGS) $(MATHFLAGS)
rapport.pdf: rapport.tex outs $(SOURCES) exo4.c
$(TEX) rapport.tex
latex_count=8 ; \
while egrep -s 'Rerun (LaTeX|to get cross-references right)' rapport.log && [ $$latex_count -gt 0 ] ;\
do \
echo "Rerunning latex...." ;\
$(TEX) rapport.tex ;\
latex_count=`expr $$latex_count - 1` ;\
done
outs: $(EXECS:%.bin=%.out) exo4.out.png
exo1.out: exo1.bin
./$< 10 > $@
exo2.out: exo2.bin
./$< > $@
exo3.out: exo3.bin
./$< > $@
exo4.out.png: exo4.bin
./$< --random & sleep 3 ; import -window `xwininfo -root -tree | grep "() 200x200" | awk '{print $$1}'` exo4.out.png
clean:
rm *.bin *.pdf *.aux *.log *.out* *.toc *.tar.gz
tarball: doc
tar zcvf $(notdir $(shell pwd)).tar.gz exo* *.pdf *.tex Makefile rle/*.rle bmp/*.bmp
.PHONY: all doc clean tarball outs
|
minijackson/IGI2001
|
TP7/Makefile
|
Makefile
|
mit
| 1,678
|
class AddStylesToFreeSpaces < ActiveRecord::Migration
def self.up
add_column :free_spaces, :styles, :text
end
def self.down
remove_column :free_spaces, :styles
end
end
|
dmonopoly/jdrampage
|
db/migrate/20110316151557_add_styles_to_free_spaces.rb
|
Ruby
|
mit
| 185
|
require 'json'
playbyplay_paths = Dir.glob(Rails.root.join('lib','data','gameflash','**','*_playbyplay.json').to_s)
for playbyplay in playbyplay_paths
puts playbyplay
playbyplay = JSON.parse(File.read(playbyplay))['playbyplay']
game_id = playbyplay['contest']['id']
plays = playbyplay['plays']['play']
for play in plays
p = Play.new
p.game_id = game_id
p.half = play['half']
p.time_minutes = play['time-minutes']
p.time_seconds = play['time-seconds']
p.details = play['details']
p.player_id_1 = play['player1-id']
p.player_id_2 = play['player2-id']
p.player_first_name_1 = play['player-first-name-1']
p.player_first_name_2 = play['player-first-name-2']
p.player_last_name_1 = play['player-last-name-1']
p.player_last_name_2 = play['player-last-name-2']
p.home_score = play['home-score']
p.visitor_score = play['visitor-score']
p.visitor_fouls = play['visitor-fouls']
p.home_fouls = play['home-fouls']
p.player_score = play['player-score']
p.points_type = play['points-type']
p.detail_desc = play['detail-desc']
p.event_desc = play['event-desc']
p.distance = play['distance']
p.x_coord = play['x-coord']
p.y_coord = play['y-coord']
p.team_id_1 = play['team-id-1']
p.team_id_2 = play['team-id-2']
p.save
end
end
|
albertlyu/shot-charts-site
|
db/seeds/03_playbyplay.rb
|
Ruby
|
mit
| 1,270
|
/*
* WinDrawLib
* Copyright (c) 2016 Martin Mitas
*
* 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.
*/
#include "misc.h"
#include "backend-d2d.h"
#include "backend-dwrite.h"
#include "backend-wic.h"
#include "backend-gdix.h"
#include "lock.h"
void (*wd_fn_lock)(void) = NULL;
void (*wd_fn_unlock)(void) = NULL;
static DWORD wd_preinit_flags = 0;
void
wdPreInitialize(void (*fnLock)(void), void (*fnUnlock)(void), DWORD dwFlags)
{
wd_fn_lock = fnLock;
wd_fn_unlock = fnUnlock;
wd_preinit_flags = dwFlags;
}
static int
wd_init_core_api(void)
{
if(!(wd_preinit_flags & WD_DISABLE_D2D)) {
if(d2d_init() == 0)
return 0;
}
if(!(wd_preinit_flags & WD_DISABLE_GDIPLUS)) {
if(gdix_init() == 0)
return 0;
}
return -1;
}
static void
wd_fini_core_api(void)
{
if(d2d_enabled())
d2d_fini();
else
gdix_fini();
}
static int
wd_init_image_api(void)
{
if(d2d_enabled()) {
return wic_init();
} else {
/* noop */
return 0;
}
}
static void
wd_fini_image_api(void)
{
if(d2d_enabled()) {
wic_fini();
} else {
/* noop */
}
}
static int
wd_init_string_api(void)
{
if(d2d_enabled()) {
return dwrite_init();
} else {
/* noop */
return 0;
}
}
static void
wd_fini_string_api(void)
{
if(d2d_enabled()) {
dwrite_fini();
} else {
/* noop */
}
}
static const struct {
int (*fn_init)(void);
void (*fn_fini)(void);
} wd_modules[] = {
{ wd_init_core_api, wd_fini_core_api },
{ wd_init_image_api, wd_fini_image_api },
{ wd_init_string_api, wd_fini_string_api }
};
#define WD_MOD_COUNT (sizeof(wd_modules) / sizeof(wd_modules[0]))
#define WD_MOD_COREAPI 0
#define WD_MOD_IMAGEAPI 1
#define WD_MOD_STRINGAPI 2
static UINT wd_init_counter[WD_MOD_COUNT] = { 0 };
BOOL
wdInitialize(DWORD dwFlags)
{
BOOL want_init[WD_MOD_COUNT];
int i;
want_init[WD_MOD_COREAPI] = TRUE;
want_init[WD_MOD_IMAGEAPI] = (dwFlags & WD_INIT_IMAGEAPI);
want_init[WD_MOD_STRINGAPI] = (dwFlags & WD_INIT_STRINGAPI);
wd_lock();
for(i = 0; i < WD_MOD_COUNT; i++) {
if(!want_init[i])
continue;
wd_init_counter[i]++;
if(wd_init_counter[i] > 0) {
if(wd_modules[i].fn_init() != 0)
goto fail;
}
}
wd_unlock();
return TRUE;
fail:
/* Undo initializations from successful iterations. */
while(--i >= 0) {
if(want_init[i]) {
wd_init_counter[i]--;
if(wd_init_counter[i] == 0)
wd_modules[i].fn_fini();
}
}
wd_unlock();
return FALSE;
}
void
wdTerminate(DWORD dwFlags)
{
BOOL want_fini[WD_MOD_COUNT];
int i;
want_fini[WD_MOD_COREAPI] = TRUE;
want_fini[WD_MOD_IMAGEAPI] = (dwFlags & WD_INIT_IMAGEAPI);
want_fini[WD_MOD_STRINGAPI] = (dwFlags & WD_INIT_STRINGAPI);
wd_lock();
for(i = WD_MOD_COUNT-1; i >= 0; i--) {
if(!want_fini[i])
continue;
wd_init_counter[i]--;
if(wd_init_counter[i] == 0)
wd_modules[i].fn_fini();
}
/* If core module counter has dropped to zero, caller likely forgot to
* terminate some optional module (i.e. mismatching flags for wdTerminate()
* somewhere. So lets kill all those modules forcefully now anyway even
* though well behaving applications should never do that...
*/
if(wd_init_counter[WD_MOD_COREAPI] == 0) {
for(i = WD_MOD_COUNT-1; i >= 0; i--) {
if(wd_init_counter[i] > 0) {
WD_TRACE("wdTerminate: Forcefully terminating module %d.", i);
wd_modules[i].fn_fini();
wd_init_counter[i] = 0;
}
}
}
wd_unlock();
}
int
wdBackend(void)
{
if(d2d_enabled()) {
return WD_BACKEND_D2D;
}
if(gdix_enabled()) {
return WD_BACKEND_GDIPLUS;
}
return -1;
}
|
mity/windrawlib
|
src/init.c
|
C
|
mit
| 5,061
|
This command removes from the current set any files matching the criteria.
|
bradyhouse/house
|
fiddles/bash/fiddle-0029-JarExtraction/com/sencha/command/compile/ExcludeCommand.md
|
Markdown
|
mit
| 75
|
var __extends = (this && this.__extends) || (function () {
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]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
define(["require", "exports", "react", "office-ui-fabric-react/lib/Button", "office-ui-fabric-react/lib/Panel"], function (require, exports, React, Button_1, Panel_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var PanelExtraLargeExample = (function (_super) {
__extends(PanelExtraLargeExample, _super);
function PanelExtraLargeExample() {
var _this = _super.call(this) || this;
_this.state = { showPanel: false };
return _this;
}
PanelExtraLargeExample.prototype.render = function () {
var _this = this;
return (React.createElement("div", null,
React.createElement(Button_1.DefaultButton, { description: 'Opens the Sample Panel', onClick: function () { return _this.setState({ showPanel: true }); }, text: 'Open Panel' }),
React.createElement(Panel_1.Panel, { isOpen: this.state.showPanel, onDismiss: function () { return _this.setState({ showPanel: false }); }, type: Panel_1.PanelType.extraLarge, headerText: 'Extra Large Panel', closeButtonAriaLabel: 'Close' },
React.createElement("span", { className: 'ms-font-m' }, "Content goes here."))));
};
return PanelExtraLargeExample;
}(React.Component));
exports.PanelExtraLargeExample = PanelExtraLargeExample;
});
//# sourceMappingURL=Panel.ExtraLarge.Example.js.map
|
SpatialMap/SpatialMapDev
|
node_modules/office-ui-fabric-react/lib-amd/components/Panel/examples/Panel.ExtraLarge.Example.js
|
JavaScript
|
mit
| 1,926
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_20) on Mon May 02 10:23:15 CEST 2011 -->
<TITLE>
Uses of Class play.db.helper.SqlSelect (Play! API)
</TITLE>
<META NAME="date" CONTENT="2011-05-02">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class play.db.helper.SqlSelect (Play! API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../play/db/helper/SqlSelect.html" title="class in play.db.helper"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?play/db/helper//class-useSqlSelect.html" target="_top"><B>FRAMES</B></A>
<A HREF="SqlSelect.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>play.db.helper.SqlSelect</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../play/db/helper/SqlSelect.html" title="class in play.db.helper">SqlSelect</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#play.db.helper"><B>play.db.helper</B></A></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<A NAME="play.db.helper"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../play/db/helper/SqlSelect.html" title="class in play.db.helper">SqlSelect</A> in <A HREF="../../../../play/db/helper/package-summary.html">play.db.helper</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../play/db/helper/SqlSelect.html" title="class in play.db.helper">SqlSelect</A> in <A HREF="../../../../play/db/helper/package-summary.html">play.db.helper</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../play/db/helper/JpqlSelect.html" title="class in play.db.helper">JpqlSelect</A></B></CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../play/db/helper/package-summary.html">play.db.helper</A> that return <A HREF="../../../../play/db/helper/SqlSelect.html" title="class in play.db.helper">SqlSelect</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../play/db/helper/SqlSelect.html" title="class in play.db.helper">SqlSelect</A></CODE></FONT></TD>
<TD><CODE><B>SqlSelect.</B><B><A HREF="../../../../play/db/helper/SqlSelect.html#andWhere(play.db.helper.SqlSelect.Where...)">andWhere</A></B>(<A HREF="../../../../play/db/helper/SqlSelect.Where.html" title="class in play.db.helper">SqlSelect.Where</A>... expr)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../play/db/helper/SqlSelect.html" title="class in play.db.helper">SqlSelect</A></CODE></FONT></TD>
<TD><CODE><B>SqlSelect.</B><B><A HREF="../../../../play/db/helper/SqlSelect.html#andWhere(java.lang.String...)">andWhere</A></B>(java.lang.String... expr)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../play/db/helper/SqlSelect.html" title="class in play.db.helper">SqlSelect</A></CODE></FONT></TD>
<TD><CODE><B>SqlSelect.</B><B><A HREF="../../../../play/db/helper/SqlSelect.html#from(java.lang.String...)">from</A></B>(java.lang.String... expr)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../play/db/helper/SqlSelect.html" title="class in play.db.helper">SqlSelect</A></CODE></FONT></TD>
<TD><CODE><B>SqlSelect.</B><B><A HREF="../../../../play/db/helper/SqlSelect.html#groupBy(java.lang.String...)">groupBy</A></B>(java.lang.String... expr)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../play/db/helper/SqlSelect.html" title="class in play.db.helper">SqlSelect</A></CODE></FONT></TD>
<TD><CODE><B>SqlSelect.</B><B><A HREF="../../../../play/db/helper/SqlSelect.html#innerJoin(java.lang.String...)">innerJoin</A></B>(java.lang.String... expr)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../play/db/helper/SqlSelect.html" title="class in play.db.helper">SqlSelect</A></CODE></FONT></TD>
<TD><CODE><B>SqlSelect.</B><B><A HREF="../../../../play/db/helper/SqlSelect.html#leftJoin(java.lang.String...)">leftJoin</A></B>(java.lang.String... expr)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../play/db/helper/SqlSelect.html" title="class in play.db.helper">SqlSelect</A></CODE></FONT></TD>
<TD><CODE><B>SqlSelect.</B><B><A HREF="../../../../play/db/helper/SqlSelect.html#limit(long)">limit</A></B>(long lines)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../play/db/helper/SqlSelect.html" title="class in play.db.helper">SqlSelect</A></CODE></FONT></TD>
<TD><CODE><B>SqlSelect.</B><B><A HREF="../../../../play/db/helper/SqlSelect.html#limit(long, long)">limit</A></B>(long offset,
long lines)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../play/db/helper/SqlSelect.html" title="class in play.db.helper">SqlSelect</A></CODE></FONT></TD>
<TD><CODE><B>SqlSelect.</B><B><A HREF="../../../../play/db/helper/SqlSelect.html#orderBy(java.lang.String...)">orderBy</A></B>(java.lang.String... expr)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../play/db/helper/SqlSelect.html" title="class in play.db.helper">SqlSelect</A></CODE></FONT></TD>
<TD><CODE><B>SqlSelect.</B><B><A HREF="../../../../play/db/helper/SqlSelect.html#orWhere(play.db.helper.SqlSelect.Where...)">orWhere</A></B>(<A HREF="../../../../play/db/helper/SqlSelect.Where.html" title="class in play.db.helper">SqlSelect.Where</A>... expr)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../play/db/helper/SqlSelect.html" title="class in play.db.helper">SqlSelect</A></CODE></FONT></TD>
<TD><CODE><B>SqlSelect.</B><B><A HREF="../../../../play/db/helper/SqlSelect.html#orWhere(java.lang.String...)">orWhere</A></B>(java.lang.String... expr)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../play/db/helper/SqlSelect.html" title="class in play.db.helper">SqlSelect</A></CODE></FONT></TD>
<TD><CODE><B>SqlSelect.</B><B><A HREF="../../../../play/db/helper/SqlSelect.html#param(java.lang.Object)">param</A></B>(java.lang.Object obj)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../play/db/helper/SqlSelect.html" title="class in play.db.helper">SqlSelect</A></CODE></FONT></TD>
<TD><CODE><B>SqlSelect.</B><B><A HREF="../../../../play/db/helper/SqlSelect.html#params(java.lang.Object...)">params</A></B>(java.lang.Object... objs)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../play/db/helper/SqlSelect.html" title="class in play.db.helper">SqlSelect</A></CODE></FONT></TD>
<TD><CODE><B>SqlSelect.</B><B><A HREF="../../../../play/db/helper/SqlSelect.html#select(java.lang.String...)">select</A></B>(java.lang.String... expr)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../play/db/helper/SqlSelect.html" title="class in play.db.helper">SqlSelect</A></CODE></FONT></TD>
<TD><CODE><B>SqlSelect.</B><B><A HREF="../../../../play/db/helper/SqlSelect.html#where(play.db.helper.SqlSelect.Where...)">where</A></B>(<A HREF="../../../../play/db/helper/SqlSelect.Where.html" title="class in play.db.helper">SqlSelect.Where</A>... expr)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../play/db/helper/SqlSelect.html" title="class in play.db.helper">SqlSelect</A></CODE></FONT></TD>
<TD><CODE><B>SqlSelect.</B><B><A HREF="../../../../play/db/helper/SqlSelect.html#where(java.lang.String...)">where</A></B>(java.lang.String... expr)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../play/db/helper/package-summary.html">play.db.helper</A> with parameters of type <A HREF="../../../../play/db/helper/SqlSelect.html" title="class in play.db.helper">SqlSelect</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../play/db/helper/SqlUnion.html" title="class in play.db.helper">SqlUnion</A></CODE></FONT></TD>
<TD><CODE><B>SqlUnion.</B><B><A HREF="../../../../play/db/helper/SqlUnion.html#union(play.db.helper.SqlSelect...)">union</A></B>(<A HREF="../../../../play/db/helper/SqlSelect.html" title="class in play.db.helper">SqlSelect</A>... expr)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../play/db/helper/SqlUnion.html" title="class in play.db.helper">SqlUnion</A></CODE></FONT></TD>
<TD><CODE><B>SqlUnion.</B><B><A HREF="../../../../play/db/helper/SqlUnion.html#unionAll(play.db.helper.SqlSelect...)">unionAll</A></B>(<A HREF="../../../../play/db/helper/SqlSelect.html" title="class in play.db.helper">SqlSelect</A>... expr)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Constructors in <A HREF="../../../../play/db/helper/package-summary.html">play.db.helper</A> with parameters of type <A HREF="../../../../play/db/helper/SqlSelect.html" title="class in play.db.helper">SqlSelect</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../play/db/helper/SqlSelect.html#SqlSelect(play.db.helper.SqlSelect)">SqlSelect</A></B>(<A HREF="../../../../play/db/helper/SqlSelect.html" title="class in play.db.helper">SqlSelect</A> src)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../play/db/helper/SqlSelect.html" title="class in play.db.helper"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?play/db/helper//class-useSqlSelect.html" target="_top"><B>FRAMES</B></A>
<A HREF="SqlSelect.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<a href="http://guillaume.bort.fr">Guillaume Bort</a> & <a href="http://www.zenexity.fr">zenexity</a> - Distributed under <a href="http://www.apache.org/licenses/LICENSE-2.0.html">Apache 2 licence</a>, without any warrantly
</BODY>
</HTML>
|
lafayette/JBTT
|
framework/documentation/api/play/db/helper/class-use/SqlSelect.html
|
HTML
|
mit
| 18,190
|
'use strict';
var fs = require('fs-extra')
, async = require('async')
, nconf = require('nconf');
var config = nconf.file('./conf/pp.' + (process.env.NODE_ENV || 'development') + '.json').load();
require('date-utils');
var pp = {};
pp.poetry = "";
pp.poetryPlain = "";
pp.rawPoetry = [];
pp.cleanPoetry = [];
pp.checkSum = 0;
pp.isFeedFresh = function(cb) {
// checks if conf.Feed is older than conf.maxAgeInMinutes
console.log('\tisFeedFresh checking how old feed is');
console.log(config.feed);
fs.stat(config.feed, function(err, stats) {
if (err) {
if (err.errno === 34) {
console.error('\tisFeedFresh error: Feed not found!');
cb(new Error('Feed not found!'));
} else {
console.error('\tisFeedFresh Unhandled error: %s', JSON.stringify(err, null, 4));
cb(err);
}
} else {
var feed = new Date(stats.mtime)
, now = new Date()
, delta = feed.getMinutesBetween(now);
console.log('\tisFeedFresh stats:\n\t\t%s\n\t\tnow %s\n\t\tdelta (min) %s\n\t\tthreshold (min) %s', feed, now, delta, config.maxAgeInMinutes);
cb(null, delta < config.maxAgeInMinutes);
}
});
};
function start(cb) {
console.log('start');
return cb(null, config.url);
}
var downloadFeed = require('./download.js').downloadFeed
, parseTweets = require('./parseTweets.js').parseTweets
, saveFile = require('./archiveFile.js').saveFile
, saveAndArchiveFile = require('./archiveFile.js').saveAndArchiveFile
, cleanText = require('./sanitiseTweets.js').cleanText
, createMatrix = require('./createMatrix.js').createMatrix
, createPlainText = require('./createPlainText.js').createPlainText;
function finished(d, cb) { // mock cleanText
console.log('finished d: %s', typeof d);
cb(null);
}
pp.updateFeed = function(cb) {
var waterfall = [start, downloadFeed, saveAndArchiveFile, parseTweets, saveAndArchiveFile, cleanText, saveAndArchiveFile,
//FIXME: refactor
function glue(data, cb) {
createMatrix(data, function(err, file, data2, encoding) {
if (err) {
return cb(err);
}
saveFile(file, data2, encoding, function(meh) {
console.log('created banner: %s', typeof meh);
createPlainText(data, function(err, file, data3, encoding) {
saveFile(file, data3, encoding, function(meh) {
console.log('created plain: %s', typeof meh);
cb(null, meh); // :(
}); // saveFileInner
}); // createPlainText
}); // saveFile outer
}); // createMatrix
},finished];
console.log('\tstart time: %s', new Date());
async.waterfall(waterfall, function finished(err) {
if (err) {
// 500
console.log('\tupdateFeed error: %s', JSON.stringify(err, null, 4));
cb(err);
} else {
console.log('\tupdateFeed completed successfully!');
console.log('\tend time: %s', new Date());
cb(null);
}
});
};
pp.ok = function() { return true; };
module.exports = pp;
|
booyaa/poisonpentametron
|
lib/poisonpentametron.js
|
JavaScript
|
mit
| 3,118
|
package com.xeiam.xchange.dto;
import java.math.BigDecimal;
import java.util.Date;
import com.xeiam.xchange.currency.CurrencyPair;
/**
* Data object representing an order
*/
public class Order {
public enum OrderType {
/**
* Buying order (you're making an offer)
*/
BID,
/**
* Selling order (you're asking for offers)
*/
ASK
}
/**
* Order type i.e. bid or ask
*/
private final OrderType type;
/**
* Amount to be ordered / amount that was ordered
*/
private final BigDecimal tradableAmount;
/**
* The currency pair
*/
private final CurrencyPair currencyPair;
/**
* An identifier that uniquely identifies the order
*/
private final String id;
/**
* The timestamp on the order
*/
private final Date timestamp;
/**
* @param type Either BID (buying) or ASK (selling)
* @param tradableAmount The amount to trade
* @param CurrencyPair currencyPair The identifier (e.g. BTC/USD)
* @param id An id (usually provided by the exchange)
* @param timestamp the absolute time for this order
*/
public Order(OrderType type, BigDecimal tradableAmount, CurrencyPair currencyPair, String id, Date timestamp) {
this.type = type;
this.tradableAmount = tradableAmount;
this.currencyPair = currencyPair;
this.id = id;
this.timestamp = timestamp;
}
/**
* @return The type (BID or ASK)
*/
public OrderType getType() {
return type;
}
/**
* @return The amount to trade
*/
public BigDecimal getTradableAmount() {
return tradableAmount;
}
public CurrencyPair getCurrencyPair() {
return currencyPair;
}
/**
* @return A unique identifier (normally provided by the exchange)
*/
public String getId() {
return id;
}
public Date getTimestamp() {
return timestamp;
}
@Override
public String toString() {
return "Order [type=" + type + ", tradableAmount=" + tradableAmount + ", currencyPair=" + currencyPair + ", id=" + id + ", timestamp="
+ timestamp + "]";
}
@Override
public int hashCode() {
int hash = 7;
hash = 83 * hash + (this.type != null ? this.type.hashCode() : 0);
hash = 83 * hash + (this.tradableAmount != null ? this.tradableAmount.hashCode() : 0);
hash = 83 * hash + (this.currencyPair != null ? this.currencyPair.hashCode() : 0);
hash = 83 * hash + (this.id != null ? this.id.hashCode() : 0);
hash = 83 * hash + (this.timestamp != null ? this.timestamp.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Order other = (Order) obj;
if (this.type != other.type) {
return false;
}
if ((this.tradableAmount == null) ? (other.tradableAmount != null) : this.tradableAmount.compareTo(other.tradableAmount) != 0) {
return false;
}
if ((this.currencyPair == null) ? (other.currencyPair != null) : !this.currencyPair.equals(other.currencyPair)) {
return false;
}
if ((this.id == null) ? (other.id != null) : !this.id.equals(other.id)) {
return false;
}
if (this.timestamp != other.timestamp && (this.timestamp == null || !this.timestamp.equals(other.timestamp))) {
return false;
}
return true;
}
}
|
okazia/XChange
|
xchange-core/src/main/java/com/xeiam/xchange/dto/Order.java
|
Java
|
mit
| 3,380
|
<?php
namespace Geo\Test\Model\Behavior;
use Cake\Core\Configure;
use Cake\Database\Driver\Mysql;
use Cake\Database\Driver\Postgres;
use Cake\Database\Expression\QueryExpression;
use Cake\Database\ValueBinder;
use Cake\Datasource\ConnectionManager;
use Cake\ORM\Entity;
use Cake\ORM\TableRegistry;
use Cake\TestSuite\TestCase;
use Geo\Geocoder\Calculator;
use Geo\Geocoder\Geocoder;
use Geocoder\Model\Coordinates;
use InvalidArgumentException;
use TestApp\Controller\TestController;
class GeocoderBehaviorTest extends TestCase {
/**
* @var array<string>
*/
protected $fixtures = [
'plugin.Geo.Addresses',
];
/**
* @var \Cake\ORM\Table|\Geo\Model\Behavior\GeocoderBehavior;
*/
protected $Addresses;
/**
* @var \Cake\Database\Connection
*/
protected $db;
/**
* setUp
*
* @return void
*/
public function setUp(): void {
parent::setUp();
Configure::write('Geocoder.locale', 'DE');
$this->Addresses = TableRegistry::get('Geo.Addresses');
$this->Addresses->addBehavior('Geocoder');
$this->db = ConnectionManager::get('test');
}
/**
* teardown
*
* @return void
*/
public function tearDown(): void {
parent::tearDown();
unset($this->Addresses, $this->Addresses);
TableRegistry::clear();
}
/**
* @return void
*/
public function testDistance() {
$expr = $this->Addresses->distanceExpr(12, 14);
$expected = '(6371.04 * ACOS(((COS(((PI() / 2) - RADIANS((90 - Addresses.lat)))) * COS(PI()/2 - RADIANS(90 - 12)) * COS((RADIANS(Addresses.lng) - RADIANS(:param0)))) + (SIN(((PI() / 2) - RADIANS((90 - Addresses.lat)))) * SIN(((PI() / 2) - RADIANS(90 - 12)))))))';
$binder = new ValueBinder();
$result = $expr->sql($binder);
$this->assertEquals($expected, $result);
$this->Addresses->removeBehavior('Geocoder');
$this->Addresses->addBehavior('Geocoder', ['lat' => 'x', 'lng' => 'y']);
$expr = $this->Addresses->distanceExpr(12.1, 14.2);
//$expected = '6371.04 * ACOS(COS(PI()/2 - RADIANS(90 - Addresses.x)) * COS(PI()/2 - RADIANS(90 - 12.1)) * COS(RADIANS(Addresses.y) - RADIANS(14.2)) + SIN(PI()/2 - RADIANS(90 - Addresses.x)) * SIN(PI()/2 - RADIANS(90 - 12.1)))';
$this->assertInstanceOf(QueryExpression::class, $expr);
$this->Addresses->removeBehavior('Geocoder');
$this->Addresses->addBehavior('Geocoder', ['lat' => 'x', 'lng' => 'y']);
$expr = $this->Addresses->distanceExpr('User.lat', 'User.lng');
//$expected = '6371.04 * ACOS(COS(PI()/2 - RADIANS(90 - Addresses.x)) * COS(PI()/2 - RADIANS(90 - User.lat)) * COS(RADIANS(Addresses.y) - RADIANS(User.lng)) + SIN(PI()/2 - RADIANS(90 - Addresses.x)) * SIN(PI()/2 - RADIANS(90 - User.lat)))';
$this->assertInstanceOf(QueryExpression::class, $expr);
}
/**
* @return void
*/
public function testDistanceField() {
$condition = $this->Addresses->distanceField(12, 14);
//$expected = '6371.04 * ACOS(COS(PI()/2 - RADIANS(90 - Addresses.lat)) * COS(PI()/2 - RADIANS(90 - 12)) * COS(RADIANS(Addresses.lng) - RADIANS(14)) + SIN(PI()/2 - RADIANS(90 - Addresses.lat)) * SIN(PI()/2 - RADIANS(90 - 12))) AS Addresses.distance';
$this->assertInstanceOf(QueryExpression::class, $condition['Addresses.distance']);
}
/**
* @return void
*/
public function testSetDistanceAsVirtualField() {
$driver = $this->db->getDriver();
$this->skipIf(!($driver instanceof Mysql || $driver instanceof Postgres), 'The virtualFields test is only compatible with Mysql/Postgres.');
$options = ['lat' => 13.3, 'lng' => 19.2]; //array('order' => array('Address.distance' => 'ASC'));
$query = $this->Addresses->find()->find('distance', $options);
$result = $query->toArray();
$this->assertTrue($result[0]['distance'] < $result[1]['distance']);
$this->assertTrue($result[1]['distance'] < $result[2]['distance']);
$this->assertTrue($result[0]['distance'] > 620 && $result[0]['distance'] < 650);
}
/**
* @return void
*/
public function testSetDistanceAsValueObject() {
$driver = $this->db->getDriver();
$this->skipIf(!($driver instanceof Mysql || $driver instanceof Postgres), 'The virtualFields test is only compatible with Mysql/Postgres.');
$coordinates = new Coordinates(13.3, 19.2);
$options = ['coordinates' => $coordinates];
$query = $this->Addresses->find()->find('distance', $options);
$result = $query->toArray();
$this->assertTrue($result[0]['distance'] < $result[1]['distance']);
$this->assertTrue($result[1]['distance'] < $result[2]['distance']);
$this->assertTrue($result[0]['distance'] > 620 && $result[0]['distance'] < 650);
}
/**
* @return void
*/
public function testFindDistanceOptionsMissing() {
$this->expectException(InvalidArgumentException::class);
$options = [];
$this->Addresses->find()->find('distance', $options);
}
/**
* @return void
*/
public function testSetDistanceAsVirtualFieldInMiles() {
$driver = $this->db->getDriver();
$this->skipIf(!($driver instanceof Mysql || $driver instanceof Postgres), 'The virtualFields test is only compatible with Mysql/Postgres.');
$this->Addresses->removeBehavior('Geocoder'); //FIXME: Shouldnt be necessary ideally
$this->Addresses->addBehavior('Geocoder', ['unit' => Calculator::UNIT_MILES]);
$options = ['lat' => 13.3, 'lng' => 19.2]; //$options = array('order' => array('Address.distance' => 'ASC'));
$res = $this->Addresses->find()->find('distance', $options)->toArray();
$this->assertTrue($res[0]['distance'] < $res[1]['distance']);
$this->assertTrue($res[1]['distance'] < $res[2]['distance']);
$this->assertTrue($res[0]['distance'] > 390 && $res[0]['distance'] < 410);
}
/**
* @return void
*/
public function testPagination() {
$driver = $this->db->getDriver();
$this->skipIf(!($driver instanceof Mysql || $driver instanceof Postgres), 'The virtualFields test is only compatible with Mysql/Postgres.');
$controller = new TestController();
$controller->Addresses->addBehavior('Geocoder');
$options = ['lat' => 13.3, 'lng' => 19.2, 'distance' => 3000];
/** @var \Cake\ORM\Query $query */
$query = $controller->Addresses->find('distance', $options);
$query->order(['distance' => 'ASC']);
$res = $controller->paginate($query)->toArray();
$this->assertEquals(2, count($res));
$this->assertTrue($res[0]['distance'] < $res[1]['distance']);
}
/**
* @return void
*/
public function testValidate() {
$is = $this->Addresses->validateLatitude(44);
$this->assertTrue($is);
$is = $this->Addresses->validateLatitude(110);
$this->assertFalse($is);
$is = $this->Addresses->validateLongitude(150);
$this->assertTrue($is);
$is = $this->Addresses->validateLongitude(-190);
$this->assertFalse($is);
$this->Addresses->getValidator()->add('lat', 'validateLatitude', ['provider' => 'table', 'rule' => 'validateLatitude', 'message' => 'validateLatitudeError']);
$this->Addresses->getValidator()->add('lng', 'validateLongitude', ['provider' => 'table', 'rule' => 'validateLongitude', 'message' => 'validateLongitudeError']);
$data = [
'lat' => 44,
'lng' => 190,
];
$entity = $this->Addresses->newEntity($data);
$expectedErrors = [
'lng' => [
'validateLongitude' => __('validateLongitudeError'),
],
];
$this->assertEquals($expectedErrors, $entity->getErrors());
}
/**
* @return void
*/
public function testBasic() {
$this->Addresses->removeBehavior('Geocoder');
$this->Addresses->addBehavior('Geocoder', ['address' => ['street', 'zip', 'city']]);
$data = [
'street' => 'Krebenweg 22',
'zip' => '74523',
'city' => 'Bibersfeld',
];
$entity = $this->_getEntity($data);
$res = $this->Addresses->save($entity);
$this->assertTrue(!empty($res['lat']) && !empty($res['lng']));
$this->assertTrue(round($res['lat']) === 49.0 && round($res['lng']) === 10.0);
// inconclusive
$data = [
//'street' => 'Leopoldstraße',
'city' => 'München',
];
$entity = $this->_getEntity($data);
$res = $this->Addresses->save($entity);
$this->assertTrue(!empty($res['lat']) && !empty($res['lng']));
//FIXME
$this->assertStringContainsString('München', $res['formatted_address']);
//$this->assertEquals('München, Deutschland', $res['formatted_address']);
$data = [
'city' => 'Bibersfeld',
];
$entity = $this->_getEntity($data);
$res = $this->Addresses->save($entity);
$this->assertTrue(!empty($res));
}
/**
* @return void
*/
public function testMinAccLow() {
$this->Addresses->removeBehavior('Geocoder');
$this->Addresses->addBehavior('Geocoder', ['minAccuracy' => Geocoder::TYPE_COUNTRY]);
$data = [
'city' => 'Deutschland',
];
$entity = $this->_getEntity($data);
$res = $this->Addresses->save($entity);
$this->assertEquals('Deutschland', $res['city']);
$this->assertTrue((int)$res['lat'] && (int)$res['lng']);
}
/**
* @return void
*/
public function testMinAccHigh() {
$this->Addresses->removeBehavior('Geocoder');
$this->Addresses->addBehavior('Geocoder', ['minAccuracy' => Geocoder::TYPE_POSTAL]);
$data = [
'city' => 'Deutschland',
];
$entity = $this->_getEntity($data);
$res = $this->Addresses->save($entity);
$this->assertEquals('Deutschland', $res['city']);
//FIXME
//$this->assertTrue(!isset($res['lat']) && !isset($res['lng']));
}
/**
* @return void
*/
public function testMinInc() {
$this->Addresses->removeBehavior('Geocoder');
$this->Addresses->addBehavior('Geocoder', ['minAccuracy' => Geocoder::TYPE_SUBLOC]);
$this->assertEquals(Geocoder::TYPE_SUBLOC, $this->Addresses->behaviors()->Geocoder->getConfig('minAccuracy'));
$data = [
//'street' => 'Leopoldstraße',
'city' => 'Neustadt',
];
$entity = $this->_getEntity($data);
$res = $this->Addresses->save($entity);
$this->assertEquals('Neustadt', $res['city']);
//FIXME
//$this->assertTrue(!isset($res['lat']) && !isset($res['lng']));
}
/**
* @return void
*/
public function testMinIncAllowed() {
$this->Addresses->removeBehavior('Geocoder');
$this->Addresses->addBehavior('Geocoder', ['allow_inconclusive' => true]);
$data = [
'city' => 'Neustadt',
];
$entity = $this->_getEntity($data);
$res = $this->Addresses->save($entity);
$this->assertEquals('Neustadt', $res['city']);
$this->assertTrue(!empty($res['lat']) && !empty($res['lng']));
}
/**
* @return void
*/
public function testExpect() {
$this->Addresses->removeBehavior('Geocoder');
$this->Addresses->addBehavior('Geocoder', ['expect' => [Geocoder::TYPE_POSTAL]]);
$data = [
'city' => 'Berlin, Deutschland',
];
$entity = $this->_getEntity($data);
$res = $this->Addresses->save($entity);
$this->assertTrue(empty($res['lat']) && empty($res['lng']));
$data = [
'city' => '74523, Deutschland',
];
$entity = $this->_getEntity($data);
$res = $this->Addresses->save($entity);
$this->assertStringContainsString('74523 Schwäbisch Hall', $res['formatted_address']);
//$this->assertEquals('74523 Schwäbisch Hall, Deutschland', $res['formatted_address']);
$this->assertTrue(!empty($res['lat']) && !empty($res['lng']));
}
/**
* @return void
*/
public function testAllowEmpty() {
$this->Addresses->removeBehavior('Geocoder');
$this->Addresses->addBehavior('Geocoder', ['expect' => [Geocoder::TYPE_POSTAL]]);
$data = [
'city' => '',
];
$entity = $this->_getEntity($data);
$res = $this->Addresses->save($entity);
$this->assertTrue((bool)$res);
}
/**
* @return void
*/
public function testAllowEmptyFalse() {
$this->Addresses->removeBehavior('Geocoder');
$this->Addresses->addBehavior('Geocoder', [
'allowEmpty' => false,
'expect' => [Geocoder::TYPE_POSTAL],
'lat' => 'latitude',
'lng' => 'longitude',
]);
$data = [
'city' => '',
];
$entity = $this->_getEntity($data);
$res = $this->Addresses->save($entity);
$this->assertFalse($res);
$data = [
'first_name' => 'ADmad',
'latitude' => 40,
'longitude' => 16,
];
$entity = $this->_getEntity($data);
$res = $this->Addresses->save($entity);
$this->assertTrue((bool)$res);
}
/**
* @return void
*/
public function testOverwrite() {
$this->Addresses->removeBehavior('Geocoder');
$this->Addresses->addBehavior('Geocoder', [
'allowEmpty' => false,
'address' => ['street', 'zip', 'city'],
]);
$data = [
'street' => 'Krebenweg 22',
'zip' => '74523',
'city' => 'Bibersfeld',
'lat' => 40,
'lng' => 16,
];
$entity = $this->_getEntity($data);
$res = $this->Addresses->save($entity);
// Lat, lng is overwritten since `overwrite` is true by default.
$this->assertTrue(round($res['lat']) === 49.0 && round($res['lng']) === 10.0);
$this->Addresses->removeBehavior('Geocoder');
$this->Addresses->addBehavior('Geocoder', [
'overwrite' => false,
'allowEmpty' => false,
'address' => ['street', 'zip', 'city'],
]);
$data = [
'street' => 'Krebenweg 22',
'zip' => '74523',
'city' => 'Bibersfeld',
'lat' => 40,
'lng' => 16,
];
$entity = $this->_getEntity($data);
$res = $this->Addresses->save($entity);
$this->assertTrue((bool)$res);
$this->assertTrue($res['lat'] === 40 && $res['lng'] === 16);
// Editing address fields does not modifying lat, lng since they are already set.
$res->street = 'blah blah';
$res->zip = 'xxxxxx';
$res = $this->Addresses->save($entity);
$this->assertTrue((bool)$res);
$this->assertTrue($res['lat'] === 40 && $res['lng'] === 16);
}
/**
* Gets a new Entity
*
* @param array $data
* @return \Cake\ORM\Entity
*/
protected function _getEntity($data) {
return new Entity($data);
}
}
|
dereuromark/cakephp-geo
|
tests/TestCase/Model/Behavior/GeocoderBehaviorTest.php
|
PHP
|
mit
| 13,523
|
import boto3
import logging
import argparse
import os
from botocore.exceptions import ClientError
from boto3.dynamodb.conditions import Key, Attr
import json
import decimal
import time
import datetime
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import contracts
from rest import IGParams, IGClient
import asyncio
import uuid
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
if o % 1 > 0:
return float(o)
else:
return int(o)
return super(DecimalEncoder, self).default(o)
class Utils(object):
def __init__(self):
pass
@staticmethod
def reliable(func):
def _decorator(self, *args, **kwargs):
tries = 0
result = func(self, *args, **kwargs)
if result is None:
while result is None and tries < 10:
tries += 1
time.sleep(2 ** tries)
result = func(self, *args, **kwargs)
return result
return _decorator
class CapsuleParams(object):
def __init__(self):
self.Region = ''
self.Instance = ''
self.Email = ''
self.Iam = ''
self.User = ''
self.Password = ''
self.Smtp = ''
class CapsuleController(object):
def __init__(self, params):
self.secDef = contracts.SecurityDefinition()
self.Email = params.Email
self.Iam = params.Iam
self.User = params.User
self.Password = params.Password
self.Smtp = params.Smtp
self.Logger = logging.getLogger()
self.Logger.setLevel(logging.INFO)
ec2 = boto3.resource('ec2', region_name=params.Region)
self.__Instance = ec2.Instance(params.Instance)
db = boto3.resource('dynamodb', region_name=params.Region)
self.__QuotesEod = db.Table('Quotes.EOD')
self.__Securities = db.Table('Securities')
self.__Orders = db.Table('Orders')
s3 = boto3.resource('s3')
debug = os.environ['DEBUG_FOLDER']
self.__debug = s3.Object(debug, 'vix_roll.txt')
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(threadName)s - %(message)s')
self.Logger.info('InstanceController Created. Region: %s Instance: %s' % (params.Region, params.Instance))
def AttemptsCount(self):
timestamp = int((datetime.datetime.now() - datetime.timedelta(hours=2)).timestamp()) * 1000
logs = boto3.client('logs')
log_group = '/aws/docker/Capsule'
data = logs.describe_log_streams(logGroupName=log_group, orderBy='LastEventTime', descending=True)
streams = filter(lambda x: x['creationTime'] > timestamp, data['logStreams'])
count = 0
for stream in streams:
lines = logs.get_log_events(logGroupName=log_group,
logStreamName=stream['logStreamName'])
for line in lines['events']:
if 'LogStream Created:' in line['message']:
count += 1
self.Logger.info('Capsule ran %s times in the last 2 hours' % count)
return count
def SendEmail(self, text):
msg = MIMEMultipart('alternative')
msg['Subject'] = 'NIGHTWATCH ALERT'
msg['From'] = self.Email
msg['To'] = self.Email
mime_text = MIMEText(text, 'html')
msg.attach(mime_text)
server = smtplib.SMTP(self.Smtp, 587, timeout=10)
server.set_debuglevel(10)
server.starttls()
server.ehlo()
server.login(self.User, self.Password)
server.sendmail(self.Email, self.Email, msg.as_string())
res = server.quit()
self.Logger.info(res)
def ValidateStrategy(self):
today = datetime.date.today().strftime("%Y%m%d")
fileObj = self.__debug.get()['Body']
ch = fileObj.read(1)
line = ''
while ch:
if ch.decode("utf-8") == '\n':
if today in line:
return True
line = ''
else:
line += ch.decode("utf-8")
ch = fileObj.read(1)
return False
@Utils.reliable
def SuspendTrading(self, symbol, broker):
try:
response = self.__Securities.update_item(
Key={
'Symbol': symbol,
'Broker': broker,
},
UpdateExpression="set #te = :te",
ExpressionAttributeNames={
'#te': 'TradingEnabled'
},
ExpressionAttributeValues={
':te': False
},
ReturnValues="UPDATED_NEW")
except ClientError as e:
self.Logger.error(e.response['Error']['Message'])
except Exception as e:
self.Logger.error(e)
else:
self.Logger.info('Security Updated')
self.Logger.info(json.dumps(response, indent=4, cls=DecimalEncoder))
return response
@Utils.reliable
def SendOrder(self, symbol, maturity, side, size, price, orderType, fillTime, dealId, broker, productType):
try:
order = {
"Side": side,
"Size": decimal.Decimal(str(size)),
"OrdType": orderType}
trade = {
"FillTime": fillTime,
"Side": side,
"FilledSize": decimal.Decimal(str(size)),
"Price": decimal.Decimal(str(price)),
"Broker": {"Name": broker, "RefType": "dealId", "Ref": dealId},
}
strategy = {
"Name": "SYSTEM",
"Reason": "STOP_TRIGGERED"
}
response = self.__Orders.update_item(
Key={
'OrderId': str(uuid.uuid4().hex),
'TransactionTime': str(time.time()),
},
UpdateExpression="set #st = :st, #s = :s, #m = :m, #p = :p, #b = :b, #o = :o, #t = :t, #str = :str",
ExpressionAttributeNames={
'#st': 'Status',
'#s': 'Symbol',
'#m': 'Maturity',
'#p': 'ProductType',
'#b': 'Broker',
'#o': 'Order',
'#t': 'Trade',
'#str': 'Strategy'
},
ExpressionAttributeValues={
':st': 'FILLED',
':s': symbol,
':m': maturity,
':p': productType,
':b': broker,
':o': order,
':t': trade,
':str': strategy
},
ReturnValues="UPDATED_NEW")
except ClientError as e:
self.Logger.error(e.response['Error']['Message'])
except Exception as e:
self.Logger.error(e)
else:
self.Logger.info('Order Created')
self.Logger.info(json.dumps(response, indent=4, cls=DecimalEncoder))
return response
def FindSystemStopOrders(self):
"""
Update Orders table if the stop order was executed by the broker
:return:
None
"""
params = IGParams()
params.Url = os.environ['IG_URL']
params.Key = os.environ['X_IG_API_KEY']
params.Identifier = os.environ['IDENTIFIER']
params.Password = os.environ['PASSWORD']
self.Logger.info('Checking if any stop order was triggered')
async def read():
async with IGClient(params, self.Logger) as client:
auth = await client.Login()
self.Logger.info('Auth: %s' % auth)
lastMonth = datetime.date.today() - datetime.timedelta(days=30)
activities = await client.GetActivities(lastMonth.strftime('%Y-%m-%d'), True)
self.Logger.info('activities: %s' % activities)
await client.Logout()
if activities is not None and 'activities' in activities and len(activities['activities']) > 0:
stopTriggered = [tran for tran in activities['activities']
if tran['channel'] == 'SYSTEM' and 'details' in tran]
if len(stopTriggered) == 0:
self.Logger.info('No stops were triggered')
return
filled = self.GetOrders('Status', 'FILLED')
self.Logger.info('All filled %s' % filled)
for tran in stopTriggered:
for action in tran['details']['actions']:
if action['actionType'] == 'POSITION_CLOSED':
self.Logger.info('affectedDealId: %s' % action['affectedDealId'])
already_done = [o for o in filled if 'Broker'in o['Trade'] and 'Ref'
in o['Trade']['Broker'] and o['Trade']['Broker']['Ref'] == tran['dealId']
and o['Strategy']['Name'] == 'SYSTEM']
if len(already_done) == 1:
self.Logger.info('Already filled this unaccounted stop %s' % tran['dealId'])
continue
found = [o for o in filled if 'Broker'in o['Trade'] and 'Ref' in o['Trade']['Broker']
and o['Trade']['Broker']['Ref'] == action['affectedDealId']]
if len(found) == 1:
f = found[0]
self.Logger.info('Unaccounted stop found %s' % found)
self.SuspendTrading(f['Symbol'], 'IG')
self.SendOrder(f['Symbol'], f['Maturity'], tran['details']['direction'],
tran['details']['size'], tran['details']['level'],
'STOP', tran['date'], tran['dealId'], 'IG', f['ProductType'])
self.SendEmail('STOP Order was triggered by IG. Trading in %s is suspended'
% f['Symbol'])
app_loop = asyncio.get_event_loop()
app_loop.run_until_complete(read())
def ValidateExecutor(self):
pending = self.GetOrders('Status', 'PENDING')
if pending is not None and len(pending) > 0:
self.SendEmail('There are %s PENDING Orders in Chaos' % len(pending))
failed = self.GetOrders('Status', 'FAILED')
if failed is not None and len(failed) > 0:
self.SendEmail('There are %s FAILED Orders in Chaos' % len(failed))
def EndOfDay(self):
allFound = True
for security in filter(lambda x: x['SubscriptionEnabled'], self.GetSecurities()):
today = datetime.date.today().strftime("%Y%m%d")
symbols = []
if security['ProductType'] == 'IND':
symbols = [security['Symbol']]
if security['ProductType'] == 'FUT':
symbols = self.secDef.get_futures(security['Symbol'], 2) # get two front months
for symbol in symbols:
found = self.GetQuotes(symbol, today)
if len(found) > 0:
self.Logger.info('Found Symbols: %s' % found)
else:
self.Logger.error('Failed to find data for %s' % symbol)
allFound &= len(found) > 0
if allFound:
self.Logger.info('All Found. Stopping EC2 Instance')
if self.IsInstanceRunning():
self.StopInstance()
if not self.ValidateStrategy():
self.SendEmail('The VIX Roll strategy left no TRACE file today')
else:
self.Logger.info('Not All Found. Will try again. Restarting EC2 Instance')
if self.IsInstanceRunning():
self.StopInstance()
if self.AttemptsCount() >= 3:
self.SendEmail('Capsule could not retrieve market data after %s attempts' % str(3))
return
self.StartInstance()
def IsInstanceRunning(self):
self.Logger.info('Instance Id: %s, State: %s' % (self.__Instance.instance_id, self.__Instance.state))
return self.__Instance.state['Name'] == 'running'
def StartInstance(self):
self.__Instance.start()
self.__Instance.wait_until_running()
self.Logger.info('Started instance: %s' % self.__Instance.instance_id)
def StopInstance(self):
self.__Instance.stop()
self.__Instance.wait_until_stopped()
self.Logger.info('Stopped instance: %s' % self.__Instance.instance_id)
@Utils.reliable
def GetOrders(self, key, value):
try:
self.Logger.info('Calling orders scan attr: %s, %s' % (key, value))
response = self.__Orders.scan(FilterExpression=Attr(key).eq(value))
except ClientError as e:
self.Logger.error(e.response['Error']['Message'])
return None
except Exception as e:
self.Logger.error(e)
return None
else:
if 'Items' in response:
return response['Items']
@Utils.reliable
def GetSecurities(self):
try:
self.Logger.info('Calling securities scan ...')
response = self.__Securities.scan(FilterExpression=Attr('SubscriptionEnabled').eq(True))
except ClientError as e:
self.Logger.error(e.response['Error']['Message'])
return None
except Exception as e:
self.Logger.error(e)
return None
else:
if 'Items' in response:
return response['Items']
@Utils.reliable
def GetQuotes(self, symbol, date):
try:
self.Logger.info('Calling quotes query Date key: %s' % date)
response = self.__QuotesEod.query(
KeyConditionExpression=Key('Symbol').eq(symbol) & Key('Date').eq(date)
)
except ClientError as e:
self.Logger.error(e.response['Error']['Message'])
return None
except Exception as e:
self.Logger.error(e)
return None
else:
self.Logger.info(json.dumps(response, indent=4, cls=DecimalEncoder))
if 'Items' in response:
return response['Items']
def lambda_handler(event, context):
params = CapsuleParams()
params.Region = os.environ["NIGHT_WATCH_REGION"]
params.Instance = os.environ["NIGHT_WATCH_INSTANCE"]
params.Email = os.environ["NIGHT_WATCH_EMAIL"]
params.Iam = os.environ["NIGHT_WATCH_IAM"]
params.User = os.environ["NIGHT_WATCH_USER"]
params.Password = os.environ["NIGHT_WATCH_PASSWORD"]
params.Smtp = os.environ["NIGHT_WATCH_SMTP"]
controller = CapsuleController(params)
try:
controller.FindSystemStopOrders()
except Exception as e:
controller.Logger.error('FindSystemStopOrders: %s' % e)
controller.ValidateExecutor()
controller.EndOfDay()
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--region', help='AWS region', required=True)
parser.add_argument('--instance', help='EC2 instance', required=True)
parser.add_argument('--email', help='Email address', required=True)
parser.add_argument('--iam', help='IAM Role', required=True)
parser.add_argument('--user', help='SMTP User', required=True)
parser.add_argument('--password', help='SMTP Password', required=True)
parser.add_argument('--smtp', help='SMTP Address', required=True)
parser.add_argument('--debug', help='Debug Folder', required=True)
args = parser.parse_args()
os.environ["NIGHT_WATCH_REGION"] = args.region
os.environ["NIGHT_WATCH_INSTANCE"] = args.instance
os.environ["NIGHT_WATCH_EMAIL"] = args.email
os.environ["NIGHT_WATCH_IAM"] = args.iam
os.environ["NIGHT_WATCH_USER"] = args.user
os.environ["NIGHT_WATCH_PASSWORD"] = args.password
os.environ["NIGHT_WATCH_SMTP"] = args.smtp
os.environ["DEBUG_FOLDER"] = args.debug
event = ''
context = ''
lambda_handler(event, context)
if __name__ == "__main__":
main()
|
th3sys/capsule
|
nightwatch.py
|
Python
|
mit
| 16,596
|
using System.Runtime.InteropServices;
namespace CSCapstone.Arm {
/// <summary>
/// Native ARM Instruction Memory Operand Value.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct NativeArmInstructionMemoryOperandValue {
/// <summary>
/// Operand Value's Base Register.
/// </summary>
public uint BaseRegister;
/// <summary>
/// Operand Value's Index Register.
/// </summary>
public uint IndexRegister;
/// <summary>
/// Operand Value's Index Register Scale.
/// </summary>
public int IndexRegisterScale;
/// <summary>
/// Operand Value's Displacement Value.
/// </summary>
public int Displacement;
}
}
|
BlueSkeye/CSCapstone
|
CSCapstone/Arm/NativeArmInstructionMemoryOperandValue.cs
|
C#
|
mit
| 796
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var laptop = exports.laptop = { "viewBox": "0 0 16 16", "children": [{ "name": "path", "attribs": { "fill": "#000000", "d": "M14 11v-8c0-0.55-0.45-1-1-1h-10c-0.55 0-1 0.45-1 1v8h-2v3h16v-3h-2zM10 13h-4v-1h4v1zM13 11h-10v-7.998c0.001-0.001 0.001-0.001 0.002-0.002h9.996c0.001 0.001 0.001 0.001 0.002 0.002v7.998z" } }] };
|
xuan6/admin_dashboard_local_dev
|
node_modules/react-icons-kit/icomoon/laptop.js
|
JavaScript
|
mit
| 400
|
<?php
/**
* @package Joomla.Platform
* @subpackage Form
*
* @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* Form Rule class for the Joomla Platform.
*
* @package Joomla.Platform
* @subpackage Form
* @since 11.1
*/
class JFormRuleChatcatapi extends JFormRule
{
/**
* Method to test the username for uniqueness.
*
* @param SimpleXMLElement $element The SimpleXMLElement object representing the <field /> tag for the form field object.
* @param mixed $value The form field value to validate.
* @param string $group The field name group control value. This acts as as an array container for the field.
* For example if the field has name="foo" and the group value is set to "bar" then the
* full field name would end up being "bar[foo]".
* @param JRegistry $input An optional JRegistry object with the entire data set to validate against the entire form.
* @param JForm $form The form object for which the field is being tested.
*
* @return boolean True if the value is valid, false otherwise.
*
* @since 11.1
*/
public function test(SimpleXMLElement $element, $value, $group = null, JRegistry $input = null, JForm $form = null)
{
if(strlen($value) == 0 || strlen($value) == 40 ){
return true;
}
else{
$value = '';
return false;
}
}
}
|
bensmiley/Chatcat
|
Joomla!/chatcat_joomla/chatcatapi.php
|
PHP
|
mit
| 1,672
|
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::ServiceFabric::V6_5_0_36
module Models
#
# Describes a Service Fabric application.
#
class ApplicationDescription
include MsRestAzure
# @return [String] The name of the application, including the 'fabric:'
# URI scheme.
attr_accessor :name
# @return [String] The application type name as defined in the
# application manifest.
attr_accessor :type_name
# @return [String] The version of the application type as defined in the
# application manifest.
attr_accessor :type_version
# @return [Array<ApplicationParameter>] List of application parameters
# with overridden values from their default values specified in the
# application manifest.
attr_accessor :parameter_list
# @return [ApplicationCapacityDescription] Describes capacity information
# for services of this application. This description can be used for
# describing the following.
# - Reserving the capacity for the services on the nodes
# - Limiting the total number of nodes that services of this application
# can run on
# - Limiting the custom capacity metrics to limit the total consumption
# of this metric by the services of this application
attr_accessor :application_capacity
# @return [ManagedApplicationIdentityDescription] Managed application
# identity description.
attr_accessor :managed_application_identity
#
# Mapper for ApplicationDescription class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'ApplicationDescription',
type: {
name: 'Composite',
class_name: 'ApplicationDescription',
model_properties: {
name: {
client_side_validation: true,
required: true,
serialized_name: 'Name',
type: {
name: 'String'
}
},
type_name: {
client_side_validation: true,
required: true,
serialized_name: 'TypeName',
type: {
name: 'String'
}
},
type_version: {
client_side_validation: true,
required: true,
serialized_name: 'TypeVersion',
type: {
name: 'String'
}
},
parameter_list: {
client_side_validation: true,
required: false,
serialized_name: 'ParameterList',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'ApplicationParameterElementType',
type: {
name: 'Composite',
class_name: 'ApplicationParameter'
}
}
}
},
application_capacity: {
client_side_validation: true,
required: false,
serialized_name: 'ApplicationCapacity',
type: {
name: 'Composite',
class_name: 'ApplicationCapacityDescription'
}
},
managed_application_identity: {
client_side_validation: true,
required: false,
serialized_name: 'ManagedApplicationIdentity',
type: {
name: 'Composite',
class_name: 'ManagedApplicationIdentityDescription'
}
}
}
}
}
end
end
end
end
|
Azure/azure-sdk-for-ruby
|
data/azure_service_fabric/lib/6.5.0.36/generated/azure_service_fabric/models/application_description.rb
|
Ruby
|
mit
| 4,166
|
from django import template
from django.conf import settings
register = template.Library()
# settings value
@register.assignment_tag
def get_google_maps_key():
return getattr(settings, 'GOOGLE_MAPS_KEY', "")
|
linuxsoftware/mamc-wagtail-site
|
home/templatetags/home_tags.py
|
Python
|
mit
| 217
|
// Modified for MonoGameEngine2D by Pascal Laurin @2014
// Originals can be found at https://github.com/marshallward/TiledSharp
// Original notice below:
// Distributed as part of TiledSharp, Copyright 2012 Marshall Ward
// Licensed under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Linq;
namespace GameFramework.IO.TiledSharp
{
internal class TmxTileset : TmxDocument, ITmxElement
{
internal TmxTileset(XDocument doc, string tmxDir)
: this(doc.Element("tileset"), tmxDir)
{
}
internal TmxTileset(XElement tileset, string tmxDir = "")
{
var firstGid = tileset.Attribute("firstgid");
var source = (string)tileset.Attribute("source");
if (source != null)
{
// Prepend the parent TMX directory if necessary
source = Path.Combine(tmxDir, source);
// source is always preceded by firstgid
this.FirstGid = (int)firstGid;
// Everything else is in the TSX file
var docTileset = this.ReadXml(source);
var ts = new TmxTileset(docTileset, this.TmxDirectory);
this.Name = ts.Name;
this.TileWidth = ts.TileWidth;
this.TileHeight = ts.TileHeight;
this.Spacing = ts.Spacing;
this.Margin = ts.Margin;
this.TileOffset = ts.TileOffset;
this.Image = ts.Image;
this.Terrains = ts.Terrains;
this.Tiles = ts.Tiles;
this.Properties = ts.Properties;
}
else
{
// firstgid is always in TMX, but not TSX
if (firstGid != null)
this.FirstGid = (int)firstGid;
this.Name = (string)tileset.Attribute("name");
this.TileWidth = (int)tileset.Attribute("tilewidth");
this.TileHeight = (int)tileset.Attribute("tileheight");
this.Spacing = (int?)tileset.Attribute("spacing") ?? 0;
this.Margin = (int?)tileset.Attribute("margin") ?? 0;
this.TileOffset = new TmxTileOffset(tileset.Element("tileoffset"));
this.Image = new TmxImage(tileset.Element("image"), tmxDir);
this.Terrains = new TmxList<TmxTerrain>();
var terrainType = tileset.Element("terraintypes");
if (terrainType != null)
{
foreach (var e in terrainType.Elements("terrain"))
this.Terrains.Add(new TmxTerrain(e));
}
this.Tiles = new List<TmxTilesetTile>();
foreach (var tileElement in tileset.Elements("tile"))
{
var tile = new TmxTilesetTile(tileElement, this.Terrains, tmxDir);
this.Tiles.Add(tile);
}
this.Properties = new PropertyDict(tileset.Element("properties"));
}
}
public int FirstGid { get; private set; }
public string Name { get; private set; }
public int TileWidth { get; private set; }
public int TileHeight { get; private set; }
public int Spacing { get; private set; }
public int Margin { get; private set; }
public TmxTileOffset TileOffset { get; private set; }
public TmxImage Image { get; private set; }
public TmxList<TmxTerrain> Terrains { get; private set; }
public List<TmxTilesetTile> Tiles { get; private set; }
public PropertyDict Properties { get; private set; }
// TMX tileset element constructor
}
}
|
plaurin/MonoGameEngine2D
|
GameFramework.IO/TiledSharp/Tileset.cs
|
C#
|
mit
| 3,837
|
import { expectTypeOf } from "expect-type";
import { Model, Op } from 'sequelize';
class MyModel extends Model {}
expectTypeOf(MyModel.count()).toEqualTypeOf<Promise<number>>();
expectTypeOf(MyModel.count({ group: 'tag' })).toEqualTypeOf<Promise<{ [key: string]: number }>>();
expectTypeOf(MyModel.count({ col: 'tag', distinct: true })).toEqualTypeOf<Promise<number>>();
expectTypeOf(MyModel.count({
where: {
updatedAt: {
[Op.gte]: new Date()
}
},
useMaster: false
})).toEqualTypeOf<Promise<number>>();
|
Americas/sequelize
|
types/test/count.ts
|
TypeScript
|
mit
| 525
|
#ifndef WAVE_BIAS_PRIOR_HPP
#define WAVE_BIAS_PRIOR_HPP
#include <gtsam/nonlinear/NonlinearFactor.h>
namespace wave {
template <class T>
class BiasPrior : public gtsam::NoiseModelFactor1<T> {
private:
Eigen::Matrix<double, 3, 1> prior;
public:
BiasPrior(gtsam::Key key,
Eigen::Matrix<double, 3, 1> m,
const gtsam::SharedNoiseModel &model)
: gtsam::NoiseModelFactor1<T>::NoiseModelFactor1(model, key),
prior(m) {}
gtsam::Vector evaluateError(
const T &m, boost::optional<gtsam::Matrix &> H = boost::none) const;
};
}
#include "wave/gtsam/impl/bias_prior_impl.hpp"
#endif // WAVE_BIAS_PRIOR_HPP
|
wavelab/libwave
|
wave_gtsam/include/wave/gtsam/bias_prior.hpp
|
C++
|
mit
| 667
|
<?php
namespace Sds\DoctrineExtensions\Test\Serializer;
use Sds\DoctrineExtensions\Manifest;
use Sds\DoctrineExtensions\Test\BaseTest;
use Sds\DoctrineExtensions\Test\Serializer\TestAsset\Document\Flavour;
class SerializerCustomTypeSerializerTest extends BaseTest {
public function setUp(){
$manifest = new Manifest([
'documents' => [
__NAMESPACE__ . '\TestAsset\Document' => __DIR__ . '/TestAsset/Document'
],
'extension_configs' => [
'extension.serializer' => [
'type_serializers' => [
'string' => 'stringTypeSerializer'
]
]
],
'document_manager' => 'testing.documentmanager',
'service_manager_config' => [
'factories' => [
'testing.documentmanager' => 'Sds\DoctrineExtensions\Test\TestAsset\DocumentManagerFactory',
]
]
]);
$manifest->getServiceManager()->setInvokableClass('stringTypeSerializer', 'Sds\DoctrineExtensions\Test\Serializer\TestAsset\StringSerializer');
$this->documentManager = $manifest->getServiceManager()->get('testing.documentmanager');
$this->serializer = $manifest->getServiceManager()->get('serializer');
}
public function testSerializer(){
$flavour = new Flavour('cherry');
$array = $this->serializer->toArray($flavour, $this->documentManager);
$this->assertEquals('Cherry', $array['name']);
}
public function testApplySerializeMetadataToArray(){
$array = $this->serializer->ApplySerializeMetadataToArray(
['name' => 'cherry'],
'Sds\DoctrineExtensions\Test\Serializer\TestAsset\Document\Flavour'
);
$this->assertEquals('Cherry', $array['name']);
}
public function testUnserializer(){
$data = array(
'name' => 'Cherry'
);
$flavour = $this->serializer->fromArray(
$data,
'Sds\DoctrineExtensions\Test\Serializer\TestAsset\Document\Flavour'
);
$this->assertEquals('cherry', $flavour->getName());
}
}
|
superdweebie/doctrine-extensions
|
tests/Sds/DoctrineExtensions/Test/Serializer/SerializerCustomTypeSerializerTest.php
|
PHP
|
mit
| 2,209
|
(function (module) {
var questionData = function ($q, urlConfig, proxy, adalAuthenticationService) {
var getUserQuestions = function () {
var url = urlConfig.questionsByUserId(adalAuthenticationService.userInfo.userName);
var deferred = $q.defer();
proxy.get(url)
.then(function (response) {
deferred.resolve(response.data);
}, function (error) {
deferred.reject(error)
});
return deferred.promise;
}
var getPublicQuestions = function () {
var url = urlConfig.getPublicQuestions;
var deferred = $q.defer();
proxy.get(url)
.then(function (response) {
deferred.resolve(response.data);
}, function (error) {
deferred.reject(error)
});
return deferred.promise;
}
var getQuestionById = function (id) {
var url = urlConfig.getQuestionById(id);
var deferred = $q.defer();
proxy.get(url)
.then(function (response) {
deferred.resolve(response.data);
}, function (error) {
deferred.reject(error)
});
return deferred.promise;
}
var getQuestionByValue = function (question) {
var url = urlConfig.getQuestionByValue(encodeURIComponent(question));
var deferred = $q.defer();
proxy.get(url)
.then(function (response) {
deferred.resolve(response.data);
}, function (error) {
deferred.reject(error)
});
return deferred.promise;
}
var addQuestion = function (question) {
var url = urlConfig.addNewQuestion;
var deferred = $q.defer();
//Audit
question.createdBy = adalAuthenticationService.userInfo.userName;
question.lastModifiedBy = adalAuthenticationService.userInfo.userName;
var today = new Date();
question.createdOn = today;
question.lastModifedOn = today;
proxy.post(url, question)
.then(function (response) {
deferred.resolve(response.data);
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
var editQuestion = function (question) {
var url = urlConfig.editQuestion;
var deferred = $q.defer();
//Audit
question.lastModifiedBy = adalAuthenticationService.userInfo.userName;
var today = new Date();
question.lastModifedOn = today;
proxy.put(url, question)
.then(function (response) {
deferred.resolve(response.data);
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
var deleteQuestion = function (questionId) {
var url = urlConfig.deleteQuestion(questionId);
var deferred = $q.defer();
proxy.del(url)
.then(function (response) {
deferred.resolve(response.data);
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
return {
getUserQuestions: getUserQuestions,
getPublicQuestions: getPublicQuestions,
getQuestionByValue: getQuestionByValue,
getQuestionById: getQuestionById,
addQuestion: addQuestion,
editQuestion: editQuestion,
deleteQuestion: deleteQuestion
}
}
module.factory("questionsData", questionData);
}(angular.module("question")))
|
patrickCode/Quest
|
src/Quest/App/Web/wwwroot/js/questions/questions.data.js
|
JavaScript
|
mit
| 4,025
|
# --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""Fast R-CNN config system.
This file specifies default config options for Fast R-CNN. You should not
change values in this file. Instead, you should write a config file (in yaml)
and use cfg_from_file(yaml_file) to load it and override the default options.
Most tools in $ROOT/tools take a --cfg option to specify an override file.
- See tools/{train,test}_net.py for example code that uses cfg_from_file()
- See experiments/cfgs/*.yml for example YAML config override files
"""
import os
import os.path as osp
import numpy as np
import math
# `pip install easydict` if you don't have it
from easydict import EasyDict as edict
__C = edict()
# Consumers can get config by:
# from fast_rcnn_config import cfg
cfg = __C
# region proposal network (RPN) or not
__C.IS_RPN = False
__C.FLIP_X = False
__C.INPUT = 'COLOR'
# multiscale training and testing
__C.IS_MULTISCALE = True
__C.IS_EXTRAPOLATING = True
#
__C.REGION_PROPOSAL = 'RPN'
__C.NET_NAME = 'CaffeNet'
__C.SUBCLS_NAME = 'voxel_exemplars'
#
# Training options
#
__C.TRAIN = edict()
__C.TRAIN.VISUALIZE = False
__C.TRAIN.VERTEX_REG = False
__C.TRAIN.GRID_SIZE = 256
__C.TRAIN.CHROMATIC = False
# Scales to compute real features
__C.TRAIN.SCALES_BASE = (0.25, 0.5, 1.0, 2.0, 3.0)
# The number of scales per octave in the image pyramid
# An octave is the set of scales up to half of the initial scale
__C.TRAIN.NUM_PER_OCTAVE = 4
# parameters for ROI generating
__C.TRAIN.SPATIAL_SCALE = 0.0625
__C.TRAIN.KERNEL_SIZE = 5
# Aspect ratio to use during training
__C.TRAIN.ASPECTS = (1, 0.75, 0.5, 0.25)
# Images to use per minibatch
__C.TRAIN.IMS_PER_BATCH = 2
# Minibatch size (number of regions of interest [ROIs])
__C.TRAIN.BATCH_SIZE = 128
# Fraction of minibatch that is labeled foreground (i.e. class > 0)
__C.TRAIN.FG_FRACTION = 0.25
# Overlap threshold for a ROI to be considered foreground (if >= FG_THRESH)
__C.TRAIN.FG_THRESH = (0.5,)
# Overlap threshold for a ROI to be considered background (class = 0 if
# overlap in [LO, HI))
__C.TRAIN.BG_THRESH_HI = (0.5,)
__C.TRAIN.BG_THRESH_LO = (0.1,)
# Use horizontally-flipped images during training?
__C.TRAIN.USE_FLIPPED = True
# Train bounding-box regressors
__C.TRAIN.BBOX_REG = True
# Overlap required between a ROI and ground-truth box in order for that ROI to
# be used as a bounding-box regression training example
__C.TRAIN.BBOX_THRESH = (0.5,)
# Iterations between snapshots
__C.TRAIN.SNAPSHOT_ITERS = 10000
# solver.prototxt specifies the snapshot path prefix, this adds an optional
# infix to yield the path: <prefix>[_<infix>]_iters_XYZ.caffemodel
__C.TRAIN.SNAPSHOT_INFIX = ''
# Use a prefetch thread in roi_data_layer.layer
# So far I haven't found this useful; likely more engineering work is required
__C.TRAIN.USE_PREFETCH = False
# Train using subclasses
__C.TRAIN.SUBCLS = True
# Train using viewpoint
__C.TRAIN.VIEWPOINT = False
# Threshold of ROIs in training RCNN
__C.TRAIN.ROI_THRESHOLD = 0.1
# IOU >= thresh: positive example
__C.TRAIN.RPN_POSITIVE_OVERLAP = 0.7
# IOU < thresh: negative example
__C.TRAIN.RPN_NEGATIVE_OVERLAP = 0.3
# If an anchor statisfied by positive and negative conditions set to negative
__C.TRAIN.RPN_CLOBBER_POSITIVES = False
# Max number of foreground examples
__C.TRAIN.RPN_FG_FRACTION = 0.5
# Total number of examples
__C.TRAIN.RPN_BATCHSIZE = 256
# NMS threshold used on RPN proposals
__C.TRAIN.RPN_NMS_THRESH = 0.7
# Number of top scoring boxes to keep before apply NMS to RPN proposals
__C.TRAIN.RPN_PRE_NMS_TOP_N = 12000
# Number of top scoring boxes to keep after applying NMS to RPN proposals
__C.TRAIN.RPN_POST_NMS_TOP_N = 2000
# Proposal height and width both need to be greater than RPN_MIN_SIZE (at orig image scale)
__C.TRAIN.RPN_MIN_SIZE = 16
# Deprecated (outside weights)
__C.TRAIN.RPN_BBOX_INSIDE_WEIGHTS = (1.0, 1.0, 1.0, 1.0)
# Give the positive RPN examples weight of p * 1 / {num positives}
# and give negatives a weight of (1 - p)
# Set to -1.0 to use uniform example weighting
__C.TRAIN.RPN_POSITIVE_WEIGHT = -1.0
__C.TRAIN.RPN_BASE_SIZE = 16
__C.TRAIN.RPN_ASPECTS = [0.25, 0.5, 0.75, 1, 1.5, 2, 3] # 7 aspects
__C.TRAIN.RPN_SCALES = [2, 2.82842712, 4, 5.65685425, 8, 11.3137085, 16, 22.627417, 32, 45.254834] # 2**np.arange(1, 6, 0.5), 10 scales
#
# Testing options
#
__C.TEST = edict()
__C.TEST.IS_PATCH = False;
__C.TEST.VERTEX_REG = False
__C.TEST.VISUALIZE = False
# Scales to compute real features
__C.TEST.SCALES_BASE = (0.25, 0.5, 1.0, 2.0, 3.0)
# The number of scales per octave in the image pyramid
# An octave is the set of scales up to half of the initial scale
__C.TEST.NUM_PER_OCTAVE = 4
# Aspect ratio to use during testing
__C.TEST.ASPECTS = (1, 0.75, 0.5, 0.25)
# parameters for ROI generating
__C.TEST.SPATIAL_SCALE = 0.0625
__C.TEST.KERNEL_SIZE = 5
# Overlap threshold used for non-maximum suppression (suppress boxes with
# IoU >= this threshold)
__C.TEST.NMS = 0.5
# Experimental: treat the (K+1) units in the cls_score layer as linear
# predictors (trained, eg, with one-vs-rest SVMs).
__C.TEST.SVM = False
# Test using bounding-box regressors
__C.TEST.BBOX_REG = True
# Test using subclass
__C.TEST.SUBCLS = True
# Train using viewpoint
__C.TEST.VIEWPOINT = False
# Threshold of ROIs in testing
__C.TEST.ROI_THRESHOLD = 0.1
__C.TEST.ROI_THRESHOLD_NUM = 80000
__C.TEST.ROI_NUM = 2000
__C.TEST.DET_THRESHOLD = 0.0001
## NMS threshold used on RPN proposals
__C.TEST.RPN_NMS_THRESH = 0.7
## Number of top scoring boxes to keep before apply NMS to RPN proposals
__C.TEST.RPN_PRE_NMS_TOP_N = 6000
## Number of top scoring boxes to keep after applying NMS to RPN proposals
__C.TEST.RPN_POST_NMS_TOP_N = 300
# Proposal height and width both need to be greater than RPN_MIN_SIZE (at orig image scale)
__C.TEST.RPN_MIN_SIZE = 16
#
# MISC
#
# The mapping from image coordinates to feature map coordinates might cause
# some boxes that are distinct in image space to become identical in feature
# coordinates. If DEDUP_BOXES > 0, then DEDUP_BOXES is used as the scale factor
# for identifying duplicate boxes.
# 1/16 is correct for {Alex,Caffe}Net, VGG_CNN_M_1024, and VGG16
__C.DEDUP_BOXES = 1./16.
# Pixel mean values (BGR order) as a (1, 1, 3) array
# These are the values originally used for training VGG16
__C.PIXEL_MEANS = np.array([[[102.9801, 115.9465, 122.7717]]])
# For reproducibility
__C.RNG_SEED = 3
# A small number that's used many times
__C.EPS = 1e-14
# Root directory of project
__C.ROOT_DIR = osp.abspath(osp.join(osp.dirname(__file__), '..', '..'))
# Place outputs under an experiments directory
__C.EXP_DIR = 'default'
# Use GPU implementation of non-maximum suppression
__C.USE_GPU_NMS = True
# Default GPU device id
__C.GPU_ID = 0
def get_output_dir(imdb, net):
"""Return the directory where experimental artifacts are placed.
A canonical path is built using the name from an imdb and a network
(if not None).
"""
path = osp.abspath(osp.join(__C.ROOT_DIR, 'output', __C.EXP_DIR, imdb.name))
if net is None:
return path
else:
return osp.join(path, net.name)
def _add_more_info(is_train):
# compute all the scales
if is_train:
scales_base = __C.TRAIN.SCALES_BASE
num_per_octave = __C.TRAIN.NUM_PER_OCTAVE
else:
scales_base = __C.TEST.SCALES_BASE
num_per_octave = __C.TEST.NUM_PER_OCTAVE
num_scale_base = len(scales_base)
num = (num_scale_base - 1) * num_per_octave + 1
scales = []
for i in xrange(num):
index_scale_base = i / num_per_octave
sbase = scales_base[index_scale_base]
j = i % num_per_octave
if j == 0:
scales.append(sbase)
else:
sbase_next = scales_base[index_scale_base+1]
step = (sbase_next - sbase) / num_per_octave
scales.append(sbase + j * step)
if is_train:
__C.TRAIN.SCALES = scales
else:
__C.TEST.SCALES = scales
print scales
# map the scales to scales for RoI pooling of classification
if is_train:
kernel_size = __C.TRAIN.KERNEL_SIZE / __C.TRAIN.SPATIAL_SCALE
else:
kernel_size = __C.TEST.KERNEL_SIZE / __C.TEST.SPATIAL_SCALE
area = kernel_size * kernel_size
scales = np.array(scales)
areas = np.repeat(area, num) / (scales ** 2)
scaled_areas = areas[:, np.newaxis] * (scales[np.newaxis, :] ** 2)
diff_areas = np.abs(scaled_areas - 224 * 224)
levels = diff_areas.argmin(axis=1)
if is_train:
__C.TRAIN.SCALE_MAPPING = levels
else:
__C.TEST.SCALE_MAPPING = levels
# compute width and height of grid box
if is_train:
area = __C.TRAIN.KERNEL_SIZE * __C.TRAIN.KERNEL_SIZE
aspect = __C.TRAIN.ASPECTS # height / width
else:
area = __C.TEST.KERNEL_SIZE * __C.TEST.KERNEL_SIZE
aspect = __C.TEST.ASPECTS # height / width
num_aspect = len(aspect)
widths = np.zeros((num_aspect), dtype=np.float32)
heights = np.zeros((num_aspect), dtype=np.float32)
for i in xrange(num_aspect):
widths[i] = math.sqrt(area / aspect[i])
heights[i] = widths[i] * aspect[i]
if is_train:
__C.TRAIN.ASPECT_WIDTHS = widths
__C.TRAIN.ASPECT_HEIGHTS = heights
__C.TRAIN.RPN_SCALES = np.array(__C.TRAIN.RPN_SCALES)
else:
__C.TEST.ASPECT_WIDTHS = widths
__C.TEST.ASPECT_HEIGHTS = heights
def _merge_a_into_b(a, b):
"""Merge config dictionary a into config dictionary b, clobbering the
options in b whenever they are also specified in a.
"""
if type(a) is not edict:
return
for k, v in a.iteritems():
# a must specify keys that are in b
if not b.has_key(k):
raise KeyError('{} is not a valid config key'.format(k))
# the types must match, too
if type(b[k]) is not type(v):
raise ValueError(('Type mismatch ({} vs. {}) '
'for config key: {}').format(type(b[k]),
type(v), k))
# recursively merge dicts
if type(v) is edict:
try:
_merge_a_into_b(a[k], b[k])
except:
print('Error under config key: {}'.format(k))
raise
else:
b[k] = v
def cfg_from_file(filename):
"""Load a config file and merge it into the default options."""
import yaml
with open(filename, 'r') as f:
yaml_cfg = edict(yaml.load(f))
_merge_a_into_b(yaml_cfg, __C)
_add_more_info(1)
_add_more_info(0)
|
yuxng/Deep_ISM
|
ISM/lib/ism/config.py
|
Python
|
mit
| 10,824
|
/**
* Automatically generated file. Please do not edit.
* @author Highcharts Config Generator by Karasiq
* @see [[http://api.highcharts.com/highmaps]]
*/
package com.highmaps.config
import scalajs.js, js.`|`
import com.highcharts.CleanJsObject
import com.highcharts.HighchartsUtils._
/**
* @note JavaScript name: <code>series<columnrange>-animation</code>
*/
@js.annotation.ScalaJSDefined
class SeriesColumnrangeAnimation extends com.highcharts.HighchartsGenericObject {
val duration: js.UndefOr[Double] = js.undefined
}
object SeriesColumnrangeAnimation {
/**
*/
def apply(duration: js.UndefOr[Double] = js.undefined): SeriesColumnrangeAnimation = {
val durationOuter: js.UndefOr[Double] = duration
com.highcharts.HighchartsGenericObject.toCleanObject(new SeriesColumnrangeAnimation {
override val duration: js.UndefOr[Double] = durationOuter
})
}
}
|
Karasiq/scalajs-highcharts
|
src/main/scala/com/highmaps/config/SeriesColumnrangeAnimation.scala
|
Scala
|
mit
| 903
|
---
title: Dynameg
inshort: CRM & ERP [Salesforce]
translator: Microsoft Cognitive Services
---
Er bod llawer o Office 365 apiau a gwasanaethau cynrychioli cynhyrchion soffistigedig, mae Dynamics 365 yn cwmpasu ystod o Microsoft rheoli cysylltiadau cwsmeriaid cwmwl (CRM), adnoddau dynol, a (ERP) cynhyrchion sy'n gallu gweithio unig cynllunio adnoddau menter neu gyda'i gilydd i gyflawni llawer o linellau o busnes angen.
Gwerthiant
---------
Gwerthiant yn y deinameg salesforce awtomatiaeth ap. Mae'n eich helpu chi awtomeiddio'r broses gwerthu llawn gan gynnwys cyfrifon, cysylltiadau, arweinwyr, cyfleoedd a gweithgareddau megis penodiadau, e-byst a galwadau ffôn.
Gwasanaeth cwsmeriaid
---------
Mae gwasanaeth cwsmeriaid yn grymuso cynrychiolwyr cymorth cwsmeriaid i reoli achosion ac olrhain datrys materion. Gellir ei ddefnyddio ar gyfer cwsmeriaid mewnol neu allanol.
Maes gwasanaeth
---------
Mae'r maes gwasanaeth rheoli gweithrediadau maes ar gyfer sefydliadau sy'n perfformio gwasanaethau megis dosbarthu, gosod, cynnal a chadw ac arolygiadau. Mae'n arwain yn adnoddau a phobl drwy'r rhyngwyneb dispatcher. Mae apiau symudol yn cefnogi nifer o ddyfeisiau.
Dalent
---------
Mae talent yn cynnig apps i ddenu talent (cyflogi a recriwtio) yn ogystal â gweithwyr newydd onboarding.
Cyllid a gweithrediadau
---------
Cyllid a gweithrediadau yn cynnig galluoedd ariannol gan gynnwys cyfriflyfr cyffredinol, cyfrifon sy'n daladwy, a cyfrifon derbyniadwy yn ogystal â gwasanaethau rheoli gweithrediadau fel cyflenwi awtomatiaeth gadwyn, caffael, rheoli asedau, a logisteg.
Manwerthu
---------
Mae manwerthu yn helpu cwmnïau rheoli gweithrediadau siop a marchnata, megis gwerthiannau, hyrwyddiadau, cyrchu, ac adnewyddu.
Awtomeiddio gwasanaethau prosiect
---------
Mae prosiect gwasanaeth cymhorthion rheoli prosiect, adnoddau optimization, rhagweld prosiect proffidioldeb, a chynyddu cynhyrchiant gyda rhyngwyneb symlach sy'n haws i ddysgu nag mwyaf prosiect offer rheoli. Mae'n cynnwys rhyngwynebau gweledol ar gyfer amserlennu adnoddau, paru pobl i rolau prosiect, a gwylio hynt prosiectau.
Marchnata
---------
Mae marchnata yn darparu awtomatiaeth marchnata a galluoedd rheoli digwyddiad megis e-byst awtomatig, meithrin ymgyrchoedd marchnata, a chofrestru digwyddiad. Mae'n cymryd lle'r Microsoft Dynamics marchnata, a oedd yn dod i ben ym mis Mai 2018.
Busnes canolog
---------
Mae busnes canolog yn cynnwys gwybodaeth ariannol, rheoli cadwyn gyflenwi, gwerthu, gwasanaeth cwsmeriaid, rheoli prosiect, gweithgynhyrchu a galluoedd rheoli warws. Mae ei hanelu tuag at fusnesau bach a chanolig.
Porth
---------
Mae Dynamics 365 yn cynnwys rhyngwyneb Porth, sy'n symleiddio'r mynediad arbennig ar gyfer defnyddwyr achlysurol megis cwsmeriaid, gwerthwyr, a gweithwyr sydd angen gallu hunan-wasanaeth. Mae deinameg Porth storfeydd ei metadata data a ffurfweddiad yn Dynamics 365 ac sy'n parchu rheolaethau diogelwch Dynamics 365.
Gyfluniadau ym Dynamics 365
---------
Dynamics 365 yn ddefnyddio extensible drwy atebion, set o osodiadau personol a gall ei osod yn lle eich Dynamics 365 i ychwanegu endidau newydd, caeau, ymholiadau, adroddiadau, ac elfennau eraill. Gallwch osod ceisiadau lluosog mewn un achos fel y gellir adeiladu atebion ar gyfer eich gofynion unigryw. Mae Microsoft yn cyhoeddi atebion rhad ac am ddim sydd yn weladwy yn Dynamics 365.
Mae'r apiau trydydd parti yn eich galluogi i ymestyn Dynamics 365 ymhellach, gyda cyfleustodau, integreiddio cyn adeiledig a swyddogaethau ychwanegol holl ffordd i weithredu ar gyfer senarios a diwydiannau penodol. Microsoft (https://appsource.microsoft.com/en-US/) [AppSource] yn y farchnad ar-lein ar gyfer yr apiau Dynamics 365 o Microsoft yn ogystal â thrydydd partïon.
Integreiddio Office 365
---------
-Dynamics 365 yn eich galluogi i storio dogfennau yn SharePoint.
-Gall olrhain awtomatig fel cofnodion gweithgarwch rhagolygon negeseuon e-bost a sy'n gysylltiedig ag arweinwyr busnes, cysylltiadau, cyfrifon a cyfleoedd gwerthu.
-Data Gellir allbwn o ddefnyddio templedi Swyddfa Dynamics 365.
-Dynamics 365 gall anfon adroddiadau ac ymholiadau i statig a deinamig ffeiliau Excel yn ogystal ynghylch fformatau eraill fel PDF.
-Gellir defnyddio yn Dynamics 365 gair uno i greu negeseuon e-bost personol.
-Ap Outlook integreiddio Dynamics 365 â Office 365.
Diogelwch
---------
Mae cynnwys yn Dynamics 365 integredig gyda Office 365 diogelwch, sy'n cael ei ddefnyddio fel y darparwr dilysu. Mae'r Dynamics 365 yn cynnig model diogelwch gyfoethog bod diogelwch lefel y cae a'r Cofnod, ac mae'n rheoli mynediad yn seiliedig ar hierarchaeth sefydliad. Mae hyn yn golygu y gellir rheoli mynediad cofnod gan sefydliad uned (e.e., gan alluogi cynrychiolwyr gwerthu dim ond i weld cyfrifon neu gyfleoedd sy'n perthyn iddynt eto gan alluogi rheolwyr i redeg adroddiadau i bob cwsmer).
Hyfforddiant
---------
-[Dynamics ar Academi rhith Microsoft](https://mva.microsoft.com/product-training/microsoft-dynamics#! lang = 1033), Microsoft
Adborth
---------
-[Fforwm syniadau Dynamics 365](https://experience.dynamics.com/ideas/list/?forum=1c8854a6-5cdf-4681-bba8-4b6b806fcf7d)
Adnoddau Microsoft
---------
-[Dynamics 365 dogfennau](https://docs.microsoft.com/en-us/dynamics365/)
-[Dynamics 365 map](https://dynamics.microsoft.com/en-us/release/spring-2018-release/#release-notes)
-[Dynamics 365 ar YouTube](https://www.youtube.com/channel/UCJGCg4rB3QSs8y_1FquelBQ)
-[Dynamics 365 ar Twitter](https://twitter.com/MSFTDynamics365)
-[AppSource](https://appsource.microsoft.com/en-US/)
Ceisiadau tebyg
--------------------
-SalesForce (CRM)
-SugarCRM (CRM)
-Oracle (CRM a rhaglen adnewyddu'r economi)
-SAP (CRM a rhaglen adnewyddu'r economi)
-Accumatica (ERP)
-Netsuite (ERP)
-Zendesk (gwasanaeth cwsmeriaid)
-Diwrnod HCM (adnoddau dynol)
-HubSpot (CRM a marchnata)
Awdur
---------
-[James Townsend](https://twitter.com/jamestownsend), credai Dynamics 365 arweinydd
Metadata
--------
-Cefnogir rhannu allanol
-Mae ap symudol ac ar gael ar gyfer bwrdd gwaith
|
Hexatown/docs
|
microsoft/office365/dynamics/cy.md
|
Markdown
|
mit
| 6,099
|
FROM centos:centos7
MAINTAINER Bin Liu <liubin0329@gmail.com>
# for ruby
RUN yum install -y wget tar gcc g++ make automake autoconf curl-devel openssl-devel zlib-devel httpd-devel apr-devel apr-util-devel sqlite-devel
RUN cd /tmp \
&& wget http://cache.ruby-lang.org/pub/ruby/2.2/ruby-2.2.2.tar.gz \
&& tar zxvf ruby-2.2.2.tar.gz \
&& cd ruby-2.2.2 \
&& autoconf \
&& ./configure --disable-install-doc \
&& make \
&& make install \
&& rm -rf /tmp/ruby-2.2.2*
# skip installing gem documentation
RUN echo 'gem: --no-rdoc --no-ri' >> "$HOME/.gemrc"
|
liubin/workshop-China-pub
|
example-2/Dockerfile
|
Dockerfile
|
mit
| 584
|
using AngleSharp;
using AngleSharp.Dom;
using AngleSharp.Html.Dom;
using AngleSharp.Html.Parser;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using NadekoBot.Common;
using NadekoBot.Common.Attributes;
using NadekoBot.Common.Replacements;
using NadekoBot.Core.Modules.Searches.Common;
using NadekoBot.Core.Services;
using NadekoBot.Extensions;
using NadekoBot.Modules.Searches.Common;
using NadekoBot.Modules.Searches.Services;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Processing.Drawing;
using SixLabors.Primitives;
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Configuration = AngleSharp.Configuration;
namespace NadekoBot.Modules.Searches
{
public partial class Searches : NadekoTopLevelModule<SearchesService>
{
private readonly IBotCredentials _creds;
private readonly IGoogleApiService _google;
private readonly IHttpClientFactory _httpFactory;
private static readonly NadekoRandom _rng = new NadekoRandom();
public Searches(IBotCredentials creds, IGoogleApiService google, IHttpClientFactory factory)
{
_creds = creds;
_google = google;
_httpFactory = factory;
}
//for anonymasen :^)
[NadekoCommand, Usage, Description, Aliases]
public async Task Rip([Leftover]IGuildUser usr)
{
var av = usr.RealAvatarUrl();
if (av == null)
return;
using (var picStream = await _service.GetRipPictureAsync(usr.Nickname ?? usr.Username, av).ConfigureAwait(false))
{
await ctx.Channel.SendFileAsync(
picStream,
"rip.png",
$"Rip {Format.Bold(usr.ToString())} \n\t- " +
Format.Italics(ctx.User.ToString()))
.ConfigureAwait(false);
}
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
[UserPerm(GuildPerm.ManageMessages)]
[Priority(1)]
public async Task Say(ITextChannel channel, [Leftover]string message)
{
if (string.IsNullOrWhiteSpace(message))
return;
var rep = new ReplacementBuilder()
.WithDefault(ctx.User, channel, (SocketGuild)ctx.Guild, (DiscordSocketClient)ctx.Client)
.Build();
if (CREmbed.TryParse(message, out var embedData))
{
rep.Replace(embedData);
try
{
await channel.EmbedAsync(embedData.ToEmbed(), embedData.PlainText?.SanitizeMentions() ?? "").ConfigureAwait(false);
}
catch (Exception ex)
{
_log.Warn(ex);
}
}
else
{
var msg = rep.Replace(message);
if (!string.IsNullOrWhiteSpace(msg))
{
await channel.SendConfirmAsync(msg).ConfigureAwait(false);
}
}
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
[UserPerm(GuildPerm.ManageMessages)]
[Priority(0)]
public Task Say([Leftover]string message) =>
Say((ITextChannel)ctx.Channel, message);
// done in 3.0
[NadekoCommand, Usage, Description, Aliases]
public async Task Weather([Leftover] string query)
{
if (!await ValidateQuery(ctx.Channel, query).ConfigureAwait(false))
return;
var embed = new EmbedBuilder();
var data = await _service.GetWeatherDataAsync(query).ConfigureAwait(false);
if (data == null)
{
embed.WithDescription(GetText("city_not_found"))
.WithErrorColor();
}
else
{
Func<double, double> f = StandardConversions.CelsiusToFahrenheit;
embed.AddField(fb => fb.WithName("🌍 " + Format.Bold(GetText("location"))).WithValue($"[{data.Name + ", " + data.Sys.Country}](https://openweathermap.org/city/{data.Id})").WithIsInline(true))
.AddField(fb => fb.WithName("📏 " + Format.Bold(GetText("latlong"))).WithValue($"{data.Coord.Lat}, {data.Coord.Lon}").WithIsInline(true))
.AddField(fb => fb.WithName("☁ " + Format.Bold(GetText("condition"))).WithValue(string.Join(", ", data.Weather.Select(w => w.Main))).WithIsInline(true))
.AddField(fb => fb.WithName("😓 " + Format.Bold(GetText("humidity"))).WithValue($"{data.Main.Humidity}%").WithIsInline(true))
.AddField(fb => fb.WithName("💨 " + Format.Bold(GetText("wind_speed"))).WithValue(data.Wind.Speed + " m/s").WithIsInline(true))
.AddField(fb => fb.WithName("🌡 " + Format.Bold(GetText("temperature"))).WithValue($"{data.Main.Temp:F1}°C / {f(data.Main.Temp):F1}°F").WithIsInline(true))
.AddField(fb => fb.WithName("🔆 " + Format.Bold(GetText("min_max"))).WithValue($"{data.Main.TempMin:F1}°C - {data.Main.TempMax:F1}°C\n{f(data.Main.TempMin):F1}°F - {f(data.Main.TempMax):F1}°F").WithIsInline(true))
.AddField(fb => fb.WithName("🌄 " + Format.Bold(GetText("sunrise"))).WithValue($"{data.Sys.Sunrise.ToUnixTimestamp():HH:mm} UTC").WithIsInline(true))
.AddField(fb => fb.WithName("🌇 " + Format.Bold(GetText("sunset"))).WithValue($"{data.Sys.Sunset.ToUnixTimestamp():HH:mm} UTC").WithIsInline(true))
.WithOkColor()
.WithFooter(efb => efb.WithText("Powered by openweathermap.org").WithIconUrl($"http://openweathermap.org/img/w/{data.Weather[0].Icon}.png"));
}
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
}
// done in 3.0
[NadekoCommand, Usage, Description, Aliases]
[NoPublicBot]
public async Task Time([Leftover] string query)
{
if (!await ValidateQuery(ctx.Channel, query).ConfigureAwait(false))
return;
if (string.IsNullOrWhiteSpace(_creds.GoogleApiKey))
{
await ReplyErrorLocalizedAsync("google_api_key_missing").ConfigureAwait(false);
return;
}
var data = await _service.GetTimeDataAsync(query).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync("time",
Format.Bold(data.Address),
Format.Code(data.Time.ToString("HH:mm")),
data.TimeZoneName).ConfigureAwait(false);
}
// done in 3.0
[NadekoCommand, Usage, Description, Aliases]
public async Task Youtube([Leftover] string query = null)
{
if (!await ValidateQuery(ctx.Channel, query).ConfigureAwait(false))
return;
var result = (await _google.GetVideoLinksByKeywordAsync(query, 1).ConfigureAwait(false)).FirstOrDefault();
if (string.IsNullOrWhiteSpace(result))
{
await ReplyErrorLocalizedAsync("no_results").ConfigureAwait(false);
return;
}
await ctx.Channel.SendMessageAsync(result).ConfigureAwait(false);
}
// done in 3.0
[NadekoCommand, Usage, Description, Aliases]
public async Task Movie([Leftover] string query = null)
{
if (!await ValidateQuery(ctx.Channel, query).ConfigureAwait(false))
return;
await ctx.Channel.TriggerTypingAsync().ConfigureAwait(false);
var movie = await _service.GetMovieDataAsync(query).ConfigureAwait(false);
if (movie == null)
{
await ReplyErrorLocalizedAsync("imdb_fail").ConfigureAwait(false);
return;
}
await ctx.Channel.EmbedAsync(new EmbedBuilder().WithOkColor()
.WithTitle(movie.Title)
.WithUrl($"http://www.imdb.com/title/{movie.ImdbId}/")
.WithDescription(movie.Plot.TrimTo(1000))
.AddField(efb => efb.WithName("Rating").WithValue(movie.ImdbRating).WithIsInline(true))
.AddField(efb => efb.WithName("Genre").WithValue(movie.Genre).WithIsInline(true))
.AddField(efb => efb.WithName("Year").WithValue(movie.Year).WithIsInline(true))
.WithImageUrl(movie.Poster)).ConfigureAwait(false);
}
// done in 3.0
[NadekoCommand, Usage, Description, Aliases]
public Task RandomCat() => InternalRandomImage(SearchesService.ImageTag.Cats);
// done in 3.0
[NadekoCommand, Usage, Description, Aliases]
public Task RandomDog() => InternalRandomImage(SearchesService.ImageTag.Dogs);
// done in 3.0
[NadekoCommand, Usage, Description, Aliases]
public Task RandomFood() => InternalRandomImage(SearchesService.ImageTag.Food);
// done in 3.0
[NadekoCommand, Usage, Description, Aliases]
public Task RandomBird() => InternalRandomImage(SearchesService.ImageTag.Birds);
// done in 3.0
private Task InternalRandomImage(SearchesService.ImageTag tag)
{
var url = _service.GetRandomImageUrl(tag);
return ctx.Channel.EmbedAsync(new EmbedBuilder()
.WithOkColor()
.WithImageUrl(url));
}
// done in 3.0
[NadekoCommand, Usage, Description, Aliases]
public async Task Image([Leftover] string query = null)
{
var oterms = query?.Trim();
if (!await ValidateQuery(ctx.Channel, query).ConfigureAwait(false))
return;
query = WebUtility.UrlEncode(oterms).Replace(' ', '+');
try
{
var res = await _google.GetImageAsync(oterms).ConfigureAwait(false);
var embed = new EmbedBuilder()
.WithOkColor()
.WithAuthor(eab => eab.WithName(GetText("image_search_for") + " " + oterms.TrimTo(50))
.WithUrl("https://www.google.rs/search?q=" + query + "&source=lnms&tbm=isch")
.WithIconUrl("http://i.imgur.com/G46fm8J.png"))
.WithDescription(res.Link)
.WithImageUrl(res.Link)
.WithTitle(ctx.User.ToString());
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
}
catch
{
_log.Warn("Falling back to Imgur");
var fullQueryLink = $"http://imgur.com/search?q={ query }";
var config = Configuration.Default.WithDefaultLoader();
using (var document = await BrowsingContext.New(config).OpenAsync(fullQueryLink).ConfigureAwait(false))
{
var elems = document.QuerySelectorAll("a.image-list-link").ToList();
if (!elems.Any())
return;
var img = (elems.ElementAtOrDefault(new NadekoRandom().Next(0, elems.Count))?.Children?.FirstOrDefault() as IHtmlImageElement);
if (img?.Source == null)
return;
var source = img.Source.Replace("b.", ".", StringComparison.InvariantCulture);
var embed = new EmbedBuilder()
.WithOkColor()
.WithAuthor(eab => eab.WithName(GetText("image_search_for") + " " + oterms.TrimTo(50))
.WithUrl(fullQueryLink)
.WithIconUrl("http://s.imgur.com/images/logo-1200-630.jpg?"))
.WithDescription(source)
.WithImageUrl(source)
.WithTitle(ctx.User.ToString());
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
}
}
}
[NadekoCommand, Usage, Description, Aliases]
public async Task Lmgtfy([Leftover] string ffs = null)
{
if (!await ValidateQuery(ctx.Channel, ffs).ConfigureAwait(false))
return;
await ctx.Channel.SendConfirmAsync("<" + await _google.ShortenUrl($"http://lmgtfy.com/?q={ Uri.EscapeUriString(ffs) }").ConfigureAwait(false) + ">")
.ConfigureAwait(false);
}
// done in 3.0
[NadekoCommand, Usage, Description, Aliases]
public async Task Shorten([Leftover] string query)
{
if (!await ValidateQuery(ctx.Channel, query).ConfigureAwait(false))
return;
var shortened = await _google.ShortenUrl(query).ConfigureAwait(false);
if (shortened == query)
{
await ReplyErrorLocalizedAsync("shorten_fail").ConfigureAwait(false);
return;
}
await ctx.Channel.EmbedAsync(new EmbedBuilder().WithColor(NadekoBot.OkColor)
.AddField(efb => efb.WithName(GetText("original_url"))
.WithValue($"<{query}>"))
.AddField(efb => efb.WithName(GetText("short_url"))
.WithValue($"<{shortened}>")))
.ConfigureAwait(false);
}
// done in 3.0
[NadekoCommand, Usage, Description, Aliases]
public async Task Google([Leftover] string query = null)
{
var oterms = query?.Trim();
if (!await ValidateQuery(ctx.Channel, query).ConfigureAwait(false))
return;
query = WebUtility.UrlEncode(oterms).Replace(' ', '+');
var fullQueryLink = $"https://www.google.ca/search?q={ query }&safe=on&lr=lang_eng&hl=en&ie=utf-8&oe=utf-8";
using (var msg = new HttpRequestMessage(HttpMethod.Get, fullQueryLink))
{
msg.Headers.AddFakeHeaders();
var parser = new HtmlParser();
var test = "";
using (var http = _httpFactory.CreateClient())
using (var response = await http.SendAsync(msg).ConfigureAwait(false))
using (var document = await parser.ParseDocumentAsync(test = await response.Content.ReadAsStringAsync().ConfigureAwait(false)).ConfigureAwait(false))
{
var elems = document.QuerySelectorAll("div.g");
var resultsElem = document.QuerySelectorAll("#resultStats").FirstOrDefault();
var totalResults = resultsElem?.TextContent;
//var time = resultsElem.Children.FirstOrDefault()?.TextContent
//^ this doesn't work for some reason, <nobr> is completely missing in parsed collection
if (!elems.Any())
return;
var results = elems.Select<IElement, GoogleSearchResult?>(elem =>
{
var aTag = elem.QuerySelector("a") as IHtmlAnchorElement; // <h3> -> <a>
var href = aTag?.Href;
var name = aTag?.QuerySelector("h3")?.TextContent;
if (href == null || name == null)
return null;
var txt = elem.QuerySelectorAll(".st").FirstOrDefault()?.TextContent;
if (txt == null)
return null;
return new GoogleSearchResult(name, href, txt);
}).Where(x => x != null).Take(5);
var embed = new EmbedBuilder()
.WithOkColor()
.WithAuthor(eab => eab.WithName(GetText("search_for") + " " + oterms.TrimTo(50))
.WithUrl(fullQueryLink)
.WithIconUrl("http://i.imgur.com/G46fm8J.png"))
.WithTitle(ctx.User.ToString())
.WithFooter(efb => efb.WithText(totalResults));
var desc = await Task.WhenAll(results.Select(async res =>
$"[{Format.Bold(res?.Title)}]({(await _google.ShortenUrl(res?.Link).ConfigureAwait(false))})\n{res?.Text?.TrimTo(400 - res.Value.Title.Length - res.Value.Link.Length)}\n\n"))
.ConfigureAwait(false);
var descStr = string.Concat(desc);
await ctx.Channel.EmbedAsync(embed.WithDescription(descStr)).ConfigureAwait(false);
}
}
}
// done in 3.0
[NadekoCommand, Usage, Description, Aliases]
public async Task MagicTheGathering([Leftover] string search)
{
if (!await ValidateQuery(ctx.Channel, search))
return;
await ctx.Channel.TriggerTypingAsync().ConfigureAwait(false);
var card = await _service.GetMtgCardAsync(search).ConfigureAwait(false);
if (card == null)
{
await ReplyErrorLocalizedAsync("card_not_found").ConfigureAwait(false);
return;
}
var embed = new EmbedBuilder().WithOkColor()
.WithTitle(card.Name)
.WithDescription(card.Description)
.WithImageUrl(card.ImageUrl)
.AddField(efb => efb.WithName(GetText("store_url")).WithValue(card.StoreUrl).WithIsInline(true))
.AddField(efb => efb.WithName(GetText("cost")).WithValue(card.ManaCost).WithIsInline(true))
.AddField(efb => efb.WithName(GetText("types")).WithValue(card.Types).WithIsInline(true));
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
}
// done in 3.0
[NadekoCommand, Usage, Description, Aliases]
public async Task Hearthstone([Leftover] string name)
{
var arg = name;
if (!await ValidateQuery(ctx.Channel, name).ConfigureAwait(false))
return;
if (string.IsNullOrWhiteSpace(_creds.MashapeKey))
{
await ReplyErrorLocalizedAsync("mashape_api_missing").ConfigureAwait(false);
return;
}
await ctx.Channel.TriggerTypingAsync().ConfigureAwait(false);
var card = await _service.GetHearthstoneCardDataAsync(name).ConfigureAwait(false);
if (card == null)
{
await ReplyErrorLocalizedAsync("card_not_found").ConfigureAwait(false);
return;
}
var embed = new EmbedBuilder().WithOkColor()
.WithImageUrl(card.Img);
if (!string.IsNullOrWhiteSpace(card.Flavor))
embed.WithDescription(card.Flavor);
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
}
// done in 3.0
[NadekoCommand, Usage, Description, Aliases]
public async Task UrbanDict([Leftover] string query = null)
{
if (!await ValidateQuery(ctx.Channel, query).ConfigureAwait(false))
return;
if (string.IsNullOrWhiteSpace(_creds.MashapeKey))
{
await ReplyErrorLocalizedAsync("mashape_api_missing").ConfigureAwait(false);
return;
}
await ctx.Channel.TriggerTypingAsync().ConfigureAwait(false);
using (var http = _httpFactory.CreateClient())
{
var res = await http.GetStringAsync($"http://api.urbandictionary.com/v0/define?term={Uri.EscapeUriString(query)}").ConfigureAwait(false);
try
{
var items = JsonConvert.DeserializeObject<UrbanResponse>(res).List;
if (items.Any())
{
await ctx.SendPaginatedConfirmAsync(0, (p) =>
{
var item = items[p];
return new EmbedBuilder().WithOkColor()
.WithUrl(item.Permalink)
.WithAuthor(eab => eab.WithIconUrl("http://i.imgur.com/nwERwQE.jpg").WithName(item.Word))
.WithDescription(item.Definition);
}, items.Length, 1).ConfigureAwait(false);
return;
}
}
catch
{
}
}
await ReplyErrorLocalizedAsync("ud_error").ConfigureAwait(false);
}
// done in 3.0
[NadekoCommand, Usage, Description, Aliases]
public async Task Define([Leftover] string word)
{
if (!await ValidateQuery(ctx.Channel, word).ConfigureAwait(false))
return;
using (var http = _httpFactory.CreateClient())
{
var res = await http.GetStringAsync("http://api.pearson.com/v2/dictionaries/entries?headword=" + WebUtility.UrlEncode(word.Trim())).ConfigureAwait(false);
var data = JsonConvert.DeserializeObject<DefineModel>(res);
var sense = data.Results.FirstOrDefault(x => x.Senses?[0].Definition != null)?.Senses[0];
if (sense?.Definition == null)
{
await ReplyErrorLocalizedAsync("define_unknown").ConfigureAwait(false);
return;
}
var definition = sense.Definition.ToString();
if (!(sense.Definition is string))
definition = ((JArray)JToken.Parse(sense.Definition.ToString())).First.ToString();
var embed = new EmbedBuilder().WithOkColor()
.WithTitle(GetText("define") + " " + word)
.WithDescription(definition)
.WithFooter(efb => efb.WithText(sense.Gramatical_info?.Type));
if (sense.Examples != null)
embed.AddField(efb => efb.WithName(GetText("example")).WithValue(sense.Examples.First().Text));
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
}
}
// done in 3.0
[NadekoCommand, Usage, Description, Aliases]
public async Task Hashtag([Leftover] string query)
{
if (!await ValidateQuery(ctx.Channel, query).ConfigureAwait(false))
return;
if (string.IsNullOrWhiteSpace(_creds.MashapeKey))
{
await ReplyErrorLocalizedAsync("mashape_api_missing").ConfigureAwait(false);
return;
}
try
{
await ctx.Channel.TriggerTypingAsync().ConfigureAwait(false);
string res;
using (var http = _httpFactory.CreateClient())
{
http.DefaultRequestHeaders.Clear();
http.DefaultRequestHeaders.Add("X-Mashape-Key", _creds.MashapeKey);
res = await http.GetStringAsync($"https://tagdef.p.mashape.com/one.{Uri.EscapeUriString(query)}.json").ConfigureAwait(false);
}
var items = JObject.Parse(res);
var item = items["defs"]["def"];
//var hashtag = item["hashtag"].ToString();
var link = item["uri"].ToString();
var desc = item["text"].ToString();
await ctx.Channel.EmbedAsync(new EmbedBuilder().WithOkColor()
.WithAuthor(eab => eab.WithUrl(link)
.WithIconUrl("http://res.cloudinary.com/urbandictionary/image/upload/a_exif,c_fit,h_200,w_200/v1394975045/b8oszuu3tbq7ebyo7vo1.jpg")
.WithName(query))
.WithDescription(desc))
.ConfigureAwait(false);
}
catch
{
await ReplyErrorLocalizedAsync("hashtag_error").ConfigureAwait(false);
}
}
// done in 3.0
[NadekoCommand, Usage, Description, Aliases]
public async Task Catfact()
{
using (var http = _httpFactory.CreateClient())
{
var response = await http.GetStringAsync("https://catfact.ninja/fact").ConfigureAwait(false);
if (response == null)
return;
var fact = JObject.Parse(response)["fact"].ToString();
await ctx.Channel.SendConfirmAsync("🐈" + GetText("catfact"), fact).ConfigureAwait(false);
}
}
//done in 3.0
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task Revav([Leftover] IGuildUser usr = null)
{
if (usr == null)
usr = (IGuildUser)ctx.User;
var av = usr.RealAvatarUrl();
if (av == null)
return;
await ctx.Channel.SendConfirmAsync($"https://images.google.com/searchbyimage?image_url={av}").ConfigureAwait(false);
}
//done in 3.0
[NadekoCommand, Usage, Description, Aliases]
public async Task Revimg([Leftover] string imageLink = null)
{
imageLink = imageLink?.Trim() ?? "";
if (string.IsNullOrWhiteSpace(imageLink))
return;
await ctx.Channel.SendConfirmAsync($"https://images.google.com/searchbyimage?image_url={imageLink}").ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
public Task Safebooru([Leftover] string tag = null)
=> InternalDapiCommand(ctx.Message, tag, DapiSearchType.Safebooru);
// done in 3.0
[NadekoCommand, Usage, Description, Aliases]
public async Task Wiki([Leftover] string query = null)
{
query = query?.Trim();
if (!await ValidateQuery(ctx.Channel, query).ConfigureAwait(false))
return;
using (var http = _httpFactory.CreateClient())
{
var result = await http.GetStringAsync("https://en.wikipedia.org//w/api.php?action=query&format=json&prop=info&redirects=1&formatversion=2&inprop=url&titles=" + Uri.EscapeDataString(query)).ConfigureAwait(false);
var data = JsonConvert.DeserializeObject<WikipediaApiModel>(result);
if (data.Query.Pages[0].Missing || string.IsNullOrWhiteSpace(data.Query.Pages[0].FullUrl))
await ReplyErrorLocalizedAsync("wiki_page_not_found").ConfigureAwait(false);
else
await ctx.Channel.SendMessageAsync(data.Query.Pages[0].FullUrl).ConfigureAwait(false);
}
}
[NadekoCommand, Usage, Description, Aliases]
public async Task Color(params Rgba32[] colors)
{
if (!colors.Any())
return;
var colorObjects = colors.Take(10)
.ToArray();
using (var img = new Image<Rgba32>(colorObjects.Length * 50, 50))
{
for (int i = 0; i < colorObjects.Length; i++)
{
var x = i * 50;
img.Mutate(m => m.FillPolygon(colorObjects[i], new PointF[] {
new PointF(x, 0),
new PointF(x + 50, 0),
new PointF(x + 50, 50),
new PointF(x, 50)
}));
}
using (var ms = img.ToStream())
{
await ctx.Channel.SendFileAsync(ms, $"colors.png").ConfigureAwait(false);
}
}
}
// done in 3.0
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task Avatar([Leftover] IGuildUser usr = null)
{
if (usr == null)
usr = (IGuildUser)ctx.User;
var avatarUrl = usr.RealAvatarUrl();
if (avatarUrl == null)
{
await ReplyErrorLocalizedAsync("avatar_none", usr.ToString()).ConfigureAwait(false);
return;
}
await ctx.Channel.EmbedAsync(new EmbedBuilder().WithOkColor()
.AddField(efb => efb.WithName("Username").WithValue(usr.ToString()).WithIsInline(false))
.AddField(efb => efb.WithName("Avatar Url").WithValue(avatarUrl).WithIsInline(false))
.WithThumbnailUrl(avatarUrl.ToString())
.WithImageUrl(avatarUrl.ToString()), ctx.User.Mention).ConfigureAwait(false);
}
// done in 3.0
[NadekoCommand, Usage, Description, Aliases]
public async Task Wikia(string target, [Leftover] string query)
{
if (string.IsNullOrWhiteSpace(target) || string.IsNullOrWhiteSpace(query))
{
await ReplyErrorLocalizedAsync("wikia_input_error").ConfigureAwait(false);
return;
}
await ctx.Channel.TriggerTypingAsync().ConfigureAwait(false);
using (var http = _httpFactory.CreateClient())
{
http.DefaultRequestHeaders.Clear();
try
{
var res = await http.GetStringAsync($"http://www.{Uri.EscapeUriString(target)}.wikia.com/api/v1/Search/List?query={Uri.EscapeUriString(query)}&limit=25&minArticleQuality=10&batch=1&namespaces=0%2C14").ConfigureAwait(false);
var items = JObject.Parse(res);
var found = items["items"][0];
var response = $@"`{GetText("title")}` {found["title"]}
`{GetText("quality")}` {found["quality"]}
`{GetText("url")}:` {await _google.ShortenUrl(found["url"].ToString()).ConfigureAwait(false)}";
await ctx.Channel.SendMessageAsync(response).ConfigureAwait(false);
}
catch
{
await ReplyErrorLocalizedAsync("wikia_error").ConfigureAwait(false);
}
}
}
// done in 3.0
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task Bible(string book, string chapterAndVerse)
{
var obj = new BibleVerses();
try
{
using (var http = _httpFactory.CreateClient())
{
var res = await http
.GetStringAsync("https://bible-api.com/" + book + " " + chapterAndVerse).ConfigureAwait(false);
obj = JsonConvert.DeserializeObject<BibleVerses>(res);
}
}
catch
{
}
if (obj.Error != null || obj.Verses == null || obj.Verses.Length == 0)
await ctx.Channel.SendErrorAsync(obj.Error ?? "No verse found.").ConfigureAwait(false);
else
{
var v = obj.Verses[0];
await ctx.Channel.EmbedAsync(new EmbedBuilder()
.WithOkColor()
.WithTitle($"{v.BookName} {v.Chapter}:{v.Verse}")
.WithDescription(v.Text)).ConfigureAwait(false);
}
}
public async Task InternalDapiCommand(IUserMessage umsg, string tag, DapiSearchType type)
{
var channel = umsg.Channel;
tag = tag?.Trim() ?? "";
var imgObj = await _service.DapiSearch(tag, type, ctx.Guild?.Id).ConfigureAwait(false);
if (imgObj == null)
await channel.SendErrorAsync(umsg.Author.Mention + " " + GetText("no_results")).ConfigureAwait(false);
else
await channel.EmbedAsync(new EmbedBuilder().WithOkColor()
.WithDescription($"{umsg.Author.Mention} [{tag ?? "url"}]({imgObj.FileUrl})")
.WithImageUrl(imgObj.FileUrl)
.WithFooter(efb => efb.WithText(type.ToString()))).ConfigureAwait(false);
}
public async Task<bool> ValidateQuery(IMessageChannel ch, string query)
{
if (!string.IsNullOrWhiteSpace(query))
{
return true;
}
await ErrorLocalizedAsync("specify_search_params").ConfigureAwait(false);
return false;
}
}
}
|
ScarletKuro/NadekoBot
|
NadekoBot.Core/Modules/Searches/Searches.cs
|
C#
|
mit
| 33,074
|
import { A } from '@ember/array';
import { module } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render, click } from '@ember/test-helpers';
import test from 'ember-sinon-qunit/test-support/test';
import hbs from 'htmlbars-inline-precompile';
import setupNoDeprecations from '../../helpers/setup-no-deprecations';
import { testBS3 } from '../../helpers/bootstrap-test';
module('Integration | Component | bs-button-group', function(hooks) {
setupRenderingTest(hooks);
setupNoDeprecations(hooks);
hooks.beforeEach(function() {
this.actions = {};
this.send = (actionName, ...args) => this.actions[actionName].apply(this, args);
});
test('button group has correct CSS classes', async function(assert) {
await render(
hbs`{{#bs-button-group size="lg" justified=true as |bg|}}{{#bg.button value=1}}1{{/bg.button}}{{#bg.button value=2}}2{{/bg.button}}{{#bg.button value=3}}3{{/bg.button}}{{/bs-button-group}}`
);
assert.dom('.btn-group').exists('has btn-group class');
assert.dom('.btn-group').hasClass('btn-group-lg', 'has size class');
});
testBS3('button group supports justified layout', async function(assert) {
await render(
hbs`{{#bs-button-group justified=true as |bg|}}{{#bg.button value=1}}1{{/bg.button}}{{#bg.button value=2}}2{{/bg.button}}{{#bg.button value=3}}3{{/bg.button}}{{/bs-button-group}}`
);
assert.dom('.btn-group').exists('has btn-group class');
assert.dom('.btn-group').hasClass('btn-group-justified', 'has justified class');
});
test('button group supports vertical layout', async function(assert) {
await render(
hbs`{{#bs-button-group vertical=true as |bg|}}{{#bg.button value=1}}1{{/bg.button}}{{#bg.button value=2}}2{{/bg.button}}{{#bg.button value=3}}3{{/bg.button}}{{/bs-button-group}}`
);
assert.dom('.btn-group').doesNotExist('has not btn-group class');
assert.dom('.btn-group-vertical').exists('has vertical class');
});
test('radio button group calls onChange with value of selected button', async function(assert) {
let action = this.spy();
this.actions.change = action;
await render(
hbs`{{#bs-button-group type="radio" value=value onChange=(action "change") as |bg|}}{{#bg.button value=1}}1{{/bg.button}}{{#bg.button value=2}}2{{/bg.button}}{{#bg.button value=3}}3{{/bg.button}}{{/bs-button-group}}`
);
for (let i = 0; i < 3; i++) {
await click(`button:nth-child(${i + 1})`);
assert.ok(action.calledWith(i + 1), 'onChange has been called with correct value');
}
});
test('checkbox button group calls onChange with value of all selected buttons', async function(assert) {
assert.expect(1);
let expectedValue = [1, 2];
this.actions.change = (value) => {
assert.deepEqual(value, expectedValue);
};
await render(
hbs`{{#bs-button-group type="checkbox" value=value onChange=(action "change") as |bg|}}{{#bg.button value=1}}1{{/bg.button}}{{#bg.button value=2}}2{{/bg.button}}{{#bg.button value=3}}3{{/bg.button}}{{/bs-button-group}}`
);
this.set('value', [1]);
await click('button:nth-child(2)');
});
test('radio button group with value set activates button with same value', async function(assert) {
await render(
hbs`{{#bs-button-group type="radio" value=value as |bg|}}{{#bg.button value=1}}1{{/bg.button}}{{#bg.button value=2}}2{{/bg.button}}{{#bg.button value=3}}3{{/bg.button}}{{/bs-button-group}}`
);
this.set('value', 1);
assert.equal(this.get('value'), 1, 'value must match set value');
// check button's active property
for (let k = 0; k < 3; k++) {
assert.equal(this.element.querySelector(`button:nth-child(${k + 1})`).classList.contains('active'), 0 === k, 'only button with same value is active');
}
});
test('checkbox button group with value set activates buttons with same value', async function(assert) {
let value = A([1, 3]);
await render(
hbs`{{#bs-button-group type="checkbox" value=value as |bg|}}{{#bg.button value=1}}1{{/bg.button}}{{#bg.button value=2}}2{{/bg.button}}{{#bg.button value=3}}3{{/bg.button}}{{/bs-button-group}}`
);
this.set('value', value);
assert.deepEqual(this.get('value'), value, 'value must match set value');
// check button's active property
for (let k = 0; k < 3; k++) {
assert.equal(this.element.querySelector(`button:nth-child(${k + 1})`).classList.contains('active'), value.includes(k + 1), 'only buttons with value contained in set value are active');
}
});
test('setting radio button group value activates button with same value', async function(assert) {
await render(
hbs`{{#bs-button-group type="radio" value=value as |bg|}}{{#bg.button value=1}}1{{/bg.button}}{{#bg.button value=2}}2{{/bg.button}}{{#bg.button value=3}}3{{/bg.button}}{{/bs-button-group}}`
);
for (let i = 0; i < 3; i++) {
this.set('value', i + 1);
assert.equal(this.get('value'), i + 1, 'value must match set value');
// check button's active property
for (let k = 0; k < 3; k++) {
assert.equal(this.element.querySelector(`button:nth-child(${k + 1})`).classList.contains('active'), i === k, 'only button with same value is active');
}
}
});
test('setting checkbox button group value with array of values activates buttons with same value', async function(assert) {
await render(
hbs`{{#bs-button-group type="checkbox" value=value as |bg|}}{{#bg.button value=1}}1{{/bg.button}}{{#bg.button value=2}}2{{/bg.button}}{{#bg.button value=3}}3{{/bg.button}}{{/bs-button-group}}`
);
let value = A([1, 3]);
this.set('value', value);
assert.deepEqual(this.get('value'), value, 'value must match set value');
// check button's active property
for (let k = 0; k < 3; k++) {
assert.equal(this.element.querySelector(`button:nth-child(${k + 1})`).classList.contains('active'), value.includes(k + 1), 'only buttons with value contained in set value is active');
}
});
test('when clicking active radio button, onChange must not be called', async function(assert) {
let action = this.spy();
this.actions.change = action;
await render(
hbs`{{#bs-button-group type="radio" value=1 as |bg|}}{{#bg.button value=1}}1{{/bg.button}}{{#bg.button value=2}}2{{/bg.button}}{{#bg.button value=3}}3{{/bg.button}}{{/bs-button-group}}`
);
await click('button:nth-child(1)');
assert.notOk(action.called, 'onChange has not been called');
});
test('setting radio button group value to null sets buttons active state to false', async function(assert) {
await render(
hbs`{{#bs-button-group type="radio" value=value as |bg|}}{{#bg.button value=1}}1{{/bg.button}}{{#bg.button value=2}}2{{/bg.button}}{{#bg.button value=3}}3{{/bg.button}}{{/bs-button-group}}`
);
for (let i = 0; i < 3; i++) {
this.set('value', i + 1);
this.set('value', null);
assert.equal(this.get('value'), null, 'value must be null');
// check button's active property
for (let k = 0; k < 3; k++) {
assert.dom(`button:nth-child(${k + 1})`).hasNoClass('active', 'button active state is true');
}
}
});
test('clicking button group does not change public value porperty', async function(assert) {
let value = A([1]);
this.set('value', value);
await render(
hbs`{{#bs-button-group type="checkbox" value=value as |bg|}}{{#bg.button value=1}}1{{/bg.button}}{{#bg.button value=2}}2{{/bg.button}}{{#bg.button value=3}}3{{/bg.button}}{{/bs-button-group}}`
);
await click('button:nth-child(3)');
assert.equal(this.get('value'), value, 'Does not change value property');
});
});
|
jelhan/ember-bootstrap
|
tests/integration/components/bs-button-group-test.js
|
JavaScript
|
mit
| 7,735
|
# Knockout Router (hash support)
|
cbcrc/koco-router-state-hash
|
README.md
|
Markdown
|
mit
| 34
|
import * as React from 'react'
const styles = require('./menuPart.less')
import Icon from 'client/components/icon/icon'
interface compProps {
icon:string;
text:string;
onClick:()=>any;
}
const MenuButton:React.StatelessComponent<compProps> = ({icon, text, onClick}) => {
return <div className={styles.menuButton} onClick={onClick}>
<Icon name={icon} className={styles.icon}/>
<span className={styles.text}>{text}</span>
</div>
}
export default MenuButton
|
Jiaoweiquan/mindp
|
src/client/parts/menuPart/menuButton.tsx
|
TypeScript
|
mit
| 493
|
body {
height: 101%;
width:100%;
}
div.wrapper {
width:1280px;
height:985px;
margin-left: auto;
margin-right: auto;
}
div#cicero {
}
div#scroll {
width: 1280px;
text-align: center;
position: fixed;
bottom: -60px;
color: rgba(255,255,255,.8);
font-size: 3em;
font-weight: bold;
}
div#potluck {
top: 0px;
width: 1280px;
position: fixed;
font-size: 1.25em;
}
div.column {
float: left;
padding: 0;
margin: 0;
}
div.half {
width: 50%;
}
div.two-thirds {
width: 66%;
}
div.one-third {
width: 33%;
}
div.pane {
padding: 10px;
margin: 0;
float: left;
}
div.contact {
display: none;
position: absolute;
}
/**
* Confirmation section
*/
div.response {
height: 7em;
}
div.confirm {
height: 3em;
margin-bottom: 2em;
}
div.confirm > div {
float: left;
}
div.confirm a.selected {
font-weight: bold;
}
div.response div.maybe {
padding-top: 1em;
}
div.response div.no {
padding-top: 2em;
}
div.response div.food.hidden {
display: none;
}
div.response form#food_form textarea,
div.response form#food_form button {
vertical-align:middle;
}
/**
* Attendance tab
*/
div.tabs {
float: left;
width: 100%;
padding: 0 0 20px 0;
}
div.tabs li {
list-style:none;
float: left;
padding: 5px 7px;
margin: 0px 0px;
cursor: pointer;
border-right: solid grey 1px;
}
div.tabs li:last-child {
border-right: none;
}
div.responses {
margin-top: 50px;
float: left;
min-height: 50px;
border: grey solid 1px;
border-radius: 10px;
padding: 20px;
}
div.responses ul {
margin: 0;
padding: 0;
}
div.tabs li.selected {
font-weight: bold;
cursor: default;
}
div.attendance > div {
display: none;
}
div.attendance > div.selected {
display: block;
}
div.attendance li {
list-style: none;
}
div.attendance .food {
display: none;
}
|
odontomachus/potluck
|
web/static/css/potluck.css
|
CSS
|
mit
| 1,958
|
import React, { Component } from 'react';
import {
View,
Text,
Image,
StyleSheet,
Linking,
TouchableOpacity
} from 'react-native';
import HtmlRender from 'react-native-html-render';
import { parseImgUrl } from '../../utils';
import moment from 'moment';
class TopicCommentItem extends Component {
render() {
const { reply, idx } = this.props;
const avatar = parseImgUrl(reply.member.avatar_normal);
const date = moment.unix(reply.created).fromNow();
const content = `<p>${reply.content_rendered}</p>`;
const floor = `#${idx + 1}`;
return (
<View style={styles.reply} key={reply.id}>
<View style={styles.header}>
<TouchableOpacity>
<Image
style={[styles.avatar]}
source={{uri: avatar}}>
</Image>
</TouchableOpacity>
<View style={styles.info}>
<View style={styles.usernameWrapper}>
<Text style={styles.username}>
{reply.member.username}
</Text>
</View>
<View style={styles.dateWrapper}>
<Text style={styles.date}>
{date}
</Text>
</View>
</View>
<View style={styles.floorWrapper}>
<Text style={styles.floor}>
{floor}
</Text>
</View>
</View>
<View style={styles.content}>
<HtmlRender
value={content}
stylesheet={htmlStyles}
onLinkPress={url => Linking.openURL(url)}
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
reply: {
padding: 10,
borderBottomColor: 'rgba(0, 0, 0, 0.05)',
borderBottomWidth: 1,
},
header: {
flexDirection: 'row',
},
avatar: {
height: 30,
width: 30,
borderRadius: 20,
marginRight: 10,
},
info: {
flexDirection: 'row',
},
usernameWrapper: {
marginRight: 10,
},
username: {
fontSize: 14,
},
dateWrapper: {
marginRight: 10,
},
date: {
fontSize: 14,
},
floorWrapper: {
position: 'absolute',
right: 5,
},
floor: {
fontSize: 12,
},
content: {
marginLeft: 25,
}
});
const htmlStyles = StyleSheet.create({
pwrapper: {
marginTop: 5,
marginBottom: 5,
paddingLeft: 15,
paddingRight: 15
},
p: {
fontSize: 14,
},
a: {
color: '#4078c0',
fontSize: 14,
}
});
export default TopicCommentItem;
|
ahonn/v2exRN
|
src/components/topic/TopicCommentItem.js
|
JavaScript
|
mit
| 2,491
|
/**
* Created by dli on 25.01.2015.
*/
define('sync/time/Clock', ['sync/time/CONST'], function (CONST) {
var Clock = function (time){
this.time = time || 0;
}
Clock.prototype.tick = function(){
return this.time < CONST.LOGICAL_HOUR - 1 ? ++this.time : (this.time = 0);
}
Clock.prototype.setTime = function(time) {
this.time = time;
}
Clock.prototype.getTime = function(time) {
return this.time;
}
return Clock;
});
|
brainfrozen/march-javascript
|
src/sync/time/Clock.js
|
JavaScript
|
mit
| 515
|
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
Bundler.require(*Rails.groups)
require "smsapi_client"
module Dummy
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
|
logicorg/smsapi_client
|
spec/dummy/config/application.rb
|
Ruby
|
mit
| 1,229
|
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Windows;
using YAMP;
namespace Saber.Plugin.Caculator
{
//https://github.com/FlorianRappl/YAMP
public class Main : IPlugin, IPluginI18n
{
private static Regex regValidExpressChar = new Regex(
@"^(" +
@"ceil|floor|exp|pi|e|max|min|det|abs|log|ln|sqrt|" +
@"sin|cos|tan|arcsin|arccos|arctan|" +
@"eigval|eigvec|eig|sum|polar|plot|round|sort|real|zeta|" +
@"bin2dec|hex2dec|oct2dec|" +
@"==|~=|&&|\|\||" +
@"[ei]|[0-9]|[\+\-\*\/\^\., ""]|[\(\)\|\!\[\]]" +
@")+$", RegexOptions.Compiled);
private static Regex regBrackets = new Regex(@"[\(\)\[\]]", RegexOptions.Compiled);
private static Parser parser;
private PluginInitContext context { get; set; }
static Main()
{
parser = new Parser();
parser.InteractiveMode = false;
parser.UseScripting = false;
}
public List<Result> Query(Query query)
{
if (query.Search.Length <= 2 // don't affect when user only input "e" or "i" keyword
|| !regValidExpressChar.IsMatch(query.Search)
|| !IsBracketComplete(query.Search)) return new List<Result>();
try
{
var result = parser.Parse(query.Search);
result.Run();
if (result.Output != null && !string.IsNullOrEmpty(result.Result))
{
return new List<Result>
{ new Result
{
Title = result.Result,
IcoPath = "Images/calculator.png",
Score = 300,
SubTitle = "Copy this number to the clipboard",
Action = c =>
{
try
{
Clipboard.SetText(result.Result);
return true;
}
catch (ExternalException e)
{
MessageBox.Show("Copy failed, please try later");
return false;
}
}
} };
}
}
catch
{}
return new List<Result>();
}
private bool IsBracketComplete(string query)
{
var matchs = regBrackets.Matches(query);
var leftBracketCount = 0;
foreach (Match match in matchs)
{
if (match.Value == "(" || match.Value == "[")
{
leftBracketCount++;
}
else
{
leftBracketCount--;
}
}
return leftBracketCount == 0;
}
public void Init(PluginInitContext context)
{
this.context = context;
}
public string GetTranslatedPluginTitle()
{
return context.API.GetTranslation("wox_plugin_caculator_plugin_name");
}
public string GetTranslatedPluginDescription()
{
return context.API.GetTranslation("wox_plugin_caculator_plugin_description");
}
}
}
|
yozora-hitagi/Saber
|
Plugins/Saber.Plugin.Calculator/Main.cs
|
C#
|
mit
| 3,649
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>whups sounds like someone forgot to get a Pen.Test done</title>
<meta name="author" content="raesene">
<!-- Enable responsive viewport -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Le styles -->
<link href="https://raesene.github.io/assets/resources/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="https://raesene.github.io/assets/resources/font-awesome/css/font-awesome.min.css" rel="stylesheet">
<link href="https://raesene.github.io/assets/resources/syntax/syntax.css" rel="stylesheet">
<link href="https://raesene.github.io/assets/css/style.css" rel="stylesheet">
<!-- Le fav and touch icons -->
<!-- Update these with your own images
<link rel="shortcut icon" href="images/favicon.ico">
<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="72x72" href="images/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="114x114" href="images/apple-touch-icon-114x114.png">
-->
<link rel="alternate" type="application/rss+xml" title="" href="https://raesene.github.io/feed.xml">
</head>
<body>
<nav class="navbar navbar-default visible-xs" role="navigation">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a type="button" class="navbar-toggle nav-link" href="https://github.com/raesene">
<i class="fa fa-github"></i>
</a>
<a type="button" class="navbar-toggle nav-link" href="https://twitter.com/raesene">
<i class="fa fa-twitter"></i>
</a>
<a type="button" class="navbar-toggle nav-link" href="mailto:raesene@gmail.com">
<i class="fa fa-envelope"></i>
</a>
<a class="navbar-brand" href="https://raesene.github.io/">
<img src="https://www.gravatar.com/avatar/8c189c784a607c4b5d52b0c7ee69b036?s=35" class="img-circle" />
Raesene's Ramblings
</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="active"><a href="https://raesene.github.io/">Home</a></li>
<li><a href="https://raesene.github.io/categories/index.html">Categories</a></li>
<li><a href="https://raesene.github.io/tags/index.html">Tags</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</nav>
<!-- nav-menu-dropdown -->
<div class="btn-group hidden-xs" id="nav-menu">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-bars"></i>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href="https://raesene.github.io/"><i class="fa fa-home"></i>Home</a></li>
<li><a href="https://raesene.github.io/categories/index.html"><i class="fa fa-folder"></i>Categories</a></li>
<li><a href="https://raesene.github.io/tags/index.html"><i class="fa fa-tags"></i>Tags</a></li>
<li class="divider"></li>
<li><a href="#"><i class="fa fa-arrow-up"></i>Top of Page</a></li>
</ul>
</div>
<div class="col-sm-3 sidebar hidden-xs">
<!-- sidebar.html -->
<header class="sidebar-header" role="banner">
<a href="https://raesene.github.io/">
<img src="https://www.gravatar.com/avatar/8c189c784a607c4b5d52b0c7ee69b036?s=150" class="img-circle" />
</a>
<h3 class="title">
<a href="https://raesene.github.io/">Raesene's Ramblings</a>
</h3>
</header>
<div id="bio" class="text-center">
Security Geek, Penetration Testing, Docker, Ruby, Hillwalking
</div>
<div id="contact-list" class="text-center">
<ul class="list-unstyled list-inline">
<li>
<a class="btn btn-default btn-sm" href="https://github.com/raesene">
<i class="fa fa-github-alt fa-lg"></i>
</a>
</li>
<li>
<a class="btn btn-default btn-sm" href="https://twitter.com/raesene">
<i class="fa fa-twitter fa-lg"></i>
</a>
</li>
<li>
<a class="btn btn-default btn-sm" href="mailto:raesene@gmail.com">
<i class="fa fa-envelope fa-lg"></i>
</a>
</li>
</ul>
<ul id="contact-list-secondary" class="list-unstyled list-inline">
<li>
<a class="btn btn-default btn-sm" href="https://linkedin.com/in/rorym">
<i class="fa fa-linkedin fa-lg"></i>
</a>
</li>
<li>
<a class="btn btn-default btn-sm" href="https://raesene.github.io/feed.xml">
<i class="fa fa-rss fa-lg"></i>
</a>
</li>
</ul>
</div>
<!-- sidebar.html end -->
</div>
<div class="col-sm-9 col-sm-offset-3">
<div class="page-header">
<h1>whups sounds like someone forgot to get a Pen.Test done </h1>
</div>
<article>
<div class="col-sm-10">
<span class="post-date">
August
30th,
2006
</span>
<div class="article_body">
<p><a title="O2 closes call records site after security flap | The Register" href="http://www.theregister.co.uk/2006/08/30/o2_security_flap/">O2 closes call records site after security flap | The Register</a><br />
whenever I read this kind of story it makes me reckon that the victims probably hadn't had a recent Pen. test done, and the kind of URL manipulation described would likely have been picked up by most testers.<br />
However kudos to O2 for admitting the flaw and moving to fix it, instead of taking the line that some organisations seem to take which is to attack the person that found the flaw....</p>
</div>
<ul class="tag_box list-unstyled list-inline">
<li><i class="fa fa-folder-open"></i></li>
<li><a href="https://raesene.github.io/categories/index.html#Web Security-ref">
Web Security <span>(39)</span>
</a></li>
</ul>
<hr>
<div>
<section class="share col-sm-6">
<h4 class="section-title">Share Post</h4>
<a class="btn btn-default btn-sm twitter" href="https://twitter.com/share?text=whups sounds like someone forgot to get a Pen.Test done&via=raesene"
onclick="window.open(this.href, 'twitter-share', 'width=550,height=235');return false;">
<i class="fa fa-twitter fa-lg"></i>
Twitter
</a>
<a class="btn btn-default btn-sm facebook" href="https://www.facebook.com/sharer/sharer.php"
onclick="window.open(this.href, 'facebook-share','width=580,height=296');return false;">
<i class="fa fa-facebook fa-lg"></i>
Facebook
</a>
<a class="btn btn-default btn-sm gplus"
onclick="window.open('https://plus.google.com/share?url='+window.location.href, 'google-plus-share', 'width=490,height=530');return false;">
<i class="fa fa-google-plus fa-lg"></i>
Google+
</a>
</section>
<section class="col-sm-6 author">
<img src="https://www.gravatar.com/avatar/8c189c784a607c4b5d52b0c7ee69b036" class="img-rounded author-image" />
<h4 class="section-title author-name">raesene</h4>
<p class="author-bio">Security Geek, Penetration Testing, Docker, Ruby, Hillwalking</p>
</section>
</div>
<div class="clearfix"></div>
<ul class="pager">
<li class="previous"><a href="https://raesene.github.io/blog/2006/08/30/good_post_on_th/" title="Good post on the dangers of XSS">← Previous</a></li>
<li class="next"><a href="https://raesene.github.io/blog/2006/08/31/one_of_the_prob/" title="One of the problems of using a developing framework">Next →</a></li>
</ul>
<hr>
</div>
<div class="col-sm-2 sidebar-2">
</div>
</article>
<div class="clearfix"></div>
<footer>
<hr/>
<p>
© 2022 raesene with Jekyll. Theme: <a href="https://github.com/dbtek/dbyll">dbyll</a> by dbtek.
</p>
</footer>
</div>
<script type="text/javascript" src="https://raesene.github.io/assets/resources/jquery/jquery.min.js"></script>
<script type="text/javascript" src="https://raesene.github.io/assets/resources/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://raesene.github.io/assets/js/app.js"></script>
</body>
</html>
|
raesene/raesene.github.io
|
blog/2006/08/30/whups_sounds_li/index.html
|
HTML
|
mit
| 8,535
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Managed.D2DSharp.SimpleText")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Dmitry Kolchev")]
[assembly: AssemblyProduct("Managed.D2DSharp.SimpleText")]
[assembly: AssemblyCopyright("Copyright © Dmitry Kolchev 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("46e36141-9743-43fa-8b83-7426381e76b2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
dmitrykolchev/d2dsharp
|
D2DSharp/DykBits.D2DSharp.SimpleText/Properties/AssemblyInfo.cs
|
C#
|
mit
| 1,494
|
'use strict';
angular.module('startingPointJsApp')
.service('Auth', ['$rootScope', '$http', 'localStorageService', function Auth($rootScope, $http, localStorageService) {
this.eventName = 'Auth.changes';
Auth.prototype.getUser = function () {
return localStorageService.get('user');
};
Auth.prototype.signIn = function (data, callback) {
$http.post('/signin', data).success(function (result) {
if (result.status.code !== 200) {
callback(result.error, null);
} else {
callback(null, result.result);
localStorageService.set('user', result.result);
Auth.prototype.broadcast();
}
});
};
Auth.prototype.signOut = function (callback) {
$http.post('/signout').success(function (result) {
if (result.status.code !== 200) {
callback(result.error, null);
} else {
callback(null, result.result);
localStorageService.clearAll();
Auth.prototype.broadcast();
}
});
};
Auth.prototype.subscribe = function ($scope, callback) {
$scope.$on(Auth.eventName, callback);
};
Auth.prototype.broadcast = function () {
$rootScope.$broadcast(Auth.eventName);
};
}]);
|
fealaer/StartingPointJS
|
client/scripts/services/auth.js
|
JavaScript
|
mit
| 1,327
|
/************************************************************************************
Filename : Util_DataLogger.h
Content : General purpose data logging to Matlab
Created : Oct 3, 2014
Authors : Neil Konzen
Copyright : Copyright 2014 Oculus VR, Inc. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.2
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************************/
#ifndef OVR_Util_DataLogger_h
#define OVR_Util_DataLogger_h
#include "Kernel/OVR_Array.h"
#include "Kernel/OVR_String.h"
#include "Util_MatFile.h"
#ifndef OVR_ENABLE_DATALOGGER
#define OVR_ENABLE_DATALOGGER 1
#endif
namespace OVR {
template<typename T> class Vector3;
template<typename T> class Quat;
template<typename T> class Pose;
namespace Util {
#if OVR_ENABLE_DATALOGGER
class DataLogger;
// DataLogger Channel
class DataLoggerChannel
{
public:
void Log(const void* data, int sampleSize);
bool IsLogging() const;
bool IsFull() const;
// Logging functions for some common types
template<typename T>
void Log(const Quat<T>& q);
template<typename T>
void Log(const Vector3<T>& v);
template<typename T>
void Log(const Pose<T>& p);
private:
friend class DataLogger;
DataLoggerChannel(DataLogger* logger, const char* name, int sampleSize, int sampleRate, bool doubleMatrix);
~DataLoggerChannel();
bool Write(MatFile& matfile);
private:
DataLogger* Logger;
String Name;
int SampleSize;
int SampleRate;
int SampleCount;
int MaxSampleCount;
bool DoubleMatrix;
uint8_t* SampleData;
};
// DataLogger class
class DataLogger
{
public:
DataLogger();
~DataLogger();
// Parses C command line parameters "-log <objectIndex> <matFileName> <logTime>"
static bool ParseCommandLine(int* pargc, const char** pargv[], int& logIndex, String& logFile, double& logTime);
void SetLogFile(const char* filename, double logTime);
bool SaveLogFile();
bool IsLogging() const { return LogTime > 0; }
DataLoggerChannel* GetChannel(const char* name);
DataLoggerChannel* CreateChannel(const char* name, int sampleSize, int sampleRate, bool doubleMatrix = true);
void Log(const char* name, const void* data, int sampleSize, int sampleRate, bool doubleMatrix = true)
{
DataLoggerChannel *channel = CreateChannel(name, sampleSize, sampleRate, doubleMatrix);
if (channel) channel->Log(data, sampleSize);
}
private:
friend class DataLoggerChannel;
DataLoggerChannel* GetChannelNoLock(const char* name);
Lock TheLock;
double LogTime;
String Filename;
ArrayPOD<DataLoggerChannel*> Channels;
};
#else // OVR_ENABLE_DATALOGGER
// Disabled, no-op implementation
class DataLoggerChannel
{
public:
OVR_FORCE_INLINE void Log(const void* data, int sampleSize) { OVR_UNUSED2(data, sampleSize); }
OVR_FORCE_INLINE bool IsLogging() const { return false; }
OVR_FORCE_INLINE bool IsFull() const { return false; }
template<typename T>
OVR_FORCE_INLINE void Log(const Quat<T>& q) { OVR_UNUSED(q); }
template<typename T>
OVR_FORCE_INLINE void Log(const Vector3<T>& v) { OVR_UNUSED(v); }
template<typename T>
OVR_FORCE_INLINE void Log(const Pose<T>& p) { OVR_UNUSED(p); }
};
class DataLogger
{
public:
static bool ParseCommandLine(int* pargc, const char** pargv[], int& logIndex, String& logFile, double& logTime) { OVR_UNUSED5(pargc, pargv, logIndex, logFile, logTime); return false; }
OVR_FORCE_INLINE void SetLogFile(const char* filename, double logTime) { OVR_UNUSED2(filename, logTime); }
OVR_FORCE_INLINE bool SaveLogFile() { return true; }
OVR_FORCE_INLINE bool IsLogging() const { return false; }
OVR_FORCE_INLINE DataLoggerChannel* GetChannel(const char* name) { OVR_UNUSED(name); return &NullChannel; }
OVR_FORCE_INLINE DataLoggerChannel* CreateChannel(const char* name, int sampleSize, int sampleRate) { OVR_UNUSED3(name, sampleSize, sampleRate); return &NullChannel; }
private:
friend class DataLoggerChannel;
static DataLoggerChannel NullChannel;
};
#endif // OVR_ENABLE_DATALOGGER
}} // namespace OVR::Util
#endif // OVR_Util_DataLogger_h
|
OSUrobotics/ros_ovr_sdk
|
sdk/ovr_sdk_linux_0.5.0.1/LibOVR/Src/Util/Util_DataLogger.h
|
C
|
mit
| 5,059
|
/**
* Created by ila on 5/18/2015.
*/
"use strict"
class SettingStore {
static set(object) {
const KEY = 'Setting';
return localforage.setItem(KEY, object.toArray());
}
static get() {
const KEY = 'Setting';
return localforage.getItem(KEY).then(function (v) {
return new Promise(function (resolve, reject) {
let setting = new Setting();
if (v) setting.fromArray(v);
resolve(setting);
});
});
}
}
|
himulawang/observer
|
js/store/setting_store.js
|
JavaScript
|
mit
| 526
|
require 'digest/sha1'
class User < ActiveRecord::Base
### AUTHORIZATION
include Authorization::User::InstanceMethods
extend Authorization::User::SingletonMethods
###
### RESTFUL AUTHENTICATION
###
include Authentication
include Authentication::ByPassword
include Authentication::ByCookieToken
# LOGIN SET BY EMAIL
# validates_presence_of :login
# validates_length_of :login, :within => 3..40
# validates_uniqueness_of :login
# validates_format_of :login, :with => Authentication.login_regex, :message => Authentication.bad_login_message
validates_presence_of :name
validates_format_of :name, :with => Authentication.name_regex, :message => Authentication.bad_name_message
validates_length_of :name, :maximum => 100
validates_presence_of :email
validates_length_of :email, :within => 6..100 #r@a.wk
validates_uniqueness_of :email
validates_format_of :email, :with => Authentication.email_regex, :message => Authentication.bad_email_message
# HACK HACK HACK -- how to do attr_accessible from here?
# prevents a user from submitting a crafted form that bypasses activation
# anything else you want your user to change should be added here.
attr_accessible :login, :email, :name, :password, :password_confirmation,
:remote_availability, :remote_availability_hours, :remote_availability_increment,
:local_availability, :local_availability_hours, :local_availability_increment,
:available_to_mentor, :available_to_be_mentored
# Authenticates a user by their login name and unencrypted password. Returns the user or nil.
#
# uff. this is really an authorization, not authentication routine.
# We really need a Dispatch Chain here or something.
# This will also let us return a human error message.
#
def self.authenticate(login, password)
return nil if login.blank? || password.blank?
u = find_by_login(login.downcase) # need to get the salt
u && u.authenticated?(password) ? u : nil
end
def login=(value)
write_attribute :login, (value ? value.downcase : nil)
end
def email=(value)
write_attribute :login, (value ? value.downcase : nil)
write_attribute :email, (value ? value.downcase : nil)
end
###
### END RESTFUL AUTHENTICATION
###
# ASSOCIATIONS
has_many :user_skills, :order => "level DESC"
has_many :skills, :through => :user_skills
# ADD GRAVATAR SUPPORT
is_gravtastic
def to_s
"#{name}"
end
def user_skills_by_level(level)
user_skills.select{ |us| us.level == level.to_i }
end
def skills_by_level(level)
user_skills_by_level(level).collect{ |us| us.skill }
end
###
### Mentorships
###
def mentorships_to_respond_to
Mentorship.find(:all, :conditions => ["receiver_id = ? AND accepted_at IS NULL AND rejected_at IS NULL", self.id])
end
# Mentoring status
def current_mentoring_mentorship
Mentorship.find(:first, :conditions => ["mentor_id = ? AND accepted_at IS NOT NULL AND completed_at IS NULL", self.id])
end
def current_apprentice
current_mentoring_mentorship.mentee if current_mentoring_mentorship
end
def currently_mentoring?
current_mentoring_mentorship ? true : false
end
# Apprenticing status
def current_apprenticing_mentorship
Mentorship.find(:first, :conditions => ["mentee_id = ? AND accepted_at IS NOT NULL AND completed_at IS NULL", self.id])
end
def current_mentor
current_apprenticing_mentorship.mentor if current_apprenticing_mentorship
end
def currently_apprenticing?
current_apprenticing_mentorship ? true : false
end
# Availability is text based at this time
# I figure it will morph and change quite a bit at the beginning
# However, I still wanted user dropdowns to give a good jumping off point
# to choose your availability
# So, I created these methods that morph input from 2 drops downs
# (xxx_availability_hours and xxx_availability_increment) in the text field
# And we need them for both remote and local...a great opportunity to Meta Program
# Whenever these become more stable, let's do just that.
# TODO: Convert to metaprogrammed methods
# Remote availability
def remote_availability_hours
@remote_availability_hours ||= remote_availability.to_s.split(" hours per ").first.to_i
end
def remote_availability_increment
@remote_availability_increment ||= remote_availability.to_s.split(" hours per ").last
end
def remote_availability_hours=(new_value)
@remote_availability_hours = new_value
self.remote_availability = set_remote_availability
@remote_availability_hours
end
def remote_availability_increment=(new_value)
@remote_availability_increment = new_value
self.remote_availability = set_remote_availability
@remote_availability_increment
end
def derived_remote_availability
set_remote_availability
end
def set_remote_availability
if remote_availability_hours == 0
nil
else
"#{remote_availability_hours} hours per #{remote_availability_increment}"
end
end
# Local availability
def local_availability_hours
@local_availability_hours ||= local_availability.to_s.split(" hours per ").first.to_i
end
def local_availability_increment
@local_availability_increment ||= local_availability.to_s.split(" hours per ").last
end
def local_availability_hours=(new_value)
@local_availability_hours = new_value
self.local_availability = set_local_availability
@local_availability_hours
end
def local_availability_increment=(new_value)
@local_availability_increment = new_value
self.local_availability = set_local_availability
@local_availability_increment
end
def derived_local_availability
set_local_availability
end
def set_local_availability
if local_availability_hours == 0
nil
else
"#{local_availability_hours} hours per #{local_availability_increment}"
end
end
class << self
def availability_hours
(0..10).to_a
end
def availability_increments
["day", "week", "month"]
end
# TODO: This is replicated in Skill. One more and it's plugin time.
def random(limit=1)
# Get all the ids
ids = connection.select_all("SELECT id FROM #{table_name}")
# Return [] if ids are empty
return [] if ids.empty?
# Get 'limit' number of random ids
# Actually double the limit in case there are any duplicates
random_ids = []
(limit.to_i * 2).times do
random_ids << ids[rand(ids.size)]["id"].to_i
end
# Get uniq entries and cut the random_ids down to size
random_ids = random_ids.uniq[0..limit-1]
# Now look up those users
find(random_ids)
end
# TODO: This obviously need to be handled by a full-text search index
# Thinking-Sphinx is a personal fav and it will probably be coming soon
def search(q)
return [] if q.blank?
q = "%#{q}%"
results = []
# Look for name matches
results << User.find(:all, :conditions => ["name LIKE ?", q])
# Look for skill matches
skills = Skill.find(:all, :conditions => ["name LIKE ?", q])
results << UserSkill.find(:all, :conditions => ["skill_id IN (?)", skills.collect{ |s| s.id }], :include => [:user]).collect{ |us| us.user }
results.flatten.compact.uniq
end
end
end
|
markmcspadden/coding-mentors
|
app/models/user.rb
|
Ruby
|
mit
| 7,555
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Optional, Inject, Injectable, NgZone, NgModule, SkipSelf, ApplicationRef, ComponentFactoryResolver, Injector, ElementRef, Directive, EventEmitter, InjectionToken, Input, Output, TemplateRef, ViewContainerRef, defineInjectable, inject } from '@angular/core';
import { coerceCssPixelValue, coerceArray, coerceBooleanProperty } from '@angular/cdk/coercion';
import { ScrollDispatcher, ViewportRuler, ScrollDispatchModule, VIEWPORT_RULER_PROVIDER } from '@angular/cdk/scrolling';
export { ViewportRuler, VIEWPORT_RULER_PROVIDER, CdkScrollable, ScrollDispatcher } from '@angular/cdk/scrolling';
import { DOCUMENT } from '@angular/common';
import { Observable, Subject, merge, Subscription } from 'rxjs';
import { take, takeUntil } from 'rxjs/operators';
import { Platform } from '@angular/cdk/platform';
import { Directionality, BidiModule } from '@angular/cdk/bidi';
import { DomPortalOutlet, TemplatePortal, PortalModule } from '@angular/cdk/portal';
import { ESCAPE } from '@angular/cdk/keycodes';
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Scroll strategy that doesn't do anything.
*/
class NoopScrollStrategy {
/**
* Does nothing, as this scroll strategy is a no-op.
* @return {?}
*/
enable() { }
/**
* Does nothing, as this scroll strategy is a no-op.
* @return {?}
*/
disable() { }
/**
* Does nothing, as this scroll strategy is a no-op.
* @return {?}
*/
attach() { }
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Initial configuration used when creating an overlay.
*/
class OverlayConfig {
/**
* @param {?=} config
*/
constructor(config) {
/**
* Strategy to be used when handling scroll events while the overlay is open.
*/
this.scrollStrategy = new NoopScrollStrategy();
/**
* Custom class to add to the overlay pane.
*/
this.panelClass = '';
/**
* Whether the overlay has a backdrop.
*/
this.hasBackdrop = false;
/**
* Custom class to add to the backdrop
*/
this.backdropClass = 'cdk-overlay-dark-backdrop';
if (config) {
Object.keys(config)
.filter(key => typeof config[key] !== 'undefined')
.forEach(key => this[key] = config[key]);
}
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* The points of the origin element and the overlay element to connect.
*/
class ConnectionPositionPair {
/**
* @param {?} origin
* @param {?} overlay
* @param {?=} offsetX
* @param {?=} offsetY
*/
constructor(origin, overlay, offsetX, offsetY) {
this.offsetX = offsetX;
this.offsetY = offsetY;
this.originX = origin.originX;
this.originY = origin.originY;
this.overlayX = overlay.overlayX;
this.overlayY = overlay.overlayY;
}
}
/**
* Set of properties regarding the position of the origin and overlay relative to the viewport
* with respect to the containing Scrollable elements.
*
* The overlay and origin are clipped if any part of their bounding client rectangle exceeds the
* bounds of any one of the strategy's Scrollable's bounding client rectangle.
*
* The overlay and origin are outside view if there is no overlap between their bounding client
* rectangle and any one of the strategy's Scrollable's bounding client rectangle.
*
* ----------- -----------
* | outside | | clipped |
* | view | --------------------------
* | | | | | |
* ---------- | ----------- |
* -------------------------- | |
* | | | Scrollable |
* | | | |
* | | --------------------------
* | Scrollable |
* | |
* --------------------------
*
* \@docs-private
*/
class ScrollingVisibility {
}
/**
* The change event emitted by the strategy when a fallback position is used.
*/
class ConnectedOverlayPositionChange {
/**
* @param {?} connectionPair
* @param {?} scrollableViewProperties
*/
constructor(connectionPair, /** @docs-private */
scrollableViewProperties) {
this.connectionPair = connectionPair;
this.scrollableViewProperties = scrollableViewProperties;
}
}
/** @nocollapse */
ConnectedOverlayPositionChange.ctorParameters = () => [
{ type: ConnectionPositionPair, },
{ type: ScrollingVisibility, decorators: [{ type: Optional },] },
];
/**
* Validates whether a vertical position property matches the expected values.
* \@docs-private
* @param {?} property Name of the property being validated.
* @param {?} value Value of the property being validated.
* @return {?}
*/
function validateVerticalPosition(property, value) {
if (value !== 'top' && value !== 'bottom' && value !== 'center') {
throw Error(`ConnectedPosition: Invalid ${property} "${value}". ` +
`Expected "top", "bottom" or "center".`);
}
}
/**
* Validates whether a horizontal position property matches the expected values.
* \@docs-private
* @param {?} property Name of the property being validated.
* @param {?} value Value of the property being validated.
* @return {?}
*/
function validateHorizontalPosition(property, value) {
if (value !== 'start' && value !== 'end' && value !== 'center') {
throw Error(`ConnectedPosition: Invalid ${property} "${value}". ` +
`Expected "start", "end" or "center".`);
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Strategy that will prevent the user from scrolling while the overlay is visible.
*/
class BlockScrollStrategy {
/**
* @param {?} _viewportRuler
* @param {?} document
*/
constructor(_viewportRuler, document) {
this._viewportRuler = _viewportRuler;
this._previousHTMLStyles = { top: '', left: '' };
this._isEnabled = false;
this._document = document;
}
/**
* Attaches this scroll strategy to an overlay.
* @return {?}
*/
attach() { }
/**
* Blocks page-level scroll while the attached overlay is open.
* @return {?}
*/
enable() {
if (this._canBeEnabled()) {
const /** @type {?} */ root = this._document.documentElement;
this._previousScrollPosition = this._viewportRuler.getViewportScrollPosition();
// Cache the previous inline styles in case the user had set them.
this._previousHTMLStyles.left = root.style.left || '';
this._previousHTMLStyles.top = root.style.top || '';
// Note: we're using the `html` node, instead of the `body`, because the `body` may
// have the user agent margin, whereas the `html` is guaranteed not to have one.
root.style.left = coerceCssPixelValue(-this._previousScrollPosition.left);
root.style.top = coerceCssPixelValue(-this._previousScrollPosition.top);
root.classList.add('cdk-global-scrollblock');
this._isEnabled = true;
}
}
/**
* Unblocks page-level scroll while the attached overlay is open.
* @return {?}
*/
disable() {
if (this._isEnabled) {
const /** @type {?} */ html = this._document.documentElement;
const /** @type {?} */ body = this._document.body;
const /** @type {?} */ previousHtmlScrollBehavior = html.style['scrollBehavior'] || '';
const /** @type {?} */ previousBodyScrollBehavior = body.style['scrollBehavior'] || '';
this._isEnabled = false;
html.style.left = this._previousHTMLStyles.left;
html.style.top = this._previousHTMLStyles.top;
html.classList.remove('cdk-global-scrollblock');
// Disable user-defined smooth scrolling temporarily while we restore the scroll position.
// See https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior
html.style['scrollBehavior'] = body.style['scrollBehavior'] = 'auto';
window.scroll(this._previousScrollPosition.left, this._previousScrollPosition.top);
html.style['scrollBehavior'] = previousHtmlScrollBehavior;
body.style['scrollBehavior'] = previousBodyScrollBehavior;
}
}
/**
* @return {?}
*/
_canBeEnabled() {
// Since the scroll strategies can't be singletons, we have to use a global CSS class
// (`cdk-global-scrollblock`) to make sure that we don't try to disable global
// scrolling multiple times.
const /** @type {?} */ html = this._document.documentElement;
if (html.classList.contains('cdk-global-scrollblock') || this._isEnabled) {
return false;
}
const /** @type {?} */ body = this._document.body;
const /** @type {?} */ viewport = this._viewportRuler.getViewportSize();
return body.scrollHeight > viewport.height || body.scrollWidth > viewport.width;
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Returns an error to be thrown when attempting to attach an already-attached scroll strategy.
* @return {?}
*/
function getMatScrollStrategyAlreadyAttachedError() {
return Error(`Scroll strategy has already been attached.`);
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Strategy that will close the overlay as soon as the user starts scrolling.
*/
class CloseScrollStrategy {
/**
* @param {?} _scrollDispatcher
* @param {?} _ngZone
* @param {?} _viewportRuler
* @param {?=} _config
*/
constructor(_scrollDispatcher, _ngZone, _viewportRuler, _config) {
this._scrollDispatcher = _scrollDispatcher;
this._ngZone = _ngZone;
this._viewportRuler = _viewportRuler;
this._config = _config;
this._scrollSubscription = null;
/**
* Detaches the overlay ref and disables the scroll strategy.
*/
this._detach = () => {
this.disable();
if (this._overlayRef.hasAttached()) {
this._ngZone.run(() => this._overlayRef.detach());
}
};
}
/**
* Attaches this scroll strategy to an overlay.
* @param {?} overlayRef
* @return {?}
*/
attach(overlayRef) {
if (this._overlayRef) {
throw getMatScrollStrategyAlreadyAttachedError();
}
this._overlayRef = overlayRef;
}
/**
* Enables the closing of the attached overlay on scroll.
* @return {?}
*/
enable() {
if (this._scrollSubscription) {
return;
}
const /** @type {?} */ stream = this._scrollDispatcher.scrolled(0);
if (this._config && this._config.threshold && this._config.threshold > 1) {
this._initialScrollPosition = this._viewportRuler.getViewportScrollPosition().top;
this._scrollSubscription = stream.subscribe(() => {
const /** @type {?} */ scrollPosition = this._viewportRuler.getViewportScrollPosition().top;
if (Math.abs(scrollPosition - this._initialScrollPosition) > /** @type {?} */ ((/** @type {?} */ ((this._config)).threshold))) {
this._detach();
}
else {
this._overlayRef.updatePosition();
}
});
}
else {
this._scrollSubscription = stream.subscribe(this._detach);
}
}
/**
* Disables the closing the attached overlay on scroll.
* @return {?}
*/
disable() {
if (this._scrollSubscription) {
this._scrollSubscription.unsubscribe();
this._scrollSubscription = null;
}
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
// TODO(jelbourn): move this to live with the rest of the scrolling code
// TODO(jelbourn): someday replace this with IntersectionObservers
/**
* Gets whether an element is scrolled outside of view by any of its parent scrolling containers.
* \@docs-private
* @param {?} element Dimensions of the element (from getBoundingClientRect)
* @param {?} scrollContainers Dimensions of element's scrolling containers (from getBoundingClientRect)
* @return {?} Whether the element is scrolled out of view
*/
function isElementScrolledOutsideView(element, scrollContainers) {
return scrollContainers.some(containerBounds => {
const /** @type {?} */ outsideAbove = element.bottom < containerBounds.top;
const /** @type {?} */ outsideBelow = element.top > containerBounds.bottom;
const /** @type {?} */ outsideLeft = element.right < containerBounds.left;
const /** @type {?} */ outsideRight = element.left > containerBounds.right;
return outsideAbove || outsideBelow || outsideLeft || outsideRight;
});
}
/**
* Gets whether an element is clipped by any of its scrolling containers.
* \@docs-private
* @param {?} element Dimensions of the element (from getBoundingClientRect)
* @param {?} scrollContainers Dimensions of element's scrolling containers (from getBoundingClientRect)
* @return {?} Whether the element is clipped
*/
function isElementClippedByScrolling(element, scrollContainers) {
return scrollContainers.some(scrollContainerRect => {
const /** @type {?} */ clippedAbove = element.top < scrollContainerRect.top;
const /** @type {?} */ clippedBelow = element.bottom > scrollContainerRect.bottom;
const /** @type {?} */ clippedLeft = element.left < scrollContainerRect.left;
const /** @type {?} */ clippedRight = element.right > scrollContainerRect.right;
return clippedAbove || clippedBelow || clippedLeft || clippedRight;
});
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Strategy that will update the element position as the user is scrolling.
*/
class RepositionScrollStrategy {
/**
* @param {?} _scrollDispatcher
* @param {?} _viewportRuler
* @param {?} _ngZone
* @param {?=} _config
*/
constructor(_scrollDispatcher, _viewportRuler, _ngZone, _config) {
this._scrollDispatcher = _scrollDispatcher;
this._viewportRuler = _viewportRuler;
this._ngZone = _ngZone;
this._config = _config;
this._scrollSubscription = null;
}
/**
* Attaches this scroll strategy to an overlay.
* @param {?} overlayRef
* @return {?}
*/
attach(overlayRef) {
if (this._overlayRef) {
throw getMatScrollStrategyAlreadyAttachedError();
}
this._overlayRef = overlayRef;
}
/**
* Enables repositioning of the attached overlay on scroll.
* @return {?}
*/
enable() {
if (!this._scrollSubscription) {
const /** @type {?} */ throttle = this._config ? this._config.scrollThrottle : 0;
this._scrollSubscription = this._scrollDispatcher.scrolled(throttle).subscribe(() => {
this._overlayRef.updatePosition();
// TODO(crisbeto): make `close` on by default once all components can handle it.
if (this._config && this._config.autoClose) {
const /** @type {?} */ overlayRect = this._overlayRef.overlayElement.getBoundingClientRect();
const { width, height } = this._viewportRuler.getViewportSize();
// TODO(crisbeto): include all ancestor scroll containers here once
// we have a way of exposing the trigger element to the scroll strategy.
const /** @type {?} */ parentRects = [{ width, height, bottom: height, right: width, top: 0, left: 0 }];
if (isElementScrolledOutsideView(overlayRect, parentRects)) {
this.disable();
this._ngZone.run(() => this._overlayRef.detach());
}
}
});
}
}
/**
* Disables repositioning of the attached overlay on scroll.
* @return {?}
*/
disable() {
if (this._scrollSubscription) {
this._scrollSubscription.unsubscribe();
this._scrollSubscription = null;
}
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Options for how an overlay will handle scrolling.
*
* Users can provide a custom value for `ScrollStrategyOptions` to replace the default
* behaviors. This class primarily acts as a factory for ScrollStrategy instances.
*/
class ScrollStrategyOptions {
/**
* @param {?} _scrollDispatcher
* @param {?} _viewportRuler
* @param {?} _ngZone
* @param {?} document
*/
constructor(_scrollDispatcher, _viewportRuler, _ngZone, document) {
this._scrollDispatcher = _scrollDispatcher;
this._viewportRuler = _viewportRuler;
this._ngZone = _ngZone;
/**
* Do nothing on scroll.
*/
this.noop = () => new NoopScrollStrategy();
/**
* Close the overlay as soon as the user scrolls.
* @param config Configuration to be used inside the scroll strategy.
*/
this.close = (config) => new CloseScrollStrategy(this._scrollDispatcher, this._ngZone, this._viewportRuler, config);
/**
* Block scrolling.
*/
this.block = () => new BlockScrollStrategy(this._viewportRuler, this._document);
/**
* Update the overlay's position on scroll.
* @param config Configuration to be used inside the scroll strategy.
* Allows debouncing the reposition calls.
*/
this.reposition = (config) => new RepositionScrollStrategy(this._scrollDispatcher, this._viewportRuler, this._ngZone, config);
this._document = document;
}
}
ScrollStrategyOptions.decorators = [
{ type: Injectable, args: [{ providedIn: 'root' },] },
];
/** @nocollapse */
ScrollStrategyOptions.ctorParameters = () => [
{ type: ScrollDispatcher, },
{ type: ViewportRuler, },
{ type: NgZone, },
{ type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] },] },
];
/** @nocollapse */ ScrollStrategyOptions.ngInjectableDef = defineInjectable({ factory: function ScrollStrategyOptions_Factory() { return new ScrollStrategyOptions(inject(ScrollDispatcher), inject(ViewportRuler), inject(NgZone), inject(DOCUMENT)); }, token: ScrollStrategyOptions, providedIn: "root" });
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Service for dispatching keyboard events that land on the body to appropriate overlay ref,
* if any. It maintains a list of attached overlays to determine best suited overlay based
* on event target and order of overlay opens.
*/
class OverlayKeyboardDispatcher {
/**
* @param {?} document
*/
constructor(document) {
/**
* Currently attached overlays in the order they were attached.
*/
this._attachedOverlays = [];
/**
* Keyboard event listener that will be attached to the body.
*/
this._keydownListener = (event) => {
const /** @type {?} */ overlays = this._attachedOverlays;
for (let /** @type {?} */ i = overlays.length - 1; i > -1; i--) {
// Dispatch the keydown event to the top overlay which has subscribers to its keydown events.
// We want to target the most recent overlay, rather than trying to match where the event came
// from, because some components might open an overlay, but keep focus on a trigger element
// (e.g. for select and autocomplete). We skip overlays without keydown event subscriptions,
// because we don't want overlays that don't handle keyboard events to block the ones below
// them that do.
if (overlays[i]._keydownEventSubscriptions > 0) {
overlays[i]._keydownEvents.next(event);
break;
}
}
};
this._document = document;
}
/**
* @return {?}
*/
ngOnDestroy() {
this._detach();
}
/**
* Add a new overlay to the list of attached overlay refs.
* @param {?} overlayRef
* @return {?}
*/
add(overlayRef) {
// Ensure that we don't get the same overlay multiple times.
this.remove(overlayRef);
// Lazily start dispatcher once first overlay is added
if (!this._isAttached) {
this._document.body.addEventListener('keydown', this._keydownListener, true);
this._isAttached = true;
}
this._attachedOverlays.push(overlayRef);
}
/**
* Remove an overlay from the list of attached overlay refs.
* @param {?} overlayRef
* @return {?}
*/
remove(overlayRef) {
const /** @type {?} */ index = this._attachedOverlays.indexOf(overlayRef);
if (index > -1) {
this._attachedOverlays.splice(index, 1);
}
// Remove the global listener once there are no more overlays.
if (this._attachedOverlays.length === 0) {
this._detach();
}
}
/**
* Detaches the global keyboard event listener.
* @return {?}
*/
_detach() {
if (this._isAttached) {
this._document.body.removeEventListener('keydown', this._keydownListener, true);
this._isAttached = false;
}
}
}
OverlayKeyboardDispatcher.decorators = [
{ type: Injectable, args: [{ providedIn: 'root' },] },
];
/** @nocollapse */
OverlayKeyboardDispatcher.ctorParameters = () => [
{ type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] },] },
];
/** @nocollapse */ OverlayKeyboardDispatcher.ngInjectableDef = defineInjectable({ factory: function OverlayKeyboardDispatcher_Factory() { return new OverlayKeyboardDispatcher(inject(DOCUMENT)); }, token: OverlayKeyboardDispatcher, providedIn: "root" });
/**
* \@docs-private \@deprecated \@breaking-change 7.0.0
* @param {?} dispatcher
* @param {?} _document
* @return {?}
*/
function OVERLAY_KEYBOARD_DISPATCHER_PROVIDER_FACTORY(dispatcher, _document) {
return dispatcher || new OverlayKeyboardDispatcher(_document);
}
/**
* \@docs-private \@deprecated \@breaking-change 7.0.0
*/
const /** @type {?} */ OVERLAY_KEYBOARD_DISPATCHER_PROVIDER = {
// If there is already an OverlayKeyboardDispatcher available, use that.
// Otherwise, provide a new one.
provide: OverlayKeyboardDispatcher,
deps: [
[new Optional(), new SkipSelf(), OverlayKeyboardDispatcher],
/** @type {?} */ (
// Coerce to `InjectionToken` so that the `deps` match the "shape"
// of the type expected by Angular
DOCUMENT)
],
useFactory: OVERLAY_KEYBOARD_DISPATCHER_PROVIDER_FACTORY
};
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Container inside which all overlays will render.
*/
class OverlayContainer {
/**
* @param {?} _document
*/
constructor(_document) {
this._document = _document;
}
/**
* @return {?}
*/
ngOnDestroy() {
if (this._containerElement && this._containerElement.parentNode) {
this._containerElement.parentNode.removeChild(this._containerElement);
}
}
/**
* This method returns the overlay container element. It will lazily
* create the element the first time it is called to facilitate using
* the container in non-browser environments.
* @return {?} the container element
*/
getContainerElement() {
if (!this._containerElement) {
this._createContainer();
}
return this._containerElement;
}
/**
* Create the overlay container element, which is simply a div
* with the 'cdk-overlay-container' class on the document body.
* @return {?}
*/
_createContainer() {
const /** @type {?} */ container = this._document.createElement('div');
container.classList.add('cdk-overlay-container');
this._document.body.appendChild(container);
this._containerElement = container;
}
}
OverlayContainer.decorators = [
{ type: Injectable, args: [{ providedIn: 'root' },] },
];
/** @nocollapse */
OverlayContainer.ctorParameters = () => [
{ type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] },] },
];
/** @nocollapse */ OverlayContainer.ngInjectableDef = defineInjectable({ factory: function OverlayContainer_Factory() { return new OverlayContainer(inject(DOCUMENT)); }, token: OverlayContainer, providedIn: "root" });
/**
* \@docs-private \@deprecated \@breaking-change 7.0.0
* @param {?} parentContainer
* @param {?} _document
* @return {?}
*/
function OVERLAY_CONTAINER_PROVIDER_FACTORY(parentContainer, _document) {
return parentContainer || new OverlayContainer(_document);
}
/**
* \@docs-private \@deprecated \@breaking-change 7.0.0
*/
const /** @type {?} */ OVERLAY_CONTAINER_PROVIDER = {
// If there is already an OverlayContainer available, use that. Otherwise, provide a new one.
provide: OverlayContainer,
deps: [
[new Optional(), new SkipSelf(), OverlayContainer],
/** @type {?} */ (DOCUMENT // We need to use the InjectionToken somewhere to keep TS happy
) // We need to use the InjectionToken somewhere to keep TS happy
],
useFactory: OVERLAY_CONTAINER_PROVIDER_FACTORY
};
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Reference to an overlay that has been created with the Overlay service.
* Used to manipulate or dispose of said overlay.
*/
class OverlayRef {
/**
* @param {?} _portalOutlet
* @param {?} _host
* @param {?} _pane
* @param {?} _config
* @param {?} _ngZone
* @param {?} _keyboardDispatcher
* @param {?} _document
*/
constructor(_portalOutlet, _host, _pane, _config, _ngZone, _keyboardDispatcher, _document) {
this._portalOutlet = _portalOutlet;
this._host = _host;
this._pane = _pane;
this._config = _config;
this._ngZone = _ngZone;
this._keyboardDispatcher = _keyboardDispatcher;
this._document = _document;
this._backdropElement = null;
this._backdropClick = new Subject();
this._attachments = new Subject();
this._detachments = new Subject();
this._keydownEventsObservable = Observable.create(observer => {
const /** @type {?} */ subscription = this._keydownEvents.subscribe(observer);
this._keydownEventSubscriptions++;
return () => {
subscription.unsubscribe();
this._keydownEventSubscriptions--;
};
});
/**
* Stream of keydown events dispatched to this overlay.
*/
this._keydownEvents = new Subject();
/**
* Amount of subscriptions to the keydown events.
*/
this._keydownEventSubscriptions = 0;
if (_config.scrollStrategy) {
_config.scrollStrategy.attach(this);
}
}
/**
* The overlay's HTML element
* @return {?}
*/
get overlayElement() {
return this._pane;
}
/**
* The overlay's backdrop HTML element.
* @return {?}
*/
get backdropElement() {
return this._backdropElement;
}
/**
* Wrapper around the panel element. Can be used for advanced
* positioning where a wrapper with specific styling is
* required around the overlay pane.
* @return {?}
*/
get hostElement() {
return this._host;
}
/**
* Attaches content, given via a Portal, to the overlay.
* If the overlay is configured to have a backdrop, it will be created.
*
* @param {?} portal Portal instance to which to attach the overlay.
* @return {?} The portal attachment result.
*/
attach(portal) {
let /** @type {?} */ attachResult = this._portalOutlet.attach(portal);
if (this._config.positionStrategy) {
this._config.positionStrategy.attach(this);
}
// Update the pane element with the given configuration.
if (!this._host.parentElement && this._previousHostParent) {
this._previousHostParent.appendChild(this._host);
}
this._updateStackingOrder();
this._updateElementSize();
this._updateElementDirection();
if (this._config.scrollStrategy) {
this._config.scrollStrategy.enable();
}
// Update the position once the zone is stable so that the overlay will be fully rendered
// before attempting to position it, as the position may depend on the size of the rendered
// content.
this._ngZone.onStable
.asObservable()
.pipe(take(1))
.subscribe(() => {
// The overlay could've been detached before the zone has stabilized.
if (this.hasAttached()) {
this.updatePosition();
}
});
// Enable pointer events for the overlay pane element.
this._togglePointerEvents(true);
if (this._config.hasBackdrop) {
this._attachBackdrop();
}
if (this._config.panelClass) {
this._toggleClasses(this._pane, this._config.panelClass, true);
}
// Only emit the `attachments` event once all other setup is done.
this._attachments.next();
// Track this overlay by the keyboard dispatcher
this._keyboardDispatcher.add(this);
return attachResult;
}
/**
* Detaches an overlay from a portal.
* @return {?} The portal detachment result.
*/
detach() {
if (!this.hasAttached()) {
return;
}
this.detachBackdrop();
// When the overlay is detached, the pane element should disable pointer events.
// This is necessary because otherwise the pane element will cover the page and disable
// pointer events therefore. Depends on the position strategy and the applied pane boundaries.
this._togglePointerEvents(false);
if (this._config.positionStrategy && this._config.positionStrategy.detach) {
this._config.positionStrategy.detach();
}
if (this._config.scrollStrategy) {
this._config.scrollStrategy.disable();
}
if (this._config.panelClass) {
this._toggleClasses(this._pane, this._config.panelClass, false);
}
const /** @type {?} */ detachmentResult = this._portalOutlet.detach();
// Only emit after everything is detached.
this._detachments.next();
// Remove this overlay from keyboard dispatcher tracking.
this._keyboardDispatcher.remove(this);
// Keeping the host element in DOM the can cause scroll jank, because it still gets rendered,
// even though it's transparent and unclickable. We can't remove the host here immediately,
// because the overlay pane's content might still be animating. This stream helps us avoid
// interrupting the animation by waiting for the pane to become empty.
const /** @type {?} */ subscription = this._ngZone.onStable
.asObservable()
.pipe(takeUntil(merge(this._attachments, this._detachments)))
.subscribe(() => {
// Needs a couple of checks for the pane and host, because
// they may have been removed by the time the zone stabilizes.
if (!this._pane || !this._host || this._pane.children.length === 0) {
if (this._host && this._host.parentElement) {
this._previousHostParent = this._host.parentElement;
this._previousHostParent.removeChild(this._host);
}
subscription.unsubscribe();
}
});
return detachmentResult;
}
/**
* Cleans up the overlay from the DOM.
* @return {?}
*/
dispose() {
const /** @type {?} */ isAttached = this.hasAttached();
if (this._config.positionStrategy) {
this._config.positionStrategy.dispose();
}
if (this._config.scrollStrategy) {
this._config.scrollStrategy.disable();
}
this.detachBackdrop();
this._keyboardDispatcher.remove(this);
this._portalOutlet.dispose();
this._attachments.complete();
this._backdropClick.complete();
this._keydownEvents.complete();
if (this._host && this._host.parentNode) {
this._host.parentNode.removeChild(this._host);
this._host = /** @type {?} */ ((null));
}
this._previousHostParent = this._pane = /** @type {?} */ ((null));
if (isAttached) {
this._detachments.next();
}
this._detachments.complete();
}
/**
* Whether the overlay has attached content.
* @return {?}
*/
hasAttached() {
return this._portalOutlet.hasAttached();
}
/**
* Gets an observable that emits when the backdrop has been clicked.
* @return {?}
*/
backdropClick() {
return this._backdropClick.asObservable();
}
/**
* Gets an observable that emits when the overlay has been attached.
* @return {?}
*/
attachments() {
return this._attachments.asObservable();
}
/**
* Gets an observable that emits when the overlay has been detached.
* @return {?}
*/
detachments() {
return this._detachments.asObservable();
}
/**
* Gets an observable of keydown events targeted to this overlay.
* @return {?}
*/
keydownEvents() {
return this._keydownEventsObservable;
}
/**
* Gets the the current overlay configuration, which is immutable.
* @return {?}
*/
getConfig() {
return this._config;
}
/**
* Updates the position of the overlay based on the position strategy.
* @return {?}
*/
updatePosition() {
if (this._config.positionStrategy) {
this._config.positionStrategy.apply();
}
}
/**
* Update the size properties of the overlay.
* @param {?} sizeConfig
* @return {?}
*/
updateSize(sizeConfig) {
this._config = Object.assign({}, this._config, sizeConfig);
this._updateElementSize();
}
/**
* Sets the LTR/RTL direction for the overlay.
* @param {?} dir
* @return {?}
*/
setDirection(dir) {
this._config = Object.assign({}, this._config, { direction: dir });
this._updateElementDirection();
}
/**
* Returns the layout direction of the overlay panel.
* @return {?}
*/
getDirection() {
const /** @type {?} */ direction = this._config.direction;
if (!direction) {
return 'ltr';
}
return typeof direction === 'string' ? direction : direction.value;
}
/**
* Updates the text direction of the overlay panel.
* @return {?}
*/
_updateElementDirection() {
this._host.setAttribute('dir', this.getDirection());
}
/**
* Updates the size of the overlay element based on the overlay config.
* @return {?}
*/
_updateElementSize() {
const /** @type {?} */ style = this._pane.style;
style.width = coerceCssPixelValue(this._config.width);
style.height = coerceCssPixelValue(this._config.height);
style.minWidth = coerceCssPixelValue(this._config.minWidth);
style.minHeight = coerceCssPixelValue(this._config.minHeight);
style.maxWidth = coerceCssPixelValue(this._config.maxWidth);
style.maxHeight = coerceCssPixelValue(this._config.maxHeight);
}
/**
* Toggles the pointer events for the overlay pane element.
* @param {?} enablePointer
* @return {?}
*/
_togglePointerEvents(enablePointer) {
this._pane.style.pointerEvents = enablePointer ? 'auto' : 'none';
}
/**
* Attaches a backdrop for this overlay.
* @return {?}
*/
_attachBackdrop() {
const /** @type {?} */ showingClass = 'cdk-overlay-backdrop-showing';
this._backdropElement = this._document.createElement('div');
this._backdropElement.classList.add('cdk-overlay-backdrop');
if (this._config.backdropClass) {
this._toggleClasses(this._backdropElement, this._config.backdropClass, true);
} /** @type {?} */
((
// Insert the backdrop before the pane in the DOM order,
// in order to handle stacked overlays properly.
this._host.parentElement)).insertBefore(this._backdropElement, this._host);
// Forward backdrop clicks such that the consumer of the overlay can perform whatever
// action desired when such a click occurs (usually closing the overlay).
this._backdropElement.addEventListener('click', (event) => this._backdropClick.next(event));
// Add class to fade-in the backdrop after one frame.
if (typeof requestAnimationFrame !== 'undefined') {
this._ngZone.runOutsideAngular(() => {
requestAnimationFrame(() => {
if (this._backdropElement) {
this._backdropElement.classList.add(showingClass);
}
});
});
}
else {
this._backdropElement.classList.add(showingClass);
}
}
/**
* Updates the stacking order of the element, moving it to the top if necessary.
* This is required in cases where one overlay was detached, while another one,
* that should be behind it, was destroyed. The next time both of them are opened,
* the stacking will be wrong, because the detached element's pane will still be
* in its original DOM position.
* @return {?}
*/
_updateStackingOrder() {
if (this._host.nextSibling) {
/** @type {?} */ ((this._host.parentNode)).appendChild(this._host);
}
}
/**
* Detaches the backdrop (if any) associated with the overlay.
* @return {?}
*/
detachBackdrop() {
let /** @type {?} */ backdropToDetach = this._backdropElement;
if (backdropToDetach) {
let /** @type {?} */ timeoutId;
let /** @type {?} */ finishDetach = () => {
// It may not be attached to anything in certain cases (e.g. unit tests).
if (backdropToDetach && backdropToDetach.parentNode) {
backdropToDetach.parentNode.removeChild(backdropToDetach);
}
// It is possible that a new portal has been attached to this overlay since we started
// removing the backdrop. If that is the case, only clear the backdrop reference if it
// is still the same instance that we started to remove.
if (this._backdropElement == backdropToDetach) {
this._backdropElement = null;
}
clearTimeout(timeoutId);
};
backdropToDetach.classList.remove('cdk-overlay-backdrop-showing');
if (this._config.backdropClass) {
this._toggleClasses(backdropToDetach, this._config.backdropClass, false);
}
this._ngZone.runOutsideAngular(() => {
/** @type {?} */ ((backdropToDetach)).addEventListener('transitionend', finishDetach);
});
// If the backdrop doesn't have a transition, the `transitionend` event won't fire.
// In this case we make it unclickable and we try to remove it after a delay.
backdropToDetach.style.pointerEvents = 'none';
// Run this outside the Angular zone because there's nothing that Angular cares about.
// If it were to run inside the Angular zone, every test that used Overlay would have to be
// either async or fakeAsync.
timeoutId = this._ngZone.runOutsideAngular(() => setTimeout(finishDetach, 500));
}
}
/**
* Toggles a single CSS class or an array of classes on an element.
* @param {?} element
* @param {?} cssClasses
* @param {?} isAdd
* @return {?}
*/
_toggleClasses(element, cssClasses, isAdd) {
const /** @type {?} */ classList = element.classList;
coerceArray(cssClasses).forEach(cssClass => {
// We can't do a spread here, because IE doesn't support setting multiple classes.
isAdd ? classList.add(cssClass) : classList.remove(cssClass);
});
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* A strategy for positioning overlays. Using this strategy, an overlay is given an
* implicit position relative some origin element. The relative position is defined in terms of
* a point on the origin element that is connected to a point on the overlay element. For example,
* a basic dropdown is connecting the bottom-left corner of the origin to the top-left corner
* of the overlay.
*/
class FlexibleConnectedPositionStrategy {
/**
* @param {?} connectedTo
* @param {?} _viewportRuler
* @param {?} _document
* @param {?=} _platform
* @param {?=} _overlayContainer
*/
constructor(connectedTo, _viewportRuler, _document, _platform, _overlayContainer) {
this._viewportRuler = _viewportRuler;
this._document = _document;
this._platform = _platform;
this._overlayContainer = _overlayContainer;
/**
* Whether we're performing the very first positioning of the overlay.
*/
this._isInitialRender = true;
/**
* Last size used for the bounding box. Used to avoid resizing the overlay after open.
*/
this._lastBoundingBoxSize = { width: 0, height: 0 };
/**
* Whether the overlay was pushed in a previous positioning.
*/
this._isPushed = false;
/**
* Whether the overlay can be pushed on-screen on the initial open.
*/
this._canPush = true;
/**
* Whether the overlay can grow via flexible width/height after the initial open.
*/
this._growAfterOpen = false;
/**
* Whether the overlay's width and height can be constrained to fit within the viewport.
*/
this._hasFlexibleDimensions = true;
/**
* Whether the overlay position is locked.
*/
this._positionLocked = false;
/**
* Amount of space that must be maintained between the overlay and the edge of the viewport.
*/
this._viewportMargin = 0;
/**
* The Scrollable containers used to check scrollable view properties on position change.
*/
this.scrollables = [];
/**
* Ordered list of preferred positions, from most to least desirable.
*/
this._preferredPositions = [];
/**
* Subject that emits whenever the position changes.
*/
this._positionChanges = new Subject();
/**
* Subscription to viewport size changes.
*/
this._resizeSubscription = Subscription.EMPTY;
/**
* Default offset for the overlay along the x axis.
*/
this._offsetX = 0;
/**
* Default offset for the overlay along the y axis.
*/
this._offsetY = 0;
/**
* Amount of subscribers to the `positionChanges` stream.
*/
this._positionChangeSubscriptions = 0;
/**
* Observable sequence of position changes.
*/
this.positionChanges = Observable.create(observer => {
const /** @type {?} */ subscription = this._positionChanges.subscribe(observer);
this._positionChangeSubscriptions++;
return () => {
subscription.unsubscribe();
this._positionChangeSubscriptions--;
};
});
this.setOrigin(connectedTo);
}
/**
* Ordered list of preferred positions, from most to least desirable.
* @return {?}
*/
get positions() {
return this._preferredPositions;
}
/**
* Attaches this position strategy to an overlay.
* @param {?} overlayRef
* @return {?}
*/
attach(overlayRef) {
if (this._overlayRef && overlayRef !== this._overlayRef) {
throw Error('This position strategy is already attached to an overlay');
}
this._validatePositions();
overlayRef.hostElement.classList.add('cdk-overlay-connected-position-bounding-box');
this._overlayRef = overlayRef;
this._boundingBox = overlayRef.hostElement;
this._pane = overlayRef.overlayElement;
this._resizeSubscription.unsubscribe();
this._resizeSubscription = this._viewportRuler.change().subscribe(() => this.apply());
}
/**
* Updates the position of the overlay element, using whichever preferred position relative
* to the origin best fits on-screen.
*
* The selection of a position goes as follows:
* - If any positions fit completely within the viewport as-is,
* choose the first position that does so.
* - If flexible dimensions are enabled and at least one satifies the given minimum width/height,
* choose the position with the greatest available size modified by the positions' weight.
* - If pushing is enabled, take the position that went off-screen the least and push it
* on-screen.
* - If none of the previous criteria were met, use the position that goes off-screen the least.
* \@docs-private
* @return {?}
*/
apply() {
// We shouldn't do anything if the strategy was disposed or we're on the server.
// @breaking-change 7.0.0 Remove `_platform` null check once it's guaranteed to be defined.
if (this._isDisposed || (this._platform && !this._platform.isBrowser)) {
return;
}
// If the position has been applied already (e.g. when the overlay was opened) and the
// consumer opted into locking in the position, re-use the old position, in order to
// prevent the overlay from jumping around.
if (!this._isInitialRender && this._positionLocked && this._lastPosition) {
this.reapplyLastPosition();
return;
}
this._resetOverlayElementStyles();
this._resetBoundingBoxStyles();
// We need the bounding rects for the origin and the overlay to determine how to position
// the overlay relative to the origin.
// We use the viewport rect to determine whether a position would go off-screen.
this._viewportRect = this._getNarrowedViewportRect();
this._originRect = this._origin.getBoundingClientRect();
this._overlayRect = this._pane.getBoundingClientRect();
const /** @type {?} */ originRect = this._originRect;
const /** @type {?} */ overlayRect = this._overlayRect;
const /** @type {?} */ viewportRect = this._viewportRect;
// Positions where the overlay will fit with flexible dimensions.
const /** @type {?} */ flexibleFits = [];
// Fallback if none of the preferred positions fit within the viewport.
let /** @type {?} */ fallback;
// Go through each of the preferred positions looking for a good fit.
// If a good fit is found, it will be applied immediately.
for (let /** @type {?} */ pos of this._preferredPositions) {
// Get the exact (x, y) coordinate for the point-of-origin on the origin element.
let /** @type {?} */ originPoint = this._getOriginPoint(originRect, pos);
// From that point-of-origin, get the exact (x, y) coordinate for the top-left corner of the
// overlay in this position. We use the top-left corner for calculations and later translate
// this into an appropriate (top, left, bottom, right) style.
let /** @type {?} */ overlayPoint = this._getOverlayPoint(originPoint, overlayRect, pos);
// Calculate how well the overlay would fit into the viewport with this point.
let /** @type {?} */ overlayFit = this._getOverlayFit(overlayPoint, overlayRect, viewportRect, pos);
// If the overlay, without any further work, fits into the viewport, use this position.
if (overlayFit.isCompletelyWithinViewport) {
this._isPushed = false;
this._applyPosition(pos, originPoint);
return;
}
// If the overlay has flexible dimensions, we can use this position
// so long as there's enough space for the minimum dimensions.
if (this._canFitWithFlexibleDimensions(overlayFit, overlayPoint, viewportRect)) {
// Save positions where the overlay will fit with flexible dimensions. We will use these
// if none of the positions fit *without* flexible dimensions.
flexibleFits.push({
position: pos,
origin: originPoint,
overlayRect,
boundingBoxRect: this._calculateBoundingBoxRect(originPoint, pos)
});
continue;
}
// If the current preferred position does not fit on the screen, remember the position
// if it has more visible area on-screen than we've seen and move onto the next preferred
// position.
if (!fallback || fallback.overlayFit.visibleArea < overlayFit.visibleArea) {
fallback = { overlayFit, overlayPoint, originPoint, position: pos, overlayRect };
}
}
// If there are any positions where the overlay would fit with flexible dimensions, choose the
// one that has the greatest area available modified by the position's weight
if (flexibleFits.length) {
let /** @type {?} */ bestFit = null;
let /** @type {?} */ bestScore = -1;
for (const /** @type {?} */ fit of flexibleFits) {
const /** @type {?} */ score = fit.boundingBoxRect.width * fit.boundingBoxRect.height * (fit.position.weight || 1);
if (score > bestScore) {
bestScore = score;
bestFit = fit;
}
}
this._isPushed = false;
this._applyPosition(/** @type {?} */ ((bestFit)).position, /** @type {?} */ ((bestFit)).origin);
return;
}
// When none of the preferred positions fit within the viewport, take the position
// that went off-screen the least and attempt to push it on-screen.
if (this._canPush) {
// TODO(jelbourn): after pushing, the opening "direction" of the overlay might not make sense.
this._isPushed = true;
this._applyPosition(/** @type {?} */ ((fallback)).position, /** @type {?} */ ((fallback)).originPoint);
return;
}
// All options for getting the overlay within the viewport have been exhausted, so go with the
// position that went off-screen the least.
this._applyPosition(/** @type {?} */ ((fallback)).position, /** @type {?} */ ((fallback)).originPoint);
}
/**
* @return {?}
*/
detach() {
this._resizeSubscription.unsubscribe();
}
/**
* Cleanup after the element gets destroyed.
* @return {?}
*/
dispose() {
if (!this._isDisposed) {
this.detach();
this._boundingBox = null;
this._positionChanges.complete();
this._isDisposed = true;
}
}
/**
* This re-aligns the overlay element with the trigger in its last calculated position,
* even if a position higher in the "preferred positions" list would now fit. This
* allows one to re-align the panel without changing the orientation of the panel.
* @return {?}
*/
reapplyLastPosition() {
if (!this._isDisposed && (!this._platform || this._platform.isBrowser)) {
this._originRect = this._origin.getBoundingClientRect();
this._overlayRect = this._pane.getBoundingClientRect();
this._viewportRect = this._getNarrowedViewportRect();
const /** @type {?} */ lastPosition = this._lastPosition || this._preferredPositions[0];
const /** @type {?} */ originPoint = this._getOriginPoint(this._originRect, lastPosition);
this._applyPosition(lastPosition, originPoint);
}
}
/**
* Sets the list of Scrollable containers that host the origin element so that
* on reposition we can evaluate if it or the overlay has been clipped or outside view. Every
* Scrollable must be an ancestor element of the strategy's origin element.
* @param {?} scrollables
* @return {?}
*/
withScrollableContainers(scrollables) {
this.scrollables = scrollables;
}
/**
* Adds new preferred positions.
* @param {?} positions List of positions options for this overlay.
* @return {?}
*/
withPositions(positions) {
this._preferredPositions = positions;
// If the last calculated position object isn't part of the positions anymore, clear
// it in order to avoid it being picked up if the consumer tries to re-apply.
if (positions.indexOf(/** @type {?} */ ((this._lastPosition))) === -1) {
this._lastPosition = null;
}
this._validatePositions();
return this;
}
/**
* Sets a minimum distance the overlay may be positioned to the edge of the viewport.
* @param {?} margin Required margin between the overlay and the viewport edge in pixels.
* @return {?}
*/
withViewportMargin(margin) {
this._viewportMargin = margin;
return this;
}
/**
* Sets whether the overlay's width and height can be constrained to fit within the viewport.
* @param {?=} flexibleDimensions
* @return {?}
*/
withFlexibleDimensions(flexibleDimensions = true) {
this._hasFlexibleDimensions = flexibleDimensions;
return this;
}
/**
* Sets whether the overlay can grow after the initial open via flexible width/height.
* @param {?=} growAfterOpen
* @return {?}
*/
withGrowAfterOpen(growAfterOpen = true) {
this._growAfterOpen = growAfterOpen;
return this;
}
/**
* Sets whether the overlay can be pushed on-screen if none of the provided positions fit.
* @param {?=} canPush
* @return {?}
*/
withPush(canPush = true) {
this._canPush = canPush;
return this;
}
/**
* Sets whether the overlay's position should be locked in after it is positioned
* initially. When an overlay is locked in, it won't attempt to reposition itself
* when the position is re-applied (e.g. when the user scrolls away).
* @param {?=} isLocked Whether the overlay should locked in.
* @return {?}
*/
withLockedPosition(isLocked = true) {
this._positionLocked = isLocked;
return this;
}
/**
* Sets the origin element, relative to which to position the overlay.
* @param {?} origin Reference to the new origin element.
* @return {?}
*/
setOrigin(origin) {
this._origin = origin instanceof ElementRef ? origin.nativeElement : origin;
return this;
}
/**
* Sets the default offset for the overlay's connection point on the x-axis.
* @param {?} offset New offset in the X axis.
* @return {?}
*/
withDefaultOffsetX(offset) {
this._offsetX = offset;
return this;
}
/**
* Sets the default offset for the overlay's connection point on the y-axis.
* @param {?} offset New offset in the Y axis.
* @return {?}
*/
withDefaultOffsetY(offset) {
this._offsetY = offset;
return this;
}
/**
* Configures that the position strategy should set a `transform-origin` on some elements
* inside the overlay, depending on the current position that is being applied. This is
* useful for the cases where the origin of an animation can change depending on the
* alignment of the overlay.
* @param {?} selector CSS selector that will be used to find the target
* elements onto which to set the transform origin.
* @return {?}
*/
withTransformOriginOn(selector) {
this._transformOriginSelector = selector;
return this;
}
/**
* Gets the (x, y) coordinate of a connection point on the origin based on a relative position.
* @param {?} originRect
* @param {?} pos
* @return {?}
*/
_getOriginPoint(originRect, pos) {
let /** @type {?} */ x;
if (pos.originX == 'center') {
// Note: when centering we should always use the `left`
// offset, otherwise the position will be wrong in RTL.
x = originRect.left + (originRect.width / 2);
}
else {
const /** @type {?} */ startX = this._isRtl() ? originRect.right : originRect.left;
const /** @type {?} */ endX = this._isRtl() ? originRect.left : originRect.right;
x = pos.originX == 'start' ? startX : endX;
}
let /** @type {?} */ y;
if (pos.originY == 'center') {
y = originRect.top + (originRect.height / 2);
}
else {
y = pos.originY == 'top' ? originRect.top : originRect.bottom;
}
return { x, y };
}
/**
* Gets the (x, y) coordinate of the top-left corner of the overlay given a given position and
* origin point to which the overlay should be connected.
* @param {?} originPoint
* @param {?} overlayRect
* @param {?} pos
* @return {?}
*/
_getOverlayPoint(originPoint, overlayRect, pos) {
// Calculate the (overlayStartX, overlayStartY), the start of the
// potential overlay position relative to the origin point.
let /** @type {?} */ overlayStartX;
if (pos.overlayX == 'center') {
overlayStartX = -overlayRect.width / 2;
}
else if (pos.overlayX === 'start') {
overlayStartX = this._isRtl() ? -overlayRect.width : 0;
}
else {
overlayStartX = this._isRtl() ? 0 : -overlayRect.width;
}
let /** @type {?} */ overlayStartY;
if (pos.overlayY == 'center') {
overlayStartY = -overlayRect.height / 2;
}
else {
overlayStartY = pos.overlayY == 'top' ? 0 : -overlayRect.height;
}
// The (x, y) coordinates of the overlay.
return {
x: originPoint.x + overlayStartX,
y: originPoint.y + overlayStartY,
};
}
/**
* Gets how well an overlay at the given point will fit within the viewport.
* @param {?} point
* @param {?} overlay
* @param {?} viewport
* @param {?} position
* @return {?}
*/
_getOverlayFit(point, overlay, viewport, position) {
let { x, y } = point;
let /** @type {?} */ offsetX = this._getOffset(position, 'x');
let /** @type {?} */ offsetY = this._getOffset(position, 'y');
// Account for the offsets since they could push the overlay out of the viewport.
if (offsetX) {
x += offsetX;
}
if (offsetY) {
y += offsetY;
}
// How much the overlay would overflow at this position, on each side.
let /** @type {?} */ leftOverflow = 0 - x;
let /** @type {?} */ rightOverflow = (x + overlay.width) - viewport.width;
let /** @type {?} */ topOverflow = 0 - y;
let /** @type {?} */ bottomOverflow = (y + overlay.height) - viewport.height;
// Visible parts of the element on each axis.
let /** @type {?} */ visibleWidth = this._subtractOverflows(overlay.width, leftOverflow, rightOverflow);
let /** @type {?} */ visibleHeight = this._subtractOverflows(overlay.height, topOverflow, bottomOverflow);
let /** @type {?} */ visibleArea = visibleWidth * visibleHeight;
return {
visibleArea,
isCompletelyWithinViewport: (overlay.width * overlay.height) === visibleArea,
fitsInViewportVertically: visibleHeight === overlay.height,
fitsInViewportHorizontally: visibleWidth == overlay.width,
};
}
/**
* Whether the overlay can fit within the viewport when it may resize either its width or height.
* @param {?} fit How well the overlay fits in the viewport at some position.
* @param {?} point The (x, y) coordinates of the overlat at some position.
* @param {?} viewport The geometry of the viewport.
* @return {?}
*/
_canFitWithFlexibleDimensions(fit, point, viewport) {
if (this._hasFlexibleDimensions) {
const /** @type {?} */ availableHeight = viewport.bottom - point.y;
const /** @type {?} */ availableWidth = viewport.right - point.x;
const /** @type {?} */ minHeight = this._overlayRef.getConfig().minHeight;
const /** @type {?} */ minWidth = this._overlayRef.getConfig().minWidth;
const /** @type {?} */ verticalFit = fit.fitsInViewportVertically ||
(minHeight != null && minHeight <= availableHeight);
const /** @type {?} */ horizontalFit = fit.fitsInViewportHorizontally ||
(minWidth != null && minWidth <= availableWidth);
return verticalFit && horizontalFit;
}
}
/**
* Gets the point at which the overlay can be "pushed" on-screen. If the overlay is larger than
* the viewport, the top-left corner will be pushed on-screen (with overflow occuring on the
* right and bottom).
*
* @param {?} start The starting point from which the overlay is pushed.
* @param {?} overlay The overlay dimensions.
* @return {?} The point at which to position the overlay after pushing. This is effectively a new
* originPoint.
*/
_pushOverlayOnScreen(start, overlay) {
const /** @type {?} */ viewport = this._viewportRect;
// Determine how much the overlay goes outside the viewport on each side, which we'll use to
// decide which direction to push it.
const /** @type {?} */ overflowRight = Math.max(start.x + overlay.width - viewport.right, 0);
const /** @type {?} */ overflowBottom = Math.max(start.y + overlay.height - viewport.bottom, 0);
const /** @type {?} */ overflowTop = Math.max(viewport.top - start.y, 0);
const /** @type {?} */ overflowLeft = Math.max(viewport.left - start.x, 0);
// Amount by which to push the overlay in each direction such that it remains on-screen.
let /** @type {?} */ pushX, /** @type {?} */ pushY = 0;
// If the overlay fits completely within the bounds of the viewport, push it from whichever
// direction is goes off-screen. Otherwise, push the top-left corner such that its in the
// viewport and allow for the trailing end of the overlay to go out of bounds.
if (overlay.width <= viewport.width) {
pushX = overflowLeft || -overflowRight;
}
else {
pushX = viewport.left - start.x;
}
if (overlay.height <= viewport.height) {
pushY = overflowTop || -overflowBottom;
}
else {
pushY = viewport.top - start.y;
}
return {
x: start.x + pushX,
y: start.y + pushY,
};
}
/**
* Applies a computed position to the overlay and emits a position change.
* @param {?} position The position preference
* @param {?} originPoint The point on the origin element where the overlay is connected.
* @return {?}
*/
_applyPosition(position, originPoint) {
this._setTransformOrigin(position);
this._setOverlayElementStyles(originPoint, position);
this._setBoundingBoxStyles(originPoint, position);
// Save the last connected position in case the position needs to be re-calculated.
this._lastPosition = position;
// Notify that the position has been changed along with its change properties.
// We only emit if we've got any subscriptions, because the scroll visibility
// calculcations can be somewhat expensive.
if (this._positionChangeSubscriptions > 0) {
const /** @type {?} */ scrollableViewProperties = this._getScrollVisibility();
const /** @type {?} */ changeEvent = new ConnectedOverlayPositionChange(position, scrollableViewProperties);
this._positionChanges.next(changeEvent);
}
this._isInitialRender = false;
}
/**
* Sets the transform origin based on the configured selector and the passed-in position.
* @param {?} position
* @return {?}
*/
_setTransformOrigin(position) {
if (!this._transformOriginSelector) {
return;
}
const /** @type {?} */ elements = /** @type {?} */ ((this._boundingBox)).querySelectorAll(this._transformOriginSelector);
let /** @type {?} */ xOrigin;
let /** @type {?} */ yOrigin = position.overlayY;
if (position.overlayX === 'center') {
xOrigin = 'center';
}
else if (this._isRtl()) {
xOrigin = position.overlayX === 'start' ? 'right' : 'left';
}
else {
xOrigin = position.overlayX === 'start' ? 'left' : 'right';
}
for (let /** @type {?} */ i = 0; i < elements.length; i++) {
elements[i].style.transformOrigin = `${xOrigin} ${yOrigin}`;
}
}
/**
* Gets the position and size of the overlay's sizing container.
*
* This method does no measuring and applies no styles so that we can cheaply compute the
* bounds for all positions and choose the best fit based on these results.
* @param {?} origin
* @param {?} position
* @return {?}
*/
_calculateBoundingBoxRect(origin, position) {
const /** @type {?} */ viewport = this._viewportRect;
const /** @type {?} */ isRtl = this._isRtl();
let /** @type {?} */ height, /** @type {?} */ top, /** @type {?} */ bottom;
if (position.overlayY === 'top') {
// Overlay is opening "downward" and thus is bound by the bottom viewport edge.
top = origin.y;
height = viewport.bottom - origin.y;
}
else if (position.overlayY === 'bottom') {
// Overlay is opening "upward" and thus is bound by the top viewport edge. We need to add
// the viewport margin back in, because the viewport rect is narrowed down to remove the
// margin, whereas the `origin` position is calculated based on its `ClientRect`.
bottom = viewport.height - origin.y + this._viewportMargin * 2;
height = viewport.height - bottom + this._viewportMargin;
}
else {
// If neither top nor bottom, it means that the overlay
// is vertically centered on the origin point.
const /** @type {?} */ smallestDistanceToViewportEdge = Math.min(viewport.bottom - origin.y, origin.y - viewport.left);
const /** @type {?} */ previousHeight = this._lastBoundingBoxSize.height;
height = smallestDistanceToViewportEdge * 2;
top = origin.y - smallestDistanceToViewportEdge;
if (height > previousHeight && !this._isInitialRender && !this._growAfterOpen) {
top = origin.y - (previousHeight / 2);
}
}
// The overlay is opening 'right-ward' (the content flows to the right).
const /** @type {?} */ isBoundedByRightViewportEdge = (position.overlayX === 'start' && !isRtl) ||
(position.overlayX === 'end' && isRtl);
// The overlay is opening 'left-ward' (the content flows to the left).
const /** @type {?} */ isBoundedByLeftViewportEdge = (position.overlayX === 'end' && !isRtl) ||
(position.overlayX === 'start' && isRtl);
let /** @type {?} */ width, /** @type {?} */ left, /** @type {?} */ right;
if (isBoundedByLeftViewportEdge) {
right = viewport.right - origin.x + this._viewportMargin;
width = origin.x - viewport.left;
}
else if (isBoundedByRightViewportEdge) {
left = origin.x;
width = viewport.right - origin.x;
}
else {
// If neither start nor end, it means that the overlay
// is horizontally centered on the origin point.
const /** @type {?} */ smallestDistanceToViewportEdge = Math.min(viewport.right - origin.x, origin.x - viewport.top);
const /** @type {?} */ previousWidth = this._lastBoundingBoxSize.width;
width = smallestDistanceToViewportEdge * 2;
left = origin.x - smallestDistanceToViewportEdge;
if (width > previousWidth && !this._isInitialRender && !this._growAfterOpen) {
left = origin.x - (previousWidth / 2);
}
}
return { top, left, bottom, right, width, height };
}
/**
* Sets the position and size of the overlay's sizing wrapper. The wrapper is positioned on the
* origin's connection point and stetches to the bounds of the viewport.
*
* @param {?} origin The point on the origin element where the overlay is connected.
* @param {?} position The position preference
* @return {?}
*/
_setBoundingBoxStyles(origin, position) {
const /** @type {?} */ boundingBoxRect = this._calculateBoundingBoxRect(origin, position);
// It's weird if the overlay *grows* while scrolling, so we take the last size into account
// when applying a new size.
if (!this._isInitialRender && !this._growAfterOpen) {
boundingBoxRect.height = Math.min(boundingBoxRect.height, this._lastBoundingBoxSize.height);
boundingBoxRect.width = Math.min(boundingBoxRect.width, this._lastBoundingBoxSize.width);
}
const /** @type {?} */ styles = /** @type {?} */ ({});
if (this._hasExactPosition()) {
styles.top = styles.left = '0';
styles.bottom = styles.right = '';
styles.width = styles.height = '100%';
}
else {
const /** @type {?} */ maxHeight = this._overlayRef.getConfig().maxHeight;
const /** @type {?} */ maxWidth = this._overlayRef.getConfig().maxWidth;
styles.height = coerceCssPixelValue(boundingBoxRect.height);
styles.top = coerceCssPixelValue(boundingBoxRect.top);
styles.bottom = coerceCssPixelValue(boundingBoxRect.bottom);
styles.width = coerceCssPixelValue(boundingBoxRect.width);
styles.left = coerceCssPixelValue(boundingBoxRect.left);
styles.right = coerceCssPixelValue(boundingBoxRect.right);
// Push the pane content towards the proper direction.
if (position.overlayX === 'center') {
styles.alignItems = 'center';
}
else {
styles.alignItems = position.overlayX === 'end' ? 'flex-end' : 'flex-start';
}
if (position.overlayY === 'center') {
styles.justifyContent = 'center';
}
else {
styles.justifyContent = position.overlayY === 'bottom' ? 'flex-end' : 'flex-start';
}
if (maxHeight) {
styles.maxHeight = coerceCssPixelValue(maxHeight);
}
if (maxWidth) {
styles.maxWidth = coerceCssPixelValue(maxWidth);
}
}
this._lastBoundingBoxSize = boundingBoxRect;
extendStyles(/** @type {?} */ ((this._boundingBox)).style, styles);
}
/**
* Resets the styles for the bounding box so that a new positioning can be computed.
* @return {?}
*/
_resetBoundingBoxStyles() {
extendStyles(/** @type {?} */ ((this._boundingBox)).style, /** @type {?} */ ({
top: '0',
left: '0',
right: '0',
bottom: '0',
height: '',
width: '',
alignItems: '',
justifyContent: '',
}));
}
/**
* Resets the styles for the overlay pane so that a new positioning can be computed.
* @return {?}
*/
_resetOverlayElementStyles() {
extendStyles(this._pane.style, /** @type {?} */ ({
top: '',
left: '',
bottom: '',
right: '',
position: '',
}));
}
/**
* Sets positioning styles to the overlay element.
* @param {?} originPoint
* @param {?} position
* @return {?}
*/
_setOverlayElementStyles(originPoint, position) {
const /** @type {?} */ styles = /** @type {?} */ ({});
if (this._hasExactPosition()) {
extendStyles(styles, this._getExactOverlayY(position, originPoint));
extendStyles(styles, this._getExactOverlayX(position, originPoint));
}
else {
styles.position = 'static';
}
// Use a transform to apply the offsets. We do this because the `center` positions rely on
// being in the normal flex flow and setting a `top` / `left` at all will completely throw
// off the position. We also can't use margins, because they won't have an effect in some
// cases where the element doesn't have anything to "push off of". Finally, this works
// better both with flexible and non-flexible positioning.
let /** @type {?} */ transformString = '';
let /** @type {?} */ offsetX = this._getOffset(position, 'x');
let /** @type {?} */ offsetY = this._getOffset(position, 'y');
if (offsetX) {
transformString += `translateX(${offsetX}px) `;
}
if (offsetY) {
transformString += `translateY(${offsetY}px)`;
}
styles.transform = transformString.trim();
// If a maxWidth or maxHeight is specified on the overlay, we remove them. We do this because
// we need these values to both be set to "100%" for the automatic flexible sizing to work.
// The maxHeight and maxWidth are set on the boundingBox in order to enforce the constraint.
if (this._hasFlexibleDimensions && this._overlayRef.getConfig().maxHeight) {
styles.maxHeight = '';
}
if (this._hasFlexibleDimensions && this._overlayRef.getConfig().maxWidth) {
styles.maxWidth = '';
}
extendStyles(this._pane.style, styles);
}
/**
* Gets the exact top/bottom for the overlay when not using flexible sizing or when pushing.
* @param {?} position
* @param {?} originPoint
* @return {?}
*/
_getExactOverlayY(position, originPoint) {
// Reset any existing styles. This is necessary in case the
// preferred position has changed since the last `apply`.
let /** @type {?} */ styles = /** @type {?} */ ({ top: null, bottom: null });
let /** @type {?} */ overlayPoint = this._getOverlayPoint(originPoint, this._overlayRect, position);
if (this._isPushed) {
overlayPoint = this._pushOverlayOnScreen(overlayPoint, this._overlayRect);
}
// @breaking-change 7.0.0 Currently the `_overlayContainer` is optional in order to avoid a
// breaking change. The null check here can be removed once the `_overlayContainer` becomes
// a required parameter.
let /** @type {?} */ virtualKeyboardOffset = this._overlayContainer ?
this._overlayContainer.getContainerElement().getBoundingClientRect().top : 0;
// Normally this would be zero, however when the overlay is attached to an input (e.g. in an
// autocomplete), mobile browsers will shift everything in order to put the input in the middle
// of the screen and to make space for the virtual keyboard. We need to account for this offset,
// otherwise our positioning will be thrown off.
overlayPoint.y -= virtualKeyboardOffset;
// We want to set either `top` or `bottom` based on whether the overlay wants to appear
// above or below the origin and the direction in which the element will expand.
if (position.overlayY === 'bottom') {
// When using `bottom`, we adjust the y position such that it is the distance
// from the bottom of the viewport rather than the top.
const /** @type {?} */ documentHeight = this._document.documentElement.clientHeight;
styles.bottom = `${documentHeight - (overlayPoint.y + this._overlayRect.height)}px`;
}
else {
styles.top = coerceCssPixelValue(overlayPoint.y);
}
return styles;
}
/**
* Gets the exact left/right for the overlay when not using flexible sizing or when pushing.
* @param {?} position
* @param {?} originPoint
* @return {?}
*/
_getExactOverlayX(position, originPoint) {
// Reset any existing styles. This is necessary in case the preferred position has
// changed since the last `apply`.
let /** @type {?} */ styles = /** @type {?} */ ({ left: null, right: null });
let /** @type {?} */ overlayPoint = this._getOverlayPoint(originPoint, this._overlayRect, position);
if (this._isPushed) {
overlayPoint = this._pushOverlayOnScreen(overlayPoint, this._overlayRect);
}
// We want to set either `left` or `right` based on whether the overlay wants to appear "before"
// or "after" the origin, which determines the direction in which the element will expand.
// For the horizontal axis, the meaning of "before" and "after" change based on whether the
// page is in RTL or LTR.
let /** @type {?} */ horizontalStyleProperty;
if (this._isRtl()) {
horizontalStyleProperty = position.overlayX === 'end' ? 'left' : 'right';
}
else {
horizontalStyleProperty = position.overlayX === 'end' ? 'right' : 'left';
}
// When we're setting `right`, we adjust the x position such that it is the distance
// from the right edge of the viewport rather than the left edge.
if (horizontalStyleProperty === 'right') {
const /** @type {?} */ documentWidth = this._document.documentElement.clientWidth;
styles.right = `${documentWidth - (overlayPoint.x + this._overlayRect.width)}px`;
}
else {
styles.left = coerceCssPixelValue(overlayPoint.x);
}
return styles;
}
/**
* Gets the view properties of the trigger and overlay, including whether they are clipped
* or completely outside the view of any of the strategy's scrollables.
* @return {?}
*/
_getScrollVisibility() {
// Note: needs fresh rects since the position could've changed.
const /** @type {?} */ originBounds = this._origin.getBoundingClientRect();
const /** @type {?} */ overlayBounds = this._pane.getBoundingClientRect();
// TODO(jelbourn): instead of needing all of the client rects for these scrolling containers
// every time, we should be able to use the scrollTop of the containers if the size of those
// containers hasn't changed.
const /** @type {?} */ scrollContainerBounds = this.scrollables.map(scrollable => {
return scrollable.getElementRef().nativeElement.getBoundingClientRect();
});
return {
isOriginClipped: isElementClippedByScrolling(originBounds, scrollContainerBounds),
isOriginOutsideView: isElementScrolledOutsideView(originBounds, scrollContainerBounds),
isOverlayClipped: isElementClippedByScrolling(overlayBounds, scrollContainerBounds),
isOverlayOutsideView: isElementScrolledOutsideView(overlayBounds, scrollContainerBounds),
};
}
/**
* Subtracts the amount that an element is overflowing on an axis from it's length.
* @param {?} length
* @param {...?} overflows
* @return {?}
*/
_subtractOverflows(length, ...overflows) {
return overflows.reduce((currentValue, currentOverflow) => {
return currentValue - Math.max(currentOverflow, 0);
}, length);
}
/**
* Narrows the given viewport rect by the current _viewportMargin.
* @return {?}
*/
_getNarrowedViewportRect() {
// We recalculate the viewport rect here ourselves, rather than using the ViewportRuler,
// because we want to use the `clientWidth` and `clientHeight` as the base. The difference
// being that the client properties don't include the scrollbar, as opposed to `innerWidth`
// and `innerHeight` that do. This is necessary, because the overlay container uses
// 100% `width` and `height` which don't include the scrollbar either.
const /** @type {?} */ width = this._document.documentElement.clientWidth;
const /** @type {?} */ height = this._document.documentElement.clientHeight;
const /** @type {?} */ scrollPosition = this._viewportRuler.getViewportScrollPosition();
return {
top: scrollPosition.top + this._viewportMargin,
left: scrollPosition.left + this._viewportMargin,
right: scrollPosition.left + width - this._viewportMargin,
bottom: scrollPosition.top + height - this._viewportMargin,
width: width - (2 * this._viewportMargin),
height: height - (2 * this._viewportMargin),
};
}
/**
* Whether the we're dealing with an RTL context
* @return {?}
*/
_isRtl() {
return this._overlayRef.getDirection() === 'rtl';
}
/**
* Determines whether the overlay uses exact or flexible positioning.
* @return {?}
*/
_hasExactPosition() {
return !this._hasFlexibleDimensions || this._isPushed;
}
/**
* Retrieves the offset of a position along the x or y axis.
* @param {?} position
* @param {?} axis
* @return {?}
*/
_getOffset(position, axis) {
if (axis === 'x') {
// We don't do something like `position['offset' + axis]` in
// order to avoid breking minifiers that rename properties.
return position.offsetX == null ? this._offsetX : position.offsetX;
}
return position.offsetY == null ? this._offsetY : position.offsetY;
}
/**
* Validates that the current position match the expected values.
* @return {?}
*/
_validatePositions() {
if (!this._preferredPositions.length) {
throw Error('FlexibleConnectedPositionStrategy: At least one position is required.');
}
// TODO(crisbeto): remove these once Angular's template type
// checking is advanced enough to catch these cases.
this._preferredPositions.forEach(pair => {
validateHorizontalPosition('originX', pair.originX);
validateVerticalPosition('originY', pair.originY);
validateHorizontalPosition('overlayX', pair.overlayX);
validateVerticalPosition('overlayY', pair.overlayY);
});
}
}
/**
* Shallow-extends a stylesheet object with another stylesheet object.
* @param {?} dest
* @param {?} source
* @return {?}
*/
function extendStyles(dest, source) {
for (let /** @type {?} */ key in source) {
if (source.hasOwnProperty(key)) {
dest[key] = source[key];
}
}
return dest;
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* A strategy for positioning overlays. Using this strategy, an overlay is given an
* implicit position relative to some origin element. The relative position is defined in terms of
* a point on the origin element that is connected to a point on the overlay element. For example,
* a basic dropdown is connecting the bottom-left corner of the origin to the top-left corner
* of the overlay.
* @deprecated Use `FlexibleConnectedPositionStrategy` instead.
* \@breaking-change 7.0.0
*/
class ConnectedPositionStrategy {
/**
* @param {?} originPos
* @param {?} overlayPos
* @param {?} connectedTo
* @param {?} viewportRuler
* @param {?} document
* @param {?=} platform
*/
constructor(originPos, overlayPos, connectedTo, viewportRuler, document,
// @breaking-change 7.0.0 `platform` parameter to be made required.
// @breaking-change 7.0.0 `platform` parameter to be made required.
platform) {
/**
* Ordered list of preferred positions, from most to least desirable.
*/
this._preferredPositions = [];
// Since the `ConnectedPositionStrategy` is deprecated and we don't want to maintain
// the extra logic, we create an instance of the positioning strategy that has some
// defaults that make it behave as the old position strategy and to which we'll
// proxy all of the API calls.
this._positionStrategy =
new FlexibleConnectedPositionStrategy(connectedTo, viewportRuler, document, platform)
.withFlexibleDimensions(false)
.withPush(false)
.withViewportMargin(0);
this.withFallbackPosition(originPos, overlayPos);
}
/**
* Whether the we're dealing with an RTL context
* @return {?}
*/
get _isRtl() {
return this._overlayRef.getDirection() === 'rtl';
}
/**
* Emits an event when the connection point changes.
* @return {?}
*/
get onPositionChange() {
return this._positionStrategy.positionChanges;
}
/**
* Ordered list of preferred positions, from most to least desirable.
* @return {?}
*/
get positions() {
return this._preferredPositions;
}
/**
* Attach this position strategy to an overlay.
* @param {?} overlayRef
* @return {?}
*/
attach(overlayRef) {
this._overlayRef = overlayRef;
this._positionStrategy.attach(overlayRef);
if (this._direction) {
overlayRef.setDirection(this._direction);
this._direction = null;
}
}
/**
* Disposes all resources used by the position strategy.
* @return {?}
*/
dispose() {
this._positionStrategy.dispose();
}
/**
* \@docs-private
* @return {?}
*/
detach() {
this._positionStrategy.detach();
}
/**
* Updates the position of the overlay element, using whichever preferred position relative
* to the origin fits on-screen.
* \@docs-private
* @return {?}
*/
apply() {
this._positionStrategy.apply();
}
/**
* Re-positions the overlay element with the trigger in its last calculated position,
* even if a position higher in the "preferred positions" list would now fit. This
* allows one to re-align the panel without changing the orientation of the panel.
* @return {?}
*/
recalculateLastPosition() {
this._positionStrategy.reapplyLastPosition();
}
/**
* Sets the list of Scrollable containers that host the origin element so that
* on reposition we can evaluate if it or the overlay has been clipped or outside view. Every
* Scrollable must be an ancestor element of the strategy's origin element.
* @param {?} scrollables
* @return {?}
*/
withScrollableContainers(scrollables) {
this._positionStrategy.withScrollableContainers(scrollables);
}
/**
* Adds a new preferred fallback position.
* @param {?} originPos
* @param {?} overlayPos
* @param {?=} offsetX
* @param {?=} offsetY
* @return {?}
*/
withFallbackPosition(originPos, overlayPos, offsetX, offsetY) {
const /** @type {?} */ position = new ConnectionPositionPair(originPos, overlayPos, offsetX, offsetY);
this._preferredPositions.push(position);
this._positionStrategy.withPositions(this._preferredPositions);
return this;
}
/**
* Sets the layout direction so the overlay's position can be adjusted to match.
* @param {?} dir New layout direction.
* @return {?}
*/
withDirection(dir) {
// Since the direction might be declared before the strategy is attached,
// we save the value in a temporary property and we'll transfer it to the
// overlay ref on attachment.
if (this._overlayRef) {
this._overlayRef.setDirection(dir);
}
else {
this._direction = dir;
}
return this;
}
/**
* Sets an offset for the overlay's connection point on the x-axis
* @param {?} offset New offset in the X axis.
* @return {?}
*/
withOffsetX(offset) {
this._positionStrategy.withDefaultOffsetX(offset);
return this;
}
/**
* Sets an offset for the overlay's connection point on the y-axis
* @param {?} offset New offset in the Y axis.
* @return {?}
*/
withOffsetY(offset) {
this._positionStrategy.withDefaultOffsetY(offset);
return this;
}
/**
* Sets whether the overlay's position should be locked in after it is positioned
* initially. When an overlay is locked in, it won't attempt to reposition itself
* when the position is re-applied (e.g. when the user scrolls away).
* @param {?} isLocked Whether the overlay should locked in.
* @return {?}
*/
withLockedPosition(isLocked) {
this._positionStrategy.withLockedPosition(isLocked);
return this;
}
/**
* Overwrites the current set of positions with an array of new ones.
* @param {?} positions Position pairs to be set on the strategy.
* @return {?}
*/
withPositions(positions) {
this._preferredPositions = positions.slice();
this._positionStrategy.withPositions(this._preferredPositions);
return this;
}
/**
* Sets the origin element, relative to which to position the overlay.
* @param {?} origin Reference to the new origin element.
* @return {?}
*/
setOrigin(origin) {
this._positionStrategy.setOrigin(origin);
return this;
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* A strategy for positioning overlays. Using this strategy, an overlay is given an
* explicit position relative to the browser's viewport. We use flexbox, instead of
* transforms, in order to avoid issues with subpixel rendering which can cause the
* element to become blurry.
*/
class GlobalPositionStrategy {
constructor() {
this._cssPosition = 'static';
this._topOffset = '';
this._bottomOffset = '';
this._leftOffset = '';
this._rightOffset = '';
this._alignItems = '';
this._justifyContent = '';
this._width = '';
this._height = '';
}
/**
* @param {?} overlayRef
* @return {?}
*/
attach(overlayRef) {
const /** @type {?} */ config = overlayRef.getConfig();
this._overlayRef = overlayRef;
if (this._width && !config.width) {
overlayRef.updateSize({ width: this._width });
}
if (this._height && !config.height) {
overlayRef.updateSize({ height: this._height });
}
overlayRef.hostElement.classList.add('cdk-global-overlay-wrapper');
}
/**
* Sets the top position of the overlay. Clears any previously set vertical position.
* @param {?=} value New top offset.
* @return {?}
*/
top(value = '') {
this._bottomOffset = '';
this._topOffset = value;
this._alignItems = 'flex-start';
return this;
}
/**
* Sets the left position of the overlay. Clears any previously set horizontal position.
* @param {?=} value New left offset.
* @return {?}
*/
left(value = '') {
this._rightOffset = '';
this._leftOffset = value;
this._justifyContent = 'flex-start';
return this;
}
/**
* Sets the bottom position of the overlay. Clears any previously set vertical position.
* @param {?=} value New bottom offset.
* @return {?}
*/
bottom(value = '') {
this._topOffset = '';
this._bottomOffset = value;
this._alignItems = 'flex-end';
return this;
}
/**
* Sets the right position of the overlay. Clears any previously set horizontal position.
* @param {?=} value New right offset.
* @return {?}
*/
right(value = '') {
this._leftOffset = '';
this._rightOffset = value;
this._justifyContent = 'flex-end';
return this;
}
/**
* Sets the overlay width and clears any previously set width.
* @deprecated Pass the `width` through the `OverlayConfig`.
* \@breaking-change 7.0.0
* @param {?=} value New width for the overlay
* @return {?}
*/
width(value = '') {
if (this._overlayRef) {
this._overlayRef.updateSize({ width: value });
}
else {
this._width = value;
}
return this;
}
/**
* Sets the overlay height and clears any previously set height.
* @deprecated Pass the `height` through the `OverlayConfig`.
* \@breaking-change 7.0.0
* @param {?=} value New height for the overlay
* @return {?}
*/
height(value = '') {
if (this._overlayRef) {
this._overlayRef.updateSize({ height: value });
}
else {
this._height = value;
}
return this;
}
/**
* Centers the overlay horizontally with an optional offset.
* Clears any previously set horizontal position.
*
* @param {?=} offset Overlay offset from the horizontal center.
* @return {?}
*/
centerHorizontally(offset = '') {
this.left(offset);
this._justifyContent = 'center';
return this;
}
/**
* Centers the overlay vertically with an optional offset.
* Clears any previously set vertical position.
*
* @param {?=} offset Overlay offset from the vertical center.
* @return {?}
*/
centerVertically(offset = '') {
this.top(offset);
this._alignItems = 'center';
return this;
}
/**
* Apply the position to the element.
* \@docs-private
* @return {?}
*/
apply() {
// Since the overlay ref applies the strategy asynchronously, it could
// have been disposed before it ends up being applied. If that is the
// case, we shouldn't do anything.
if (!this._overlayRef.hasAttached()) {
return;
}
const /** @type {?} */ styles = this._overlayRef.overlayElement.style;
const /** @type {?} */ parentStyles = this._overlayRef.hostElement.style;
const /** @type {?} */ config = this._overlayRef.getConfig();
styles.position = this._cssPosition;
styles.marginLeft = config.width === '100%' ? '0' : this._leftOffset;
styles.marginTop = config.height === '100%' ? '0' : this._topOffset;
styles.marginBottom = this._bottomOffset;
styles.marginRight = this._rightOffset;
if (config.width === '100%') {
parentStyles.justifyContent = 'flex-start';
}
else if (this._justifyContent === 'center') {
parentStyles.justifyContent = 'center';
}
else if (this._overlayRef.getConfig().direction === 'rtl') {
// In RTL the browser will invert `flex-start` and `flex-end` automatically, but we
// don't want that because our positioning is explicitly `left` and `right`, hence
// why we do another inversion to ensure that the overlay stays in the same position.
// TODO: reconsider this if we add `start` and `end` methods.
if (this._justifyContent === 'flex-start') {
parentStyles.justifyContent = 'flex-end';
}
else if (this._justifyContent === 'flex-end') {
parentStyles.justifyContent = 'flex-start';
}
}
else {
parentStyles.justifyContent = this._justifyContent;
}
parentStyles.alignItems = config.height === '100%' ? 'flex-start' : this._alignItems;
}
/**
* Noop implemented as a part of the PositionStrategy interface.
* \@docs-private
* @return {?}
*/
dispose() { }
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Builder for overlay position strategy.
*/
class OverlayPositionBuilder {
/**
* @param {?} _viewportRuler
* @param {?} _document
* @param {?=} _platform
* @param {?=} _overlayContainer
*/
constructor(_viewportRuler, _document,
// @breaking-change 7.0.0 `_platform` and `_overlayContainer` parameters to be made required.
_platform, _overlayContainer) {
this._viewportRuler = _viewportRuler;
this._document = _document;
this._platform = _platform;
this._overlayContainer = _overlayContainer;
}
/**
* Creates a global position strategy.
* @return {?}
*/
global() {
return new GlobalPositionStrategy();
}
/**
* Creates a relative position strategy.
* @deprecated Use `flexibleConnectedTo` instead.
* \@breaking-change 7.0.0
* @param {?} elementRef
* @param {?} originPos
* @param {?} overlayPos
* @return {?}
*/
connectedTo(elementRef, originPos, overlayPos) {
return new ConnectedPositionStrategy(originPos, overlayPos, elementRef, this._viewportRuler, this._document);
}
/**
* Creates a flexible position strategy.
* @param {?} elementRef
* @return {?}
*/
flexibleConnectedTo(elementRef) {
return new FlexibleConnectedPositionStrategy(elementRef, this._viewportRuler, this._document, this._platform, this._overlayContainer);
}
}
OverlayPositionBuilder.decorators = [
{ type: Injectable, args: [{ providedIn: 'root' },] },
];
/** @nocollapse */
OverlayPositionBuilder.ctorParameters = () => [
{ type: ViewportRuler, },
{ type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] },] },
{ type: Platform, decorators: [{ type: Optional },] },
{ type: OverlayContainer, decorators: [{ type: Optional },] },
];
/** @nocollapse */ OverlayPositionBuilder.ngInjectableDef = defineInjectable({ factory: function OverlayPositionBuilder_Factory() { return new OverlayPositionBuilder(inject(ViewportRuler), inject(DOCUMENT), inject(Platform, 8), inject(OverlayContainer, 8)); }, token: OverlayPositionBuilder, providedIn: "root" });
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Next overlay unique ID.
*/
let /** @type {?} */ nextUniqueId = 0;
/**
* Service to create Overlays. Overlays are dynamically added pieces of floating UI, meant to be
* used as a low-level building block for other components. Dialogs, tooltips, menus,
* selects, etc. can all be built using overlays. The service should primarily be used by authors
* of re-usable components rather than developers building end-user applications.
*
* An overlay *is* a PortalOutlet, so any kind of Portal can be loaded into one.
*/
class Overlay {
/**
* @param {?} scrollStrategies
* @param {?} _overlayContainer
* @param {?} _componentFactoryResolver
* @param {?} _positionBuilder
* @param {?} _keyboardDispatcher
* @param {?} _injector
* @param {?} _ngZone
* @param {?} _document
* @param {?} _directionality
*/
constructor(scrollStrategies, _overlayContainer, _componentFactoryResolver, _positionBuilder, _keyboardDispatcher, _injector, _ngZone, _document, _directionality) {
this.scrollStrategies = scrollStrategies;
this._overlayContainer = _overlayContainer;
this._componentFactoryResolver = _componentFactoryResolver;
this._positionBuilder = _positionBuilder;
this._keyboardDispatcher = _keyboardDispatcher;
this._injector = _injector;
this._ngZone = _ngZone;
this._document = _document;
this._directionality = _directionality;
}
/**
* Creates an overlay.
* @param {?=} config Configuration applied to the overlay.
* @return {?} Reference to the created overlay.
*/
create(config) {
const /** @type {?} */ host = this._createHostElement();
const /** @type {?} */ pane = this._createPaneElement(host);
const /** @type {?} */ portalOutlet = this._createPortalOutlet(pane);
const /** @type {?} */ overlayConfig = new OverlayConfig(config);
overlayConfig.direction = overlayConfig.direction || this._directionality.value;
return new OverlayRef(portalOutlet, host, pane, overlayConfig, this._ngZone, this._keyboardDispatcher, this._document);
}
/**
* Gets a position builder that can be used, via fluent API,
* to construct and configure a position strategy.
* @return {?} An overlay position builder.
*/
position() {
return this._positionBuilder;
}
/**
* Creates the DOM element for an overlay and appends it to the overlay container.
* @param {?} host
* @return {?} Newly-created pane element
*/
_createPaneElement(host) {
const /** @type {?} */ pane = this._document.createElement('div');
pane.id = `cdk-overlay-${nextUniqueId++}`;
pane.classList.add('cdk-overlay-pane');
host.appendChild(pane);
return pane;
}
/**
* Creates the host element that wraps around an overlay
* and can be used for advanced positioning.
* @return {?} Newly-create host element.
*/
_createHostElement() {
const /** @type {?} */ host = this._document.createElement('div');
this._overlayContainer.getContainerElement().appendChild(host);
return host;
}
/**
* Create a DomPortalOutlet into which the overlay content can be loaded.
* @param {?} pane The DOM element to turn into a portal outlet.
* @return {?} A portal outlet for the given DOM element.
*/
_createPortalOutlet(pane) {
// We have to resolve the ApplicationRef later in order to allow people
// to use overlay-based providers during app initialization.
if (!this._appRef) {
this._appRef = this._injector.get(ApplicationRef);
}
return new DomPortalOutlet(pane, this._componentFactoryResolver, this._appRef, this._injector);
}
}
Overlay.decorators = [
{ type: Injectable },
];
/** @nocollapse */
Overlay.ctorParameters = () => [
{ type: ScrollStrategyOptions, },
{ type: OverlayContainer, },
{ type: ComponentFactoryResolver, },
{ type: OverlayPositionBuilder, },
{ type: OverlayKeyboardDispatcher, },
{ type: Injector, },
{ type: NgZone, },
{ type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] },] },
{ type: Directionality, },
];
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Default set of positions for the overlay. Follows the behavior of a dropdown.
*/
const /** @type {?} */ defaultPositionList = [
{
originX: 'start',
originY: 'bottom',
overlayX: 'start',
overlayY: 'top'
},
{
originX: 'start',
originY: 'top',
overlayX: 'start',
overlayY: 'bottom'
},
{
originX: 'end',
originY: 'top',
overlayX: 'end',
overlayY: 'bottom'
},
{
originX: 'end',
originY: 'bottom',
overlayX: 'end',
overlayY: 'top'
}
];
/**
* Injection token that determines the scroll handling while the connected overlay is open.
*/
const /** @type {?} */ CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY = new InjectionToken('cdk-connected-overlay-scroll-strategy');
/**
* Directive applied to an element to make it usable as an origin for an Overlay using a
* ConnectedPositionStrategy.
*/
class CdkOverlayOrigin {
/**
* @param {?} elementRef
*/
constructor(elementRef) {
this.elementRef = elementRef;
}
}
CdkOverlayOrigin.decorators = [
{ type: Directive, args: [{
selector: '[cdk-overlay-origin], [overlay-origin], [cdkOverlayOrigin]',
exportAs: 'cdkOverlayOrigin',
},] },
];
/** @nocollapse */
CdkOverlayOrigin.ctorParameters = () => [
{ type: ElementRef, },
];
/**
* Directive to facilitate declarative creation of an
* Overlay using a FlexibleConnectedPositionStrategy.
*/
class CdkConnectedOverlay {
/**
* @param {?} _overlay
* @param {?} templateRef
* @param {?} viewContainerRef
* @param {?} _scrollStrategy
* @param {?} _dir
*/
constructor(_overlay, templateRef, viewContainerRef, _scrollStrategy, _dir) {
this._overlay = _overlay;
this._scrollStrategy = _scrollStrategy;
this._dir = _dir;
this._hasBackdrop = false;
this._lockPosition = false;
this._growAfterOpen = false;
this._flexibleDimensions = false;
this._push = false;
this._backdropSubscription = Subscription.EMPTY;
/**
* Margin between the overlay and the viewport edges.
*/
this.viewportMargin = 0;
/**
* Strategy to be used when handling scroll events while the overlay is open.
*/
this.scrollStrategy = this._scrollStrategy();
/**
* Whether the overlay is open.
*/
this.open = false;
/**
* Event emitted when the backdrop is clicked.
*/
this.backdropClick = new EventEmitter();
/**
* Event emitted when the position has changed.
*/
this.positionChange = new EventEmitter();
/**
* Event emitted when the overlay has been attached.
*/
this.attach = new EventEmitter();
/**
* Event emitted when the overlay has been detached.
*/
this.detach = new EventEmitter();
/**
* Emits when there are keyboard events that are targeted at the overlay.
*/
this.overlayKeydown = new EventEmitter();
this._templatePortal = new TemplatePortal(templateRef, viewContainerRef);
}
/**
* The offset in pixels for the overlay connection point on the x-axis
* @return {?}
*/
get offsetX() { return this._offsetX; }
/**
* @param {?} offsetX
* @return {?}
*/
set offsetX(offsetX) {
this._offsetX = offsetX;
if (this._position) {
this._setPositions(this._position);
}
}
/**
* The offset in pixels for the overlay connection point on the y-axis
* @return {?}
*/
get offsetY() { return this._offsetY; }
/**
* @param {?} offsetY
* @return {?}
*/
set offsetY(offsetY) {
this._offsetY = offsetY;
if (this._position) {
this._setPositions(this._position);
}
}
/**
* Whether or not the overlay should attach a backdrop.
* @return {?}
*/
get hasBackdrop() { return this._hasBackdrop; }
/**
* @param {?} value
* @return {?}
*/
set hasBackdrop(value) { this._hasBackdrop = coerceBooleanProperty(value); }
/**
* Whether or not the overlay should be locked when scrolling.
* @return {?}
*/
get lockPosition() { return this._lockPosition; }
/**
* @param {?} value
* @return {?}
*/
set lockPosition(value) { this._lockPosition = coerceBooleanProperty(value); }
/**
* Whether the overlay's width and height can be constrained to fit within the viewport.
* @return {?}
*/
get flexibleDiemsions() { return this._flexibleDimensions; }
/**
* @param {?} value
* @return {?}
*/
set flexibleDiemsions(value) { this._flexibleDimensions = coerceBooleanProperty(value); }
/**
* Whether the overlay can grow after the initial open when flexible positioning is turned on.
* @return {?}
*/
get growAfterOpen() { return this._growAfterOpen; }
/**
* @param {?} value
* @return {?}
*/
set growAfterOpen(value) { this._growAfterOpen = coerceBooleanProperty(value); }
/**
* Whether the overlay can be pushed on-screen if none of the provided positions fit.
* @return {?}
*/
get push() { return this._push; }
/**
* @param {?} value
* @return {?}
*/
set push(value) { this._push = coerceBooleanProperty(value); }
/**
* The associated overlay reference.
* @return {?}
*/
get overlayRef() {
return this._overlayRef;
}
/**
* The element's layout direction.
* @return {?}
*/
get dir() {
return this._dir ? this._dir.value : 'ltr';
}
/**
* @return {?}
*/
ngOnDestroy() {
this._destroyOverlay();
}
/**
* @param {?} changes
* @return {?}
*/
ngOnChanges(changes) {
if (this._position) {
if (changes['positions']) {
this._position.withPositions(this.positions);
}
if (changes['lockPosition']) {
this._position.withLockedPosition(this.lockPosition);
}
if (changes['origin']) {
this._position.setOrigin(this.origin.elementRef);
if (this.open) {
this._position.apply();
}
}
}
if (changes['open']) {
this.open ? this._attachOverlay() : this._detachOverlay();
}
}
/**
* Creates an overlay
* @return {?}
*/
_createOverlay() {
if (!this.positions || !this.positions.length) {
this.positions = defaultPositionList;
}
this._overlayRef = this._overlay.create(this._buildConfig());
}
/**
* Builds the overlay config based on the directive's inputs
* @return {?}
*/
_buildConfig() {
const /** @type {?} */ positionStrategy = this._position = this._createPositionStrategy();
const /** @type {?} */ overlayConfig = new OverlayConfig({
direction: this._dir,
positionStrategy,
scrollStrategy: this.scrollStrategy,
hasBackdrop: this.hasBackdrop
});
if (this.width || this.width === 0) {
overlayConfig.width = this.width;
}
if (this.height || this.height === 0) {
overlayConfig.height = this.height;
}
if (this.minWidth || this.minWidth === 0) {
overlayConfig.minWidth = this.minWidth;
}
if (this.minHeight || this.minHeight === 0) {
overlayConfig.minHeight = this.minHeight;
}
if (this.backdropClass) {
overlayConfig.backdropClass = this.backdropClass;
}
return overlayConfig;
}
/**
* Returns the position strategy of the overlay to be set on the overlay config
* @return {?}
*/
_createPositionStrategy() {
const /** @type {?} */ strategy = this._overlay.position()
.flexibleConnectedTo(this.origin.elementRef)
.withFlexibleDimensions(this.flexibleDiemsions)
.withPush(this.push)
.withGrowAfterOpen(this.growAfterOpen)
.withViewportMargin(this.viewportMargin)
.withLockedPosition(this.lockPosition);
this._setPositions(strategy);
strategy.positionChanges.subscribe(p => this.positionChange.emit(p));
return strategy;
}
/**
* Sets the primary and fallback positions of a positions strategy,
* based on the current directive inputs.
* @param {?} positionStrategy
* @return {?}
*/
_setPositions(positionStrategy) {
const /** @type {?} */ positions = this.positions.map(pos => ({
originX: pos.originX,
originY: pos.originY,
overlayX: pos.overlayX,
overlayY: pos.overlayY,
offsetX: pos.offsetX || this.offsetX,
offsetY: pos.offsetY || this.offsetY
}));
positionStrategy.withPositions(positions);
}
/**
* Attaches the overlay and subscribes to backdrop clicks if backdrop exists
* @return {?}
*/
_attachOverlay() {
if (!this._overlayRef) {
this._createOverlay(); /** @type {?} */
((this._overlayRef)).keydownEvents().subscribe((event) => {
this.overlayKeydown.next(event);
if (event.keyCode === ESCAPE) {
this._detachOverlay();
}
});
}
else {
// Update the overlay size, in case the directive's inputs have changed
this._overlayRef.updateSize({
width: this.width,
minWidth: this.minWidth,
height: this.height,
minHeight: this.minHeight,
});
}
if (!this._overlayRef.hasAttached()) {
this._overlayRef.attach(this._templatePortal);
this.attach.emit();
}
if (this.hasBackdrop) {
this._backdropSubscription = this._overlayRef.backdropClick().subscribe(event => {
this.backdropClick.emit(event);
});
}
}
/**
* Detaches the overlay and unsubscribes to backdrop clicks if backdrop exists
* @return {?}
*/
_detachOverlay() {
if (this._overlayRef) {
this._overlayRef.detach();
this.detach.emit();
}
this._backdropSubscription.unsubscribe();
}
/**
* Destroys the overlay created by this directive.
* @return {?}
*/
_destroyOverlay() {
if (this._overlayRef) {
this._overlayRef.dispose();
}
this._backdropSubscription.unsubscribe();
}
}
CdkConnectedOverlay.decorators = [
{ type: Directive, args: [{
selector: '[cdk-connected-overlay], [connected-overlay], [cdkConnectedOverlay]',
exportAs: 'cdkConnectedOverlay'
},] },
];
/** @nocollapse */
CdkConnectedOverlay.ctorParameters = () => [
{ type: Overlay, },
{ type: TemplateRef, },
{ type: ViewContainerRef, },
{ type: undefined, decorators: [{ type: Inject, args: [CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY,] },] },
{ type: Directionality, decorators: [{ type: Optional },] },
];
CdkConnectedOverlay.propDecorators = {
"origin": [{ type: Input, args: ['cdkConnectedOverlayOrigin',] },],
"positions": [{ type: Input, args: ['cdkConnectedOverlayPositions',] },],
"offsetX": [{ type: Input, args: ['cdkConnectedOverlayOffsetX',] },],
"offsetY": [{ type: Input, args: ['cdkConnectedOverlayOffsetY',] },],
"width": [{ type: Input, args: ['cdkConnectedOverlayWidth',] },],
"height": [{ type: Input, args: ['cdkConnectedOverlayHeight',] },],
"minWidth": [{ type: Input, args: ['cdkConnectedOverlayMinWidth',] },],
"minHeight": [{ type: Input, args: ['cdkConnectedOverlayMinHeight',] },],
"backdropClass": [{ type: Input, args: ['cdkConnectedOverlayBackdropClass',] },],
"viewportMargin": [{ type: Input, args: ['cdkConnectedOverlayViewportMargin',] },],
"scrollStrategy": [{ type: Input, args: ['cdkConnectedOverlayScrollStrategy',] },],
"open": [{ type: Input, args: ['cdkConnectedOverlayOpen',] },],
"hasBackdrop": [{ type: Input, args: ['cdkConnectedOverlayHasBackdrop',] },],
"lockPosition": [{ type: Input, args: ['cdkConnectedOverlayLockPosition',] },],
"flexibleDiemsions": [{ type: Input, args: ['cdkConnectedOverlayFlexibleDimensions',] },],
"growAfterOpen": [{ type: Input, args: ['cdkConnectedOverlayGrowAfterOpen',] },],
"push": [{ type: Input, args: ['cdkConnectedOverlayPush',] },],
"backdropClick": [{ type: Output },],
"positionChange": [{ type: Output },],
"attach": [{ type: Output },],
"detach": [{ type: Output },],
"overlayKeydown": [{ type: Output },],
};
/**
* \@docs-private
* @param {?} overlay
* @return {?}
*/
function CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY_PROVIDER_FACTORY(overlay) {
return () => overlay.scrollStrategies.reposition();
}
/**
* \@docs-private
*/
const /** @type {?} */ CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY_PROVIDER = {
provide: CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY,
deps: [Overlay],
useFactory: CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY_PROVIDER_FACTORY,
};
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
class OverlayModule {
}
OverlayModule.decorators = [
{ type: NgModule, args: [{
imports: [BidiModule, PortalModule, ScrollDispatchModule],
exports: [CdkConnectedOverlay, CdkOverlayOrigin, ScrollDispatchModule],
declarations: [CdkConnectedOverlay, CdkOverlayOrigin],
providers: [
Overlay,
CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY_PROVIDER,
],
},] },
];
/**
* @deprecated Use `OverlayModule` instead.
* \@breaking-change 7.0.0
*/
const /** @type {?} */ OVERLAY_PROVIDERS = [
Overlay,
OverlayPositionBuilder,
OVERLAY_KEYBOARD_DISPATCHER_PROVIDER,
VIEWPORT_RULER_PROVIDER,
OVERLAY_CONTAINER_PROVIDER,
CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY_PROVIDER,
];
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Alternative to OverlayContainer that supports correct displaying of overlay elements in
* Fullscreen mode
* https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullScreen
*
* Should be provided in the root component.
*/
class FullscreenOverlayContainer extends OverlayContainer {
/**
* @param {?} _document
*/
constructor(_document) {
super(_document);
}
/**
* @return {?}
*/
ngOnDestroy() {
super.ngOnDestroy();
if (this._fullScreenEventName && this._fullScreenListener) {
this._document.removeEventListener(this._fullScreenEventName, this._fullScreenListener);
}
}
/**
* @return {?}
*/
_createContainer() {
super._createContainer();
this._adjustParentForFullscreenChange();
this._addFullscreenChangeListener(() => this._adjustParentForFullscreenChange());
}
/**
* @return {?}
*/
_adjustParentForFullscreenChange() {
if (!this._containerElement) {
return;
}
const /** @type {?} */ fullscreenElement = this.getFullscreenElement();
const /** @type {?} */ parent = fullscreenElement || this._document.body;
parent.appendChild(this._containerElement);
}
/**
* @param {?} fn
* @return {?}
*/
_addFullscreenChangeListener(fn) {
const /** @type {?} */ eventName = this._getEventName();
if (eventName) {
if (this._fullScreenListener) {
this._document.removeEventListener(eventName, this._fullScreenListener);
}
this._document.addEventListener(eventName, fn);
this._fullScreenListener = fn;
}
}
/**
* @return {?}
*/
_getEventName() {
if (!this._fullScreenEventName) {
if (this._document.fullscreenEnabled) {
this._fullScreenEventName = 'fullscreenchange';
}
else if (this._document.webkitFullscreenEnabled) {
this._fullScreenEventName = 'webkitfullscreenchange';
}
else if ((/** @type {?} */ (this._document)).mozFullScreenEnabled) {
this._fullScreenEventName = 'mozfullscreenchange';
}
else if ((/** @type {?} */ (this._document)).msFullscreenEnabled) {
this._fullScreenEventName = 'MSFullscreenChange';
}
}
return this._fullScreenEventName;
}
/**
* When the page is put into fullscreen mode, a specific element is specified.
* Only that element and its children are visible when in fullscreen mode.
* @return {?}
*/
getFullscreenElement() {
return this._document.fullscreenElement ||
this._document.webkitFullscreenElement ||
(/** @type {?} */ (this._document)).mozFullScreenElement ||
(/** @type {?} */ (this._document)).msFullscreenElement ||
null;
}
}
FullscreenOverlayContainer.decorators = [
{ type: Injectable },
];
/** @nocollapse */
FullscreenOverlayContainer.ctorParameters = () => [
{ type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] },] },
];
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
export { Overlay, OverlayContainer, CdkOverlayOrigin, CdkConnectedOverlay, FullscreenOverlayContainer, OverlayRef, OverlayKeyboardDispatcher, OverlayPositionBuilder, GlobalPositionStrategy, ConnectedPositionStrategy, FlexibleConnectedPositionStrategy, OverlayConfig, ConnectionPositionPair, ScrollingVisibility, ConnectedOverlayPositionChange, validateVerticalPosition, validateHorizontalPosition, ScrollStrategyOptions, RepositionScrollStrategy, CloseScrollStrategy, NoopScrollStrategy, BlockScrollStrategy, OverlayModule, OVERLAY_PROVIDERS, OVERLAY_KEYBOARD_DISPATCHER_PROVIDER as ɵg, OVERLAY_KEYBOARD_DISPATCHER_PROVIDER_FACTORY as ɵf, OVERLAY_CONTAINER_PROVIDER as ɵb, OVERLAY_CONTAINER_PROVIDER_FACTORY as ɵa, CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY as ɵc, CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY_PROVIDER as ɵe, CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY_PROVIDER_FACTORY as ɵd };
//# sourceMappingURL=overlay.js.map
|
friendsofagape/mt2414ui
|
node_modules/@angular/cdk/esm2015/overlay.js
|
JavaScript
|
mit
| 124,054
|
var ThorElement = require('./thorElement');
var ThorController = function(){
ThorElement.call(this);
this.type = ThorElement.TYPES.CONTROLLER;
}
module.exports = ThorController;
|
Zombitch/thor
|
api/modules/thorController.js
|
JavaScript
|
mit
| 184
|
// Copyright (c) Aurora Studio. All rights reserved.
//
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Text;
using System.Threading.Tasks;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Security.Cryptography.DataProtection;
using Windows.Storage.Streams;
namespace Aurora.Shared.Helpers.Crypto
{
public class CryptoHelper
{
public static string ToBase64(string str)
{
var buffer = CryptographicBuffer.ConvertStringToBinary(str, BinaryStringEncoding.Utf8);
return CryptographicBuffer.EncodeToBase64String(buffer);
}
public static string FromBase64(string str)
{
var buffer = CryptographicBuffer.DecodeFromBase64String(str);
return CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffer);
}
/// <summary>
/// 对指定 utf-8 字符串执行 MD5 校验
/// </summary>
/// <param name="str">注意编码格式为 utf-8</param>
/// <returns></returns>
public static string ComputeMD5(string str)
{
var alg = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
IBuffer buff = CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes(str));
var hashed = alg.HashData(buff);
var res = CryptographicBuffer.EncodeToHexString(hashed);
return res;
}
/// <summary>
/// 对字符串依据指定的算法和密钥进行加密,如果使用 CBC 算法,还需要初始化向量
/// </summary>
/// <param name="content">源字符串</param>
/// <param name="strAlgName">加密算法</param>
/// <param name="encoding">字符串编码方式</param>
/// <param name="key">密钥</param>
/// <param name="iniVec">CBC 初始化向量</param>
/// <returns></returns>
public static IBuffer CipherEncryption(string content, string strAlgName,
BinaryStringEncoding encoding, CryptographicKey key, IBuffer iniVec = null)
{
// Create a buffer that contains the encoded message to be encrypted.
IBuffer buffContent = CryptographicBuffer.ConvertStringToBinary(content, encoding);
// Open a symmetric algorithm provider for the specified algorithm.
SymmetricKeyAlgorithmProvider objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAlgName);
// Determine whether the message length is a multiple of the block length.
// This is not necessary for PKCS #7 algorithms which automatically pad the
// message to an appropriate length.
if (!strAlgName.Contains("PKCS7"))
{
if ((buffContent.Length % objAlg.BlockLength) != 0)
{
throw new Exception("Message buffer length must be multiple of block length.");
}
}
if (strAlgName.Contains("CBC") && iniVec == null)
{
throw new ArgumentException("Using CBC Encryption, initial vector must have value");
}
// Encrypt the data and return.
IBuffer buffEncrypt = CryptographicEngine.Encrypt(key, buffContent, iniVec);
return buffEncrypt;
}
/// <summary>
/// 根据加密算法和长度生成一个对称密钥,现在尚不能导出密钥
/// </summary>
/// <param name="strAlgName">算法</param>
/// <param name="keyLength">密钥长度</param>
/// <returns></returns>
public static CryptographicKey GenerateKey(string strAlgName, uint keyLength)
{
SymmetricKeyAlgorithmProvider objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAlgName);
IBuffer keyMaterial = CryptographicBuffer.GenerateRandom(keyLength);
return objAlg.CreateSymmetricKey(keyMaterial);
}
/// <summary>
/// 生成 CBC 算法初始化向量
/// </summary>
/// <param name="strAlgName"></param>
/// <returns></returns>
public static IBuffer GenerateCBCVector(string strAlgName)
{
if (strAlgName.Contains("CBC"))
{
SymmetricKeyAlgorithmProvider objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAlgName);
return CryptographicBuffer.GenerateRandom(objAlg.BlockLength);
}
else return null;
}
/// <summary>
/// 对一段 Buffer 根据指定的算法和密钥解密,如果使用 CBC 算法,还需要初始化向量
/// </summary>
/// <param name="strAlgName">算法</param>
/// <param name="buffEncrypt">加密缓冲区</param>
/// <param name="encoding">编码方式</param>
/// <param name="key">密钥</param>
/// /// <param name="iniVec">初始化向量</param>
/// <returns></returns>
public static string CipherDecryption(string strAlgName, IBuffer buffEncrypt,
BinaryStringEncoding encoding, CryptographicKey key, IBuffer iniVec = null)
{
// Declare a buffer to contain the decrypted data.
IBuffer buffDecrypted;
// Open an symmetric algorithm provider for the specified algorithm.
SymmetricKeyAlgorithmProvider objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAlgName);
// The input key must be securely shared between the sender of the encrypted message
// and the recipient. The initialization vector must also be shared but does not
// need to be shared in a secure manner. If the sender encodes a message string
// to a buffer, the binary encoding method must also be shared with the recipient.
buffDecrypted = CryptographicEngine.Decrypt(key, buffEncrypt, iniVec);
// Convert the decrypted buffer to a string (for display). If the sender created the
// original message buffer from a string, the sender must tell the recipient what
// BinaryStringEncoding value was used. Here, BinaryStringEncoding.Utf8 is used to
// convert the message to a buffer before encryption and to convert the decrypted
// buffer back to the original plaintext.
return ToString(encoding, buffDecrypted);
}
public static string ToString(BinaryStringEncoding encoding, IBuffer buff)
{
return CryptographicBuffer.ConvertBinaryToString(encoding, buff);
}
public static async Task<IBuffer> ProtectAsync(string strMsg, string strDescriptor, BinaryStringEncoding encoding)
{
// Create a DataProtectionProvider object for the specified descriptor.
DataProtectionProvider Provider = new DataProtectionProvider(strDescriptor);
// Encode the plaintext input message to a buffer.
encoding = BinaryStringEncoding.Utf8;
IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, encoding);
// Encrypt the message.
IBuffer buffProtected = await Provider.ProtectAsync(buffMsg);
// Execution of the SampleProtectAsync function resumes here
// after the awaited task (Provider.ProtectAsync) completes.
return buffProtected;
}
public static async Task<string> UnprotectAsync(IBuffer buffProtected, BinaryStringEncoding encoding)
{
// Create a DataProtectionProvider object.
DataProtectionProvider Provider = new DataProtectionProvider();
// Decrypt the protected message specified on input.
IBuffer buffUnprotected = await Provider.UnprotectAsync(buffProtected);
// Execution of the SampleUnprotectData method resumes here
// after the awaited task (Provider.UnprotectAsync) completes
// Convert the unprotected message from an IBuffer object to a string.
string strClearText = CryptographicBuffer.ConvertBinaryToString(encoding, buffUnprotected);
// Return the plaintext string.
return strClearText;
}
}
}
|
pkzxs/Aurora.Music
|
Source/Aurora.Shared/Helpers/Crypto/CryptoHelper.cs
|
C#
|
mit
| 8,349
|
package generated.zcsclient.admin;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for cancelRuleInfo complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="cancelRuleInfo">
* <complexContent>
* <extension base="{urn:zimbraAdmin}recurIdInfo">
* <sequence>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "cancelRuleInfo")
public class testCancelRuleInfo
extends testRecurIdInfo
{
}
|
nico01f/z-pec
|
ZimbraSoap/src/wsdl-test/generated/zcsclient/admin/testCancelRuleInfo.java
|
Java
|
mit
| 748
|
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="keywords" content=" ">
<title>Update Predefined Content | LivePerson Technical Documentation</title>
<link rel="stylesheet" href="css/syntax.css">
<link rel="stylesheet" type="text/css" href="css/font-awesome-4.7.0/css/font-awesome.min.css">
<!--<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">-->
<link rel="stylesheet" href="css/modern-business.css">
<link rel="stylesheet" href="css/lavish-bootstrap.css">
<link rel="stylesheet" href="css/customstyles.css">
<link rel="stylesheet" href="css/theme-blue.css">
<!-- <script src="assets/js/jsoneditor.js"></script> -->
<script src="assets/js/jquery-3.1.0.min.js"></script>
<!-- <link rel='stylesheet' id='theme_stylesheet' href='//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css'> -->
<!-- <link rel='stylesheet' id='theme_stylesheet' href='//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css'>
-->
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> -->
<script src="assets/js/jquery.cookie-1.4.1.min.js"></script>
<script src="js/jquery.navgoco.min.js"></script>
<script src="assets/js/bootstrap-3.3.4.min.js"></script>
<script src="assets/js/anchor-2.0.0.min.js"></script>
<script src="js/toc.js"></script>
<script src="js/customscripts.js"></script>
<link rel="shortcut icon" href="images/favicon.ico">
<!-- 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/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" title="" href="http://liveperson.comfeed.xml">
<script>
$(document).ready(function() {
// Initialize navgoco with default options
$("#mysidebar").navgoco({
caretHtml: '',
accordion: true,
openClass: 'active', // open
save: false, // leave false or nav highlighting doesn't work right
cookie: {
name: 'navgoco',
expires: false,
path: '/'
},
slide: {
duration: 400,
easing: 'swing'
}
});
$("#collapseAll").click(function(e) {
e.preventDefault();
$("#mysidebar").navgoco('toggle', false);
});
$("#expandAll").click(function(e) {
e.preventDefault();
$("#mysidebar").navgoco('toggle', true);
});
});
</script>
<script>
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
</script>
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container topnavlinks">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<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="fa fa-home fa-lg navbar-brand" href="index.html"> <span class="projectTitle"> LivePerson Technical Documentation</span></a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<!-- entries without drop-downs appear here -->
<!-- entries with drop-downs appear here -->
<!-- conditional logic to control which topnav appears for the audience defined in the configuration file.-->
<li><a class="email" title="Submit feedback" href="https://github.com/LivePersonInc/dev-hub/issues" ><i class="fa fa-github"></i> Issues</a><li>
<!--comment out this block if you want to hide search-->
<li>
<!--start search-->
<div id="search-demo-container">
<input type="text" id="search-input" placeholder="search...">
<ul id="results-container"></ul>
</div>
<script src="js/jekyll-search.js" type="text/javascript"></script>
<script type="text/javascript">
SimpleJekyllSearch.init({
searchInput: document.getElementById('search-input'),
resultsContainer: document.getElementById('results-container'),
dataSource: 'search.json',
searchResultTemplate: '<li><a href="{url}" title="Update Predefined Content">{title}</a></li>',
noResultsText: 'No results found.',
limit: 10,
fuzzy: true,
})
</script>
<!--end search-->
</li>
</ul>
</div>
</div>
<!-- /.container -->
</nav>
<!-- Page Content -->
<div class="container">
<div class="col-lg-12"> </div>
<!-- Content Row -->
<div class="row">
<!-- Sidebar Column -->
<div class="col-md-3">
<ul id="mysidebar" class="nav">
<li class="sidebarTitle"> </li>
<li>
<a href="#">Common Guidelines</a>
<ul>
<li class="subfolders">
<a href="#">Introduction</a>
<ul>
<li class="thirdlevel"><a href="index.html">Home</a></li>
</ul>
</li>
</ul>
<li>
<a href="#">Account Configuration</a>
<ul>
<li class="subfolders">
<a href="#">Predefined Content API</a>
<ul>
<li class="thirdlevel"><a href="account-configuration-predefined-content-overview.html">Overview</a></li>
<li class="thirdlevel"><a href="account-configuration-predefined-content-methods.html">Methods</a></li>
<li class="thirdlevel"><a href="account-configuration-predefined-content-get-items.html">Get Predefined Content Items</a></li>
<li class="thirdlevel"><a href="account-configuration-predefined-content-get-by-id.html">Get Predefined Content by ID</a></li>
<li class="thirdlevel"><a href="account-configuration-predefined-content-query-delta.html">Predefined Content Query Delta</a></li>
<li class="thirdlevel"><a href="account-configuration-predefined-content-create-content.html">Create Predefined Content</a></li>
<li class="active thirdlevel"><a href="account-configuration-predefined-content-update-content.html">Update Predefined Content</a></li>
<li class="thirdlevel"><a href="account-configuration-predefined-content-update-content-items.html">Update Predefined Content Items</a></li>
<li class="thirdlevel"><a href="account-configuration-predefined-content-delete-content.html">Delete Predefined Content</a></li>
<li class="thirdlevel"><a href="account-configuration-predefined-content-delete-content-items.html">Delete Predefined Content Items</a></li>
<li class="thirdlevel"><a href="account-configuration-predefined-content-get-default-items.html">Get Default Predefined Content Items</a></li>
<li class="thirdlevel"><a href="account-configuration-predefined-content-get-default-items-by-id.html">Get Default Predefined Content by ID</a></li>
<li class="thirdlevel"><a href="account-configuration-predefined-content-appendix.html">Appendix</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">Automatic Messages API</a>
<ul>
<li class="thirdlevel"><a href="account-configuration-automatic-messages-overview.html">Overview</a></li>
<li class="thirdlevel"><a href="account-configuration-automatic-messages-methods.html">Methods</a></li>
<li class="thirdlevel"><a href="account-configuration-automatic-messages-get-automatic-messages.html">Get Automatic Messages</a></li>
<li class="thirdlevel"><a href="account-configuration-automatic-messages-get-automatic-message-by-id.html">Get Automatic Message by ID</a></li>
<li class="thirdlevel"><a href="account-configuration-automatic-messages-update-an-automatic-message.html">Update an Automatic Message</a></li>
<li class="thirdlevel"><a href="account-configuration-automatic-messages-appendix.html">Appendix</a></li>
</ul>
</li>
</ul>
<li>
<a href="#">Administration</a>
<ul>
<li class="subfolders">
<a href="#">Users API</a>
<ul>
<li class="thirdlevel"><a href="administration-users-overview.html">Overview</a></li>
<li class="thirdlevel"><a href="administration-users-methods.html">Methods</a></li>
<li class="thirdlevel"><a href="administration-get-all-users.html">Get all users</a></li>
<li class="thirdlevel"><a href="administration-get-user-by-id.html">Get user by ID</a></li>
<li class="thirdlevel"><a href="administration-create-users.html">Create users</a></li>
<li class="thirdlevel"><a href="administration-update-users.html">Update users</a></li>
<li class="thirdlevel"><a href="administration-update-user.html">Update user</a></li>
<li class="thirdlevel"><a href="administration-delete-users.html">Delete users</a></li>
<li class="thirdlevel"><a href="administration-delete-user.html">Delete user</a></li>
<li class="thirdlevel"><a href="administration-change-users-password.html">Change user's password</a></li>
<li class="thirdlevel"><a href="administration-reset-users-password.html">Reset user's password</a></li>
<li class="thirdlevel"><a href="administration-user-query-delta.html">User query delta</a></li>
<li class="thirdlevel"><a href="administration-users-appendix.html">Appendix</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">Skills API</a>
<ul>
<li class="thirdlevel"><a href="administration-skills-overview.html">Overview</a></li>
<li class="thirdlevel"><a href="administration-skills-methods.html">Methods</a></li>
<li class="thirdlevel"><a href="administration-get-all-skills.html">Get all skills</a></li>
<li class="thirdlevel"><a href="administration-get-skill-by-id.html">Get skill by ID</a></li>
<li class="thirdlevel"><a href="administration-create-skills.html">Create skills</a></li>
<li class="thirdlevel"><a href="administration.update-skills.html">Update skills</a></li>
<li class="thirdlevel"><a href="administration-update-skill.html">Update skill</a></li>
<li class="thirdlevel"><a href="administration-delete-skills.html">Delete skills</a></li>
<li class="thirdlevel"><a href="administration-delete-skill.html">Delete skill</a></li>
<li class="thirdlevel"><a href="administration-skills-query-delta.html">Skills Query Delta</a></li>
<li class="thirdlevel"><a href="administration-skills-appendix.html">Appendix</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">Agent Groups API</a>
<ul>
<li class="thirdlevel"><a href="administration-agent-groups-overview.html">Overview</a></li>
<li class="thirdlevel"><a href="administration-agent-groups-methods.html">Methods</a></li>
<li class="thirdlevel"><a href="administration-get-all-agent-groups.html">Get all agent groups</a></li>
<li class="thirdlevel"><a href="administration-get-agent-groups-by-id.html">Get agent group by ID</a></li>
<li class="thirdlevel"><a href="administration-create-agent-groups.html">Create agent groups</a></li>
<li class="thirdlevel"><a href="administration-update-agent-groups.html">Update agent groups</a></li>
<li class="thirdlevel"><a href="administration-update-agent-group.html">Update agent group</a></li>
<li class="thirdlevel"><a href="administration-delete-agent-groups.html">Delete agent groups</a></li>
<li class="thirdlevel"><a href="administration-delete-agent-group.html">Delete agent group</a></li>
<li class="thirdlevel"><a href="administration-get-subgroups-and-members.html">Get subgroups and members of an agent group</a></li>
<li class="thirdlevel"><a href="administration-agent-groups-query-delta.html">Agent Groups Query Delta</a></li>
</ul>
</li>
</ul>
<li>
<a href="#">Consumer Experience</a>
<ul>
<li class="subfolders">
<a href="#">JavaScript Chat API</a>
<ul>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-getting-started.html">Getting Started</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-chat-states.html">Chat States</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-surveys.html">Surveys</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-creating-an-instance.html">Creating an Instance</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-methods.html">Methods</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-getestimatedwaittime.html">getEstimatedWaitTime</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-getprechatsurvey.html">getPreChatSurvey</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-getengagement.html">getEngagement(reqObj)</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-requestchat.html">requestChat</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-addline.html">addLine</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-setvisitortyping.html">setVisitorTyping</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-setvisitorname.html">setVisitorName</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-endchat.html">endChat</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-setcustomvariable.html">setCustomVariable</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-requesttranscript.html">requestTranscript</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-getexitsurvey.html">getExitSurvey</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-submitexitsurvey.html">submitExitSurvey</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-getofflinesurvey.html">getOfflineSurvey</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-submitofflinesurvey.html">submitOfflineSurvey</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-getstate.html">getState</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-getagentloginname.html">getAgentLoginName</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-getvisitorname.html">getVisitorName</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-getagentid.html">getAgentId</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-getrtsessionid.html">getRtSessionId</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-getsessionkey.html">getSessionKey</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-getagenttyping.html">getAgentTyping</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-events.html">Events</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-onload.html">onLoad</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-oninit.html">onInit</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-onestimatedwaittime.html">onEstimatedWaitTime</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-onprechatsurvey.html">onPreChatSurvey</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-onstart.html">onStart</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-onstop.html">onStop</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-onrequestchat.html">onRequestChat</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-ontranscript.html">onTranscript</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-online.html">onLine</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-onstate.html">onState</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-oninfo.html">onInfo</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-onagenttyping.html">onAgentTyping</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-onexitsurvey.html">onExitSurvey</a></li>
<li class="thirdlevel"><a href="consumer-experience-javascript-chat-onaccounttoaccounttransfer.html">onAccountToAccountTransfer</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">Server Chat API</a>
<ul>
<li class="thirdlevel"><a href="consumer-experience-server-chat-getting-started.html">Getting Started</a></li>
<li class="thirdlevel"><a href="consumer-experience-server-chat-methods.html">Methods</a></li>
<li class="thirdlevel"><a href="consumer-experience-server-chat-retrieve-availability.html">Retrieve Availability</a></li>
<li class="thirdlevel"><a href="consumer-experience-server-chat-retrieve-available-slots.html">Retrieve Available Slots</a></li>
<li class="thirdlevel"><a href="consumer-experience-server-chat-retrieve-estimated-wait-time.html">Retrieve Estimated Wait Time</a></li>
<li class="thirdlevel"><a href="consumer-experience-server-chat-retrieve-offline-survey.html">Retrieve an Offline Survey</a></li>
<li class="thirdlevel"><a href="consumer-experience-server-chat-start-chat.html">Start a Chat</a></li>
<li class="thirdlevel"><a href="consumer-experience-server-chat-retrieve-chat-resources.html">Retrieve Chat Resources, Events and Information</a></li>
<li class="thirdlevel"><a href="consumer-experience-server-chat-retrieve-chat-events.html">Retrieve Chat Events</a></li>
<li class="thirdlevel"><a href="consumer-experience-server-chat-add-lines.html">Add Lines / End Chat</a></li>
<li class="thirdlevel"><a href="consumer-experience-server-chat-retrieve-chat-information.html">Retrieve Chat Information</a></li>
<li class="thirdlevel"><a href="consumer-experience-server-chat-retrieve-visitor-name.html">Retrieve the Visitor's Name</a></li>
<li class="thirdlevel"><a href="consumer-experience-server-chat-set-visitor-name.html">Set the Visitor's Name</a></li>
<li class="thirdlevel"><a href="consumer-experience-server-chat-retrieve-agent-typing-status.html">Retrieve the Agent's Typing Status</a></li>
<li class="thirdlevel"><a href="consumer-experience-server-chat-retrieve-visitor-typing-status.html">Retrieve the Visitor's Typing Status</a></li>
<li class="thirdlevel"><a href="consumer-experience-server-chat-set-visitor-typing-status.html">Set the Visitor's Typing Status</a></li>
<li class="thirdlevel"><a href="consumer-experience-server-chat-retrieve-exit-survey-structure.html">Retrieve Exit Survey Structure</a></li>
<li class="thirdlevel"><a href="consumer-experience-server-chat-submit-survey-data.html">Submit Survey Data</a></li>
<li class="thirdlevel"><a href="consumer-experience-server-chat-set-custom-variables.html">Set Custom Variables</a></li>
<li class="thirdlevel"><a href="consumer-experience-server-chat-send-transcript.html">Send a Transcript</a></li>
<li class="thirdlevel"><a href="consumer-experience-server-chat-sample.html">Sample Postman Collection</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">In-App Messaging SDK iOS (2.0)</a>
<ul>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-quick-start.html">Quick Start</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-advanced-configurations.html">Advanced Configurations</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-methods.html">Methods</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-initialize.html">initialize</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-showconversation.html">showConversation</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-removeconversation.html">removeConversation</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-reconnect.html">reconnect</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-togglechatactions.html">toggleChatActions</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-checkactiveconversation.html">checkActiveConversation</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-markasurgent.html">markAsUrgent</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-isurgent.html">isUrgent</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-dismissurgent.html">dismissUrgent</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-resolveconversation.html">resolveConversation</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-clearhistory.html">clearHistory</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-logout.html">logout</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-destruct.html">destruct</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-handlepush.html">handlePush</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-registerpushnotifications.html">registerPushNotifications</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-setuserprofile.html">setUserProfile</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-getassignedagent.html">getAssignedAgent</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-subscribelogevents.html">subscribeLogEvents</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-getsdkversion.html">getSDKVersion</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-printalllocalizedkeys.html">printAllLocalizedKeys</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-printsupportedlanguages.html">printSupportedLanguages</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-getallsupportedlanguages.html">getAllSupportedLanguages</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-interfacedefinitions.html">Interface and Class Definitions</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-callbacks-index.html">Callbacks index</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-configuring-the-sdk.html">Configuring the SDK</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-attributes.html">Attributes</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-deprecated-attributes.html">Deprecated Attributes</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-stringlocalization.html">String localization in SDK</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-localizationkeys.html">Localization Keys</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-timestamps.html">Timestamps Formatting</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-createcertificate.html">OS Certificate Creation</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-advanced-csat.html">CSAT UI Content</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-photosharing.html">Photo Sharing (Beta)</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-pushnotifications.html">Configuring Push Notifications</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-opensource.html">Open Source List</a></li>
<li class="thirdlevel"><a href="consumer-experience-ios-sdk-security.html">Security</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">In-App Messaging SDK Android (2.0)</a>
<ul>
<li class="thirdlevel"><a href="consumer-experience-android-sdk.html">Version 2.0</a></li>
</ul>
</li>
</ul>
<li>
<a href="#">Real-time Interactions</a>
<ul>
<li class="subfolders">
<a href="#">Visit Information API</a>
<ul>
<li class="thirdlevel"><a href="rt-interactions-visit-information-overview.html">Overview</a></li>
<li class="thirdlevel"><a href="rt-interactions-visit-information-visit-information.html">Visit Information</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">App Engagement API</a>
<ul>
<li class="thirdlevel"><a href="rt-interactions-app-engagement-overview.html">Overview</a></li>
<li class="thirdlevel"><a href="rt-interactions-app-engagement-methods.html">Methods</a></li>
<li class="thirdlevel"><a href="rt-interactions-create-session.html">Create Session</a></li>
<li class="thirdlevel"><a href="rt-interactions-update-session.html">Update Session</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">Engagement Attributes</a>
<ul>
<li class="thirdlevel"><a href="rt-interactions-engagement-attributes-overview.html">Overview</a></li>
<li class="thirdlevel"><a href="rt-interactions-engagement-attributes-engagement-attributes.html">Engagement Attributes</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">IVR Engagement API</a>
<ul>
<li class="thirdlevel"><a href="rt-interactions-ivr-engagement-overview.html">Overview</a></li>
<li class="thirdlevel"><a href="rt-interactions-ivr-engagement-methods.html">Methods</a></li>
<li class="thirdlevel"><a href="rt-interactions-ivr-engagement-external engagement.html">External Engagement</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">Validate Engagement</a>
<ul>
<li class="thirdlevel"><a href="rt-interactions-validate-engagement-overview.html">Overview</a></li>
<li class="thirdlevel"><a href="rt-interactions-validate-engagement-validate-engagement.html">Validate Engagement API</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">Engagement Window Widget SDK</a>
<ul>
<li class="thirdlevel"><a href="rt-interactions-window-sdk-overview.html">Overview</a></li>
<li class="thirdlevel"><a href="rt-interactions-window-sdk-getting-started.html">Getting Started</a></li>
<li class="thirdlevel"><a href="rt-interactions-window-sdk-limitations.html">Limitations</a></li>
<li class="thirdlevel"><a href="rt-interactions-window-sdk-configuration.html">Configuration</a></li>
<li class="thirdlevel"><a href="rt-interactions-window-sdk-how-to-use.html">How to use the SDK</a></li>
<li class="thirdlevel"><a href="rt-interactions-window-sdk-code-examples.html">Code Examples</a></li>
<li class="thirdlevel"><a href="rt-interactions-window-sdk-event-structure.html">Event Structure</a></li>
</ul>
</li>
</ul>
<li>
<a href="#">Agent</a>
<ul>
<li class="subfolders">
<a href="#">Agent Workspace Widget SDK</a>
<ul>
<li class="thirdlevel"><a href="agent-workspace-sdk-overview.html">Overview</a></li>
<li class="thirdlevel"><a href="agent-workspace-sdk-getting-started.html">Getting Started</a></li>
<li class="thirdlevel"><a href="agent-workspace-sdk-limitations.html">Limitations</a></li>
<li class="thirdlevel"><a href="agent-workspace-sdk-how-to-use.html">How to use the SDK</a></li>
<li class="thirdlevel"><a href="agent-workspace-sdk-methods.html">Methods</a></li>
<li class="thirdlevel"><a href="agent-workspace-sdk-public-model.html">Public Model Structure</a></li>
<li class="thirdlevel"><a href="agent-workspace-sdk-public-properties.html">Public Properties</a></li>
<li class="thirdlevel"><a href="agent-workspace-sdk-code-examples.html">Code Examples</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">LivePerson Domain API</a>
<ul>
<li class="thirdlevel"><a href="agent-domain-domain-api.html">Domain API</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">Login Service API</a>
<ul>
<li class="thirdlevel"><a href="login-getting-started.html">Getting Started</a></li>
<li class="thirdlevel"><a href="agent-login-methods.html">Methods</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">Chat Agent API</a>
<ul>
<li class="thirdlevel"><a href="chat-agent-getting-started.html">Getting Started</a></li>
<li class="thirdlevel"><a href="agent-chat-agent-methods.html">Methods</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">Messaging Agent SDK</a>
<ul>
<li class="thirdlevel"><a href="messaging-agent-sdk-overview.html">Overview</a></li>
</ul>
</li>
</ul>
<li>
<a href="#">Data</a>
<ul>
<li class="subfolders">
<a href="#">Data Access API</a>
<ul>
<li class="thirdlevel"><a href="data-data-access.html">Data Access API</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">Messaging Operations API</a>
<ul>
<li class="thirdlevel"><a href="data-messaging-operations.html">Messaging Operations API</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">Messaging Interactions API</a>
<ul>
<li class="thirdlevel"><a href="data-messaging-interactions.html">Messaging Interactions API (Beta)</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">Engagement History API</a>
<ul>
<li class="thirdlevel"><a href="data-engagement-history.html">Engagement History API</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">Operational Real-time API</a>
<ul>
<li class="thirdlevel"><a href="data-operational-realtime.html">Operational Real-time API</a></li>
</ul>
</li>
</ul>
<li>
<a href="#">LiveEngage Tag</a>
<ul>
<li class="subfolders">
<a href="#">LE Tag Events</a>
<ul>
<li class="thirdlevel"><a href="lp-tag-tag-events.html">LE Tag Events</a></li>
</ul>
</li>
</ul>
<li>
<a href="#">Messaging Window API</a>
<ul>
<li class="subfolders">
<a href="#">Introduction</a>
<ul>
<li class="thirdlevel"><a href="consumer-interation-index.html">Home</a></li>
<li class="thirdlevel"><a href="consumer-int-protocol-overview.html">Protocol Overview</a></li>
<li class="thirdlevel"><a href="consumer-int-getting-started.html">Getting Started</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">Tutorials</a>
<ul>
<li class="thirdlevel"><a href="consumer-int-get-msg.html">Get Messages</a></li>
<li class="thirdlevel"><a href="consumer-int-conversation-md.html">Conversation Metadata</a></li>
<li class="thirdlevel"><a href="consumer-int-readaccept-events.html">Read/Accept events</a></li>
<li class="thirdlevel"><a href="consumer-int-authentication.html">Authentication</a></li>
<li class="thirdlevel"><a href="consumer-int-agent-profile.html">Agent Profile</a></li>
<li class="thirdlevel"><a href="consumer-int-post-survey.html">Post Conversation Survey</a></li>
<li class="thirdlevel"><a href="consumer-int-client-props.html">Client Properties</a></li>
<li class="thirdlevel"><a href="consumer-int-no-headers.html">Avoid Webqasocket Headers</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">Samples</a>
<ul>
<li class="thirdlevel"><a href="consumer-int-js-sample.html">JavaScript Messenger</a></li>
</ul>
</li>
<li class="subfolders">
<a href="#">API Reference</a>
<ul>
<li class="thirdlevel"><a href="consumer-int-api-reference.html">Overview</a></li>
<li class="thirdlevel"><a href="consumer-int-msg-reqs.html">Request Builder</a></li>
<li class="thirdlevel"><a href="consumer-int-msg-resps.html">Response Builder</a></li>
<li class="thirdlevel"><a href="consumer-int-msg-notifications.html">Notification Builder</a></li>
<li class="thirdlevel"><a href="consumer-int-msg-req-conv.html">New Conversation</a></li>
<li class="thirdlevel"><a href="consumer-int-msg-close-conv.html">Close Conversation</a></li>
<li class="thirdlevel"><a href="consumer-int-msg-csat-conv.html">Update CSAT</a></li>
<li class="thirdlevel"><a href="consumer-int-msg-sub-conv.html">Subscribe Conversations Metadata</a></li>
<li class="thirdlevel"><a href="consumer-int-msg-unsub-conv.html">Unsubscribe Conversations Metadata</a></li>
<li class="thirdlevel"><a href="consumer-int-msg-text-cont.html">Publish Content</a></li>
<li class="thirdlevel"><a href="consumer-int-msg-sub-events.html">Subscribe Conversation Content</a></li>
<li class="thirdlevel"><a href="consumer-int-msg-init-con.html">Browser Init Connection</a></li>
</ul>
</li>
</ul>
<!-- if you aren't using the accordion, uncomment this block:
<p class="external">
<a href="#" id="collapseAll">Collapse All</a> | <a href="#" id="expandAll">Expand All</a>
</p>
-->
</li>
</ul>
</div>
<!-- this highlights the active parent class in the navgoco sidebar. this is critical so that the parent expands when you're viewing a page. This must appear below the sidebar code above. Otherwise, if placed inside customscripts.js, the script runs before the sidebar code runs and the class never gets inserted.-->
<script>$("li.active").parents('li').toggleClass("active");</script>
<!-- Content Column -->
<div class="col-md-9">
<div class="post-header">
<h1 class="post-title-main">Update Predefined Content</h1>
</div>
<div class="post-content">
<p>Updates an existing Predefined Content item for a specific account.</p>
<h2 id="request">Request</h2>
<table>
<thead>
<tr>
<th style="text-align: left">Method</th>
<th style="text-align: left">URL</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left">PUT</td>
<td style="text-align: left">/api/account/{accountId}/configuration/engagement-window/canned-responses/{pre-defined-content-id}</td>
</tr>
</tbody>
</table>
<p><strong>Path Parameters</strong></p>
<table>
<thead>
<tr>
<th style="text-align: left">Parameter</th>
<th style="text-align: left">Description</th>
<th style="text-align: left">Type</th>
<th style="text-align: left">Notes</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left">accountId</td>
<td style="text-align: left">LP site ID</td>
<td style="text-align: left">string ^[a-zA-Z0-9_]{1,20}$</td>
<td style="text-align: left">Validation fail error code: 400</td>
</tr>
<tr>
<td style="text-align: left">predefined-content-id</td>
<td style="text-align: left">Account Config object’s unique ID</td>
<td style="text-align: left">Positive long number greater than zero</td>
<td style="text-align: left"> </td>
</tr>
</tbody>
</table>
<h2 id="query-parameters">Query Parameters</h2>
<table>
<thead>
<tr>
<th style="text-align: left">Name</th>
<th style="text-align: left">Description</th>
<th style="text-align: left">Type</th>
<th style="text-align: left">Required</th>
<th style="text-align: left">Notes</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left">v</td>
<td style="text-align: left">API version</td>
<td style="text-align: left">Double</td>
<td style="text-align: left">Required</td>
<td style="text-align: left">Default value: 2.0 <br /> Validation fail error code: 400</td>
</tr>
<tr>
<td style="text-align: left">select</td>
<td style="text-align: left">Dynamic selection of the response fields.</td>
<td style="text-align: left">YOGA ‘gdata’ dialect.</td>
<td style="text-align: left">Optional</td>
<td style="text-align: left">Validation error: 400 <br />Non-existing field: no error, blank in response <br /> Supported fields: any in response body</td>
</tr>
<tr>
<td style="text-align: left">fields</td>
<td style="text-align: left">List of required fields</td>
<td style="text-align: left">Comma delimited list of strings</td>
<td style="text-align: left">Optional</td>
<td style="text-align: left">Validation fail error code: 400 <br /> Non existing field error code: 400 <br /> Supported fields: <br /> 1. enabled <br /> 2. data <br /> 3. categoriesIds <br /> 4. hot-key <br /> 5. type</td>
</tr>
<tr>
<td style="text-align: left">field_set</td>
<td style="text-align: left">Predefined set of fields</td>
<td style="text-align: left">Comma delimited list of strings</td>
<td style="text-align: left">Optional</td>
<td style="text-align: left">Default: summary <br /> Validation fail error code: 400 <br /> Non existing field error code: 400 <br /> Supported field_set values: <br /> 1. all(id, deleted, enabled, data, categoriesIds, type, hot-key) <br /> 2. summary(id, deleted, enabled, categoriesIds, type, hot-key)</td>
</tr>
<tr>
<td style="text-align: left">lang</td>
<td style="text-align: left">List of requested content languages</td>
<td style="text-align: left">Comma delimited list of language IDs (en-US,…)</td>
<td style="text-align: left">Optional</td>
<td style="text-align: left">Default: all languages</td>
</tr>
</tbody>
</table>
<p><strong>Request Headers</strong></p>
<table>
<thead>
<tr>
<th style="text-align: left">Header</th>
<th style="text-align: left">Description</th>
<th style="text-align: left">Notes</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left">Authorization</td>
<td style="text-align: left">Contains token string to allow request authentication and authorization.</td>
<td style="text-align: left"> </td>
</tr>
<tr>
<td style="text-align: left">X-HTTP-Method-Override=PUT</td>
<td style="text-align: left">Overrides unsupported HTTP methods.</td>
<td style="text-align: left">To be used with the PUT value.</td>
</tr>
<tr>
<td style="text-align: left">If-Match</td>
<td style="text-align: left">Contains data revision, as known by the client.</td>
<td style="text-align: left">Allows optimization of backend, networking and client resource utilization.</td>
</tr>
</tbody>
</table>
<p><strong>Request Body</strong></p>
<p>See <a href="account-configuration-predefined-content-appendix.html">Appendix</a> for objects’ data structure.</p>
<h2 id="response">Response</h2>
<p><strong>Response Codes</strong></p>
<table>
<thead>
<tr>
<th style="text-align: left">Code</th>
<th style="text-align: left">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left">200</td>
<td style="text-align: left">OK</td>
</tr>
<tr>
<td style="text-align: left">401</td>
<td style="text-align: left">Not Authenticated</td>
</tr>
<tr>
<td style="text-align: left">403</td>
<td style="text-align: left">Not Authorized</td>
</tr>
<tr>
<td style="text-align: left">404</td>
<td style="text-align: left">Data Not Found</td>
</tr>
<tr>
<td style="text-align: left">500</td>
<td style="text-align: left">Internal Server Error</td>
</tr>
</tbody>
</table>
<p><strong>Response Body</strong></p>
<p>Updated Predefined Content JSON.</p>
<div class="tags">
</div>
</div>
<hr class="shaded"/>
<footer>
<div class="row">
<div class="col-lg-12 footer">
©2017 LivePerson. All rights reserved.<br />This documentation is subject to change without notice.<br />
Site last generated: Feb 28, 2017 <br />
<p><img src="img/company_logo.png" alt="Company logo"/></p>
</div>
</div>
</footer>
</div>
<!-- /.row -->
</div>
<!-- /.container -->
</div>
</body>
</html>
|
LivePersonInc/dev-hub
|
content4/account-configuration-predefined-content-update-content.html
|
HTML
|
mit
| 119,407
|
---
layout: post
title: "UX Lausanne: Delight and Innovation"
date: 2014-06-13 05:40:08
categories: blog
description: My sketchnote of Giles Colborne's talk Delight and Innovation
image: https://farm4.staticflickr.com/3794/14103533820_6b7067693e_z.jpg
tags: uxls, ux, event, lausanne, delight, innovation, sketchnote
---
Here's my sketchnote of [Giles Colborne](https://twitter.com/gilescolborne)'s talk.
<figure>
<img src="https://farm4.staticflickr.com/3837/14224367428_e503c1c557_z.jpg" alt="Delight and innovation sketchnote">
<figcaption>
Delight and Innovation sketchnote. <a href="https://www.flickr.com/photos/alienlebarge/14224367428/">View original on Flickr</a>
</figcaption>
</figure>
## Related Tweets
<blockquote class="twitter-tweet" lang="fr"><p>"we asked ordinary people what is delightful for them" <a href="https://twitter.com/gilescolborne">@gilescolborne</a> <a href="https://twitter.com/hashtag/uxls?src=hash">#uxls</a></p>— nicolasnova (@nicolasnova) <a href="https://twitter.com/nicolasnova/statuses/469389446660775936">22 Mai 2014</a></blockquote>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
<blockquote class="twitter-tweet" lang="fr"><p>"we are experience designers and post-its are what we do" says <a href="https://twitter.com/gilescolborne">@gilescolborne</a> <a href="https://twitter.com/hashtag/uxls?src=hash">#uxls</a></p>— nicolasnova (@nicolasnova) <a href="https://twitter.com/nicolasnova/statuses/469393452560838656">22 Mai 2014</a></blockquote>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
<blockquote class="twitter-tweet" lang="fr"><p>So proud to present <a href="https://twitter.com/hashtag/uxls?src=hash">#uxls</a> with <a href="https://twitter.com/uxromandie">@uxromandie</a> - <a href="https://twitter.com/gilescolborne">@gilescolborne</a> talk about delight (and anxiety) was the perfect intro. <a href="http://t.co/XUuc4LMOZY">pic.twitter.com/XUuc4LMOZY</a></p>— :ratio (@ratio) <a href="https://twitter.com/ratio/statuses/469397523728453632">22 Mai 2014</a></blockquote>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
<blockquote class="twitter-tweet" lang="fr"><p>Discover (or rewatch) the great talk by <a href="https://twitter.com/gilescolborne">@gilescolborne</a> on innovation and delight at <a href="http://t.co/bwmT5f14Uz">http://t.co/bwmT5f14Uz</a> <a href="https://twitter.com/hashtag/UXLS?src=hash">#UXLS</a></p>— UX Lausanne #UXLS (@uxlausanne) <a href="https://twitter.com/uxlausanne/statuses/479621236855930880">19 Juin 2014</a></blockquote>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
<blockquote class="twitter-tweet" lang="fr"><p>All the videos from day 1 of <a href="https://twitter.com/hashtag/UXLS?src=hash">#UXLS</a> are available <a href="http://t.co/WxyW6th2CS">http://t.co/WxyW6th2CS</a> <a href="https://twitter.com/gilescolborne">@gilescolborne</a> <a href="https://twitter.com/birgitgcom">@birgitgcom</a> <a href="https://twitter.com/pboersma">@pboersma</a> <a href="https://twitter.com/simonraess">@simonraess</a> <a href="https://twitter.com/fabianhemmert">@fabianhemmert</a></p>— UX Lausanne #UXLS (@uxlausanne) <a href="https://twitter.com/uxlausanne/statuses/479909489626611712">20 Juin 2014</a></blockquote>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
|
alienlebarge/alienlebarge.github.com
|
_posts/2014-06-13-ux-lausanne-delight-and-innovation.md
|
Markdown
|
mit
| 3,507
|
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("IronRureTests")]
|
iwillspeak/IronRure
|
src/IronRure/Meta.cs
|
C#
|
mit
| 88
|
<h1 class="title" data-bind="title"></h1>
<input class="meter" data-angleOffset=-125 data-angleArc=360 data-width=75 data-readOnly=true data-bind-value="value | shortenedNumber" data-bind-data-min="min" data-bind-data-max="max">
<p class="more-info" data-bind="moreinfo"></p>
<p class="updated-at" data-bind="updatedAtMessage"></p>
|
ropensci/rodash
|
widgets/meter/meter.html
|
HTML
|
mit
| 335
|
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Component\Resource\Translation\Provider;
final class ImmutableTranslationLocaleProvider implements TranslationLocaleProviderInterface
{
/** @var array */
private $definedLocalesCodes;
private string $defaultLocaleCode;
public function __construct(array $definedLocalesCodes, string $defaultLocaleCode)
{
$this->definedLocalesCodes = $definedLocalesCodes;
$this->defaultLocaleCode = $defaultLocaleCode;
}
public function getDefinedLocalesCodes(): array
{
return $this->definedLocalesCodes;
}
public function getDefaultLocaleCode(): string
{
return $this->defaultLocaleCode;
}
}
|
Sylius/Resource
|
Translation/Provider/ImmutableTranslationLocaleProvider.php
|
PHP
|
mit
| 925
|
var test2 = true;
|
cloudspace/ettu
|
spec/dummy/app/assets/javascripts/test.js
|
JavaScript
|
mit
| 18
|
using System.Linq;
using System.Threading.Tasks;
using SfAttendance.Server.Entities;
using SfAttendance.Server.Extensions;
using SfAttendance.Server.Services.Abstract;
using SfAttendance.Server.ViewModels.AccountViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
namespace SfAttendance.Server.Controllers.api
{
[Authorize]
[Route("api/[controller]")]
public class AccountController : BaseController
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
public AccountController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<AccountController>();
}
[HttpPost("login")]
[AllowAnonymous]
public async Task<IActionResult> Login([FromBody]LoginViewModel model)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
var user = await _userManager.FindByEmailAsync(model.Email);
var roles = await _userManager.GetRolesAsync(user);
_logger.LogInformation(1, "User logged in.");
return AppUtils.SignIn(user, roles);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { RememberMe = model.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning(2, "User account locked out.");
return BadRequest("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return BadRequest(ModelState.GetModelErrors());
}
}
[HttpPost("register")]
[AllowAnonymous]
public async Task<IActionResult> Register([FromBody]RegisterViewModel model, string returnUrl = null)
{
var currentUser = new ApplicationUser
{
UserName = model.Email,
Email = model.Email,
FirstName = model.Firstname,
LastName = model.Lastname
};
var result = await _userManager.CreateAsync(currentUser, model.Password);
if (result.Succeeded)
{
// Add to roles
var roleAddResult = await _userManager.AddToRoleAsync(currentUser, "User");
if (roleAddResult.Succeeded)
{
var code = await _userManager.GenerateEmailConfirmationTokenAsync(currentUser);
var host = Request.Scheme + "://" + Request.Host;
var callbackUrl = host + "?userId=" + currentUser.Id + "&emailConfirmCode=" + code;
var confirmationLink = "<a class='btn-primary' href=\"" + callbackUrl + "\">Confirm email address</a>";
_logger.LogInformation(3, "User created a new account with password.");
//await _emailSender.SendEmailAsync(MailType.Register, new EmailModel { To = model.Email }, confirmationLink);
return Json(new { });
}
}
AddErrors(result);
// If we got this far, something failed, redisplay form
return BadRequest(ModelState.GetModelErrors());
}
[HttpPost("logout")]
public async Task<IActionResult> LogOff()
{
await _signInManager.SignOutAsync();
_logger.LogInformation(4, "User logged out.");
return Ok();
}
[HttpGet("ExternalLogin")]
[AllowAnonymous]
public IActionResult ExternalLogin(string provider, string returnUrl = null)
{
// Request a redirect to the external login provider.
var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return Challenge(properties, provider);
}
[HttpGet("ExternalLoginCallback")]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
if (remoteError != null)
{
return Render(ExternalLoginStatus.Error);
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return Render(ExternalLoginStatus.Invalid);
}
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
_logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);
return Render(ExternalLoginStatus.Ok); // Everything Ok, login user
}
if (result.RequiresTwoFactor)
{
return Render(ExternalLoginStatus.TwoFactor);
}
if (result.IsLockedOut)
{
return Render(ExternalLoginStatus.Lockout);
}
else
{
// If the user does not have an account, then ask the user to create an account.
// ViewData["ReturnUrl"] = returnUrl;
// ViewData["LoginProvider"] = info.LoginProvider;
// var email = info.Principal.FindFirstValue(ClaimTypes.Email);
// return RedirectToAction("Index", "Home", new ExternalLoginCreateAccountViewModel { Email = email });
return Render(ExternalLoginStatus.CreateAccount);
}
}
[HttpPost("ExternalLoginCreateAccount")]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ExternalLoginCreateAccount([FromBody]ExternalLoginConfirmationViewModel model, string returnUrl = null)
{
// Get the information about the user from the external login provider
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return BadRequest("External login information cannot be accessed, try again.");
}
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user);
if (result.Succeeded)
{
result = await _userManager.AddLoginAsync(user, info);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
return Ok(); // Everything ok
}
}
return BadRequest(new[] { "Email already exists" });
}
[HttpGet("ConfirmEmail")]
[AllowAnonymous]
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return View("Error");
}
var result = await _userManager.ConfirmEmailAsync(user, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
[HttpGet("ForgotPassword")]
[AllowAnonymous]
public IActionResult ForgotPassword()
{
return View();
}
[HttpPost("ForgotPassword")]
[AllowAnonymous]
public async Task<IActionResult> ForgotPassword([FromBody]ForgotPasswordViewModel model)
{
var currentUser = await _userManager.FindByNameAsync(model.Email);
if (currentUser == null || !(await _userManager.IsEmailConfirmedAsync(currentUser)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
var code = await _userManager.GeneratePasswordResetTokenAsync(currentUser);
var host = Request.Scheme + "://" + Request.Host;
var callbackUrl = host + "?userId=" + currentUser.Id + "&passwordResetCode=" + code;
var confirmationLink = "<a class='btn-primary' href=\"" + callbackUrl + "\">Reset your password</a>";
await _emailSender.SendEmailAsync(MailType.ForgetPassword, new EmailModel { To = model.Email }, confirmationLink);
return Json(new { });
}
[HttpPost("resetpassword")]
[AllowAnonymous]
public async Task<IActionResult> ResetPassword([FromBody]ResetPasswordViewModel model)
{
var user = await _userManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return Ok("Reset confirmed");
}
var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);
if (result.Succeeded)
{
return Ok("Reset confirmed"); ;
}
AddErrors(result);
return BadRequest(ModelState.GetModelErrors());
}
[HttpGet("SendCode")]
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false)
{
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return BadRequest("Error");
}
var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
[HttpPost("SendCode")]
[AllowAnonymous]
public async Task<IActionResult> SendCode([FromBody]SendCodeViewModel model)
{
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return BadRequest("Error");
}
// Generate the token and send it
var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider);
if (string.IsNullOrWhiteSpace(code))
{
return BadRequest("Error");
}
var message = "Your security code is: " + code;
if (model.SelectedProvider == "Email")
{
await _emailSender.SendEmailAsync(MailType.SecurityCode, new EmailModel { }, null);
//await _emailSender.SendEmailAsync(Email, await _userManager.GetEmailAsync(user), "Security Code", message);
}
else if (model.SelectedProvider == "Phone")
{
await _smsSender.SendSmsTwillioAsync(await _userManager.GetPhoneNumberAsync(user), message);
}
return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
[HttpGet("VerifyCode")]
[AllowAnonymous]
public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null)
{
// Require that the user has already logged in via username/password or external login
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return BadRequest("Error");
}
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
[HttpPost("VerifyCode")]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model)
{
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser);
if (result.Succeeded)
{
return RedirectToLocal(model.ReturnUrl);
}
if (result.IsLockedOut)
{
_logger.LogWarning(7, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid code.");
return View(model);
}
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private Task<ApplicationUser> GetCurrentUserAsync()
{
return _userManager.GetUserAsync(HttpContext.User);
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction(nameof(HomeController.Index), "Home");
}
}
private IActionResult Render(ExternalLoginStatus status)
{
return RedirectToAction("Index", "Home", new { externalLoginStatus = (int)status });
}
#endregion
}
}
|
mak-in/sf-attendance
|
Server/Controllers/api/AccountController.cs
|
C#
|
mit
| 15,381
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-14 02:26
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Building',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
('size', models.PositiveSmallIntegerField()),
],
),
migrations.CreateModel(
name='Floor',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('size', models.PositiveSmallIntegerField()),
('number', models.PositiveSmallIntegerField()),
('building', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='floors', to='buildings.Building')),
],
),
migrations.CreateModel(
name='Room',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('size', models.PositiveSmallIntegerField()),
('name', models.CharField(max_length=255)),
('floor', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rooms', to='buildings.Floor')),
],
),
]
|
foohooboo/graphql-cookiecutter
|
graphql_cookiecutter/buildings/migrations/0001_initial.py
|
Python
|
mit
| 1,612
|
package com.usabilityetc.spacefillerexplorer.treemap;
import java.awt.*;
/**
* Holds the information about a file required to present a tool tip
* for the rectangular region on a TreeMap panel that represent the file.
*
* @author Jeffrey Morgan
*/
public class ToolTip {
private static final String toolTipFormat = "<html><pre>%s\n\n%d bytes\n%s</pre></html>";
private final Rectangle rectangle;
private final String text;
private final long size;
private String toolTipText;
public ToolTip(final String text, final long size, final Rectangle rectangle) {
this.text = text;
this.size = size;
this.rectangle = rectangle;
}
public boolean contains(final Point p) {
return rectangle.contains(p);
}
public String getToolTipText() {
if (toolTipText == null) {
toolTipText = createToolTipText();
}
return toolTipText;
}
private String createToolTipText() {
final String[] pathComponents = text.split("/");
final String filename = pathComponents[pathComponents.length - 1];
final String pathHierarchy = createPathHierarchy(pathComponents);
return String.format(
toolTipFormat,
filename,
size,
pathHierarchy
);
}
private String createPathHierarchy(final String[] pathComponents) {
final StringBuffer pathHierarchy = new StringBuffer();
if (pathComponents.length > 1) {
pathHierarchy.append("\n");
}
for (int index = 1; index < pathComponents.length; index += 1) {
pathHierarchy.append(pathComponents[index]);
if (index < pathComponents.length - 1) {
pathHierarchy.append("\n");
pathHierarchy.append(indentation(2 * index));
}
}
return pathHierarchy.toString();
}
private String indentation(final int length) {
final Character indentationCharacter = ' ';
final StringBuffer indentation = new StringBuffer(length);
for (int i = 0; i < length; i += 1) {
indentation.append(indentationCharacter);
}
return indentation.toString();
}
}
|
UsabilityEtc/java-space-filler-explorer
|
src/main/java/com/usabilityetc/spacefillerexplorer/treemap/ToolTip.java
|
Java
|
mit
| 2,050
|
function initTask(subTask) {
var cellSide = 60;
subTask.gridInfos = {
hideSaveOrLoad: true,
cellSide: cellSide,
actionDelay: 200,
itemTypes: {
green_robot: { img: "green_robot.png", side: 80, nbStates: 9, isObstacle: true, offsetX: -14, category: "robot", team: 0, zOrder: 2 },
paint: { img: "paint.png", side: cellSide, category: "paint", isPaint: true, isObstacle: false, hasColor: true, color: "gris", zOrder: 1 },
marker: { num: 2, img: "marker.png", side: cellSide, category: "marker", isObstacle: false, isMarker: true, zOrder: 0 }
},
maxInstructions: 15,
includeBlocks: {
groupByCategory: false,
generatedBlocks: {
robot: ["east", "west", "north", "south", "paint", "markedCell"]
},
standardBlocks: {
includeAll: false,
wholeCategories: [],
singleBlocks: ["controls_repeat", "controls_if"]
}
},
ignoreInvalidMoves: false,
checkEndEveryTurn: false,
checkEndCondition: robotEndConditions.checkMarkersPainted
};
subTask.data = {
easy: [
{
tiles: [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 2, 2, 1, 1, 1, 1],
[1, 1, 1, 2, 1, 1, 2, 1, 1, 1],
[1, 1, 2, 1, 1, 1, 1, 2, 1, 1],
[1, 2, 1, 1, 1, 1, 1, 1, 2, 1],
[1, 2, 1, 1, 1, 1, 1, 1, 2, 1],
[1, 2, 1, 1, 2, 2, 1, 1, 2, 1],
[1, 2, 1, 1, 2, 2, 1, 1, 2, 1],
[1, 2, 2, 2, 2, 2, 2, 2, 2, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
],
initItems: [
{ row: 9, col: 0, dir: 0, type: "green_robot" }
]
}
]
};
initBlocklySubTask(subTask);
displayHelper.thresholdEasy = 5000;
displayHelper.thresholdMedium = 10000;
}
initWrapper(initTask, null, null, true);
|
France-ioi/bebras-tasks
|
algorea/algorea_training/training-repeat-nested-if-paint/task.js
|
JavaScript
|
mit
| 2,001
|
//
// ViewController.h
// HCSCarousel
//
// Created by Sahil Kapoor on 26/02/15.
// Copyright (c) 2015 Hot Cocoa Software. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
|
HotCocoaSoftware/HCSCarousel
|
HCSCarousel/ViewController.h
|
C
|
mit
| 230
|
# encoding: utf-8
require 'helper'
class TestParsingItIt < TestCase
# Wed Aug 16 14:00:00 UTC 2006
TIME_2006_08_16_14_00_00 = Time.local(2006, 8, 16, 14, 0, 0, 0)
def setup
@time_2006_08_16_14_00_00 = TIME_2006_08_16_14_00_00
@locale_before = Chronic.locale
Chronic.locale = :'it-IT'
end
def teardown
Chronic.locale = @locale_before
end
def test_handle_basics
time = parse_now("3 di agosto")
assert_equal Time.local(2006, 8, 3, 12), time
time = parse_now("3 di agosto", :context => :past)
assert_equal Time.local(2006, 8, 3, 12), time
time = parse_now("20 di agosto")
assert_equal Time.local(2006, 8, 20, 12), time
time = parse_now("20 di agosto", :context => :future)
assert_equal Time.local(2006, 8, 20, 12), time
time = parse_now("27 di maggio")
assert_equal Time.local(2007, 5, 27, 12), time
time = parse_now("28 di maggio", :context => :past)
assert_equal Time.local(2006, 5, 28, 12), time
time = parse_now("28 maggio alle 5pm", :context => :past)
assert_equal Time.local(2006, 5, 28, 17), time
time = parse_now("28 maggio alle 17", :context => :future)
assert_equal Time.local(2007, 5, 28, 17), time
time = parse_now("5 maggio 28", :ambiguous_time_range => :none)
assert_equal Time.local(2007, 5, 28, 05), time
end
def test_textual_forms
time = parse_now("domani")
assert_equal Time.local(2006, 8, 17, 12), time
time = parse_now("dopodomani")
assert_equal Time.local(2006, 8, 18, 14), time
time = parse_now("ieri")
assert_equal Time.local(2006, 8, 15, 12), time
time = parse_now("sabato")
assert_equal Time.local(2006, 8, 19, 12), time
time = parse_now("venerdi")
assert_equal Time.local(2006, 8, 18, 12), time
end
def test_day_portions
time = parse_now("2 di notte")
assert_equal Time.local(2006, 8, 16, 2), time
time = parse_now("2 di mattina")
assert_equal Time.local(2006, 8, 16, 2), time
time = parse_now("2 del pomeriggio")
assert_equal Time.local(2006, 8, 16, 14), time
time = parse_now("7 di sera")
assert_equal Time.local(2006, 8, 16, 19), time
end
def test_combinations
time = parse_now("sabato alle 10")
assert_equal Time.local(2006, 8, 19, 10), time
time = parse_now("prossima domenica alle 19")
assert_equal Time.local(2006, 8, 20, 19), time
end
def test_relative_times
time = parse_now("tra 7 ore")
assert_equal Time.local(2006, 8, 16, 21), time
end
def test_relative_dates
#time = parse_now("mes que vem")
#assert_equal Time.local(2006, 9, 16), time
time = parse_now("mese prossimo")
assert_equal Time.local(2006, 9, 16), time
time = parse_now("prossimo mese")
assert_equal Time.local(2006, 9, 16), time
time = parse_now("mese scorso")
assert_equal Time.local(2006, 7, 16, 12), time
time = parse_now("mese passato")
assert_equal Time.local(2006, 7, 16, 12), time
time = parse_now("ultimo mese")
assert_equal Time.local(2006, 7, 16, 12), time
time = parse_now("tra 3 giorni")
assert_equal Time.local(2006, 8, 19, 14), time
time = parse_now("tra 3 settimane")
assert_equal Time.local(2006, 9, 6, 14), time
time = parse_now("oggi alle 9")
assert_equal Time.local(2006, 8, 16, 9, 00), time
time = parse_now("adesso")
assert_equal Time.local(2006, 8, 16, 14, 00), time
end
private
def parse_now(string, options={})
Chronic.parse(string, {:now => TIME_2006_08_16_14_00_00 }.merge(options))
end
end
|
luan/chronic-l10n
|
test/test_parsing_it_it.rb
|
Ruby
|
mit
| 3,560
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `XKB_KEY_Thai_nonu` constant in crate `wayland_kbd`.">
<meta name="keywords" content="rust, rustlang, rust-lang, XKB_KEY_Thai_nonu">
<title>wayland_kbd::keysyms::XKB_KEY_Thai_nonu - Rust</title>
<link rel="stylesheet" type="text/css" href="../../main.css">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<section class="sidebar">
<p class='location'><a href='../index.html'>wayland_kbd</a>::<wbr><a href='index.html'>keysyms</a></p><script>window.sidebarCurrent = {name: 'XKB_KEY_Thai_nonu', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</section>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press 'S' to search, '?' for more options..."
type="search">
</div>
</form>
</nav>
<section id='main' class="content constant">
<h1 class='fqn'><span class='in-band'><a href='../index.html'>wayland_kbd</a>::<wbr><a href='index.html'>keysyms</a>::<wbr><a class='constant' href=''>XKB_KEY_Thai_nonu</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-3926' class='srclink' href='../../src/wayland_kbd/ffi/keysyms.rs.html#1595' title='goto source code'>[src]</a></span></h1>
<pre class='rust const'>pub const XKB_KEY_Thai_nonu: <a href='http://doc.rust-lang.org/nightly/std/primitive.u32.html'>u32</a><code> = </code><code>0x0db9</code></pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<div id="help" class="hidden">
<div class="shortcuts">
<h1>Keyboard shortcuts</h1>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
</dl>
</div>
<div class="infos">
<h1>Search tricks</h1>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>typedef</code> (or
<code>tdef</code>).
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code>)
</p>
</div>
</div>
<script>
window.rootPath = "../../";
window.currentCrate = "wayland_kbd";
window.playgroundUrl = "";
</script>
<script src="../../jquery.js"></script>
<script src="../../main.js"></script>
<script async src="../../search-index.js"></script>
</body>
</html>
|
mcanders/bevy
|
doc/wayland_kbd/keysyms/constant.XKB_KEY_Thai_nonu.html
|
HTML
|
mit
| 3,835
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.