repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
CaitlinJD/RA-Angular2Project
node_modules/tslint/lib/rules/onlyArrowFunctionsRule.js
3447
/** * @license * Copyright 2013 Palantir Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Lint = require("../index"); var OPTION_ALLOW_DECLARATIONS = "allow-declarations"; var Rule = (function (_super) { __extends(Rule, _super); function Rule() { _super.apply(this, arguments); } Rule.prototype.apply = function (sourceFile) { return this.applyWithWalker(new OnlyArrowFunctionsWalker(sourceFile, this.getOptions())); }; /* tslint:disable:object-literal-sort-keys */ Rule.metadata = { ruleName: "only-arrow-functions", description: "Disallows traditional (non-arrow) function expressions.", rationale: "Traditional functions don't bind lexical scope, which can lead to unexpected behavior when accessing 'this'.", optionsDescription: (_a = ["\n One argument may be optionally provided:\n\n * `\"", "\"` allows standalone function declarations.\n "], _a.raw = ["\n One argument may be optionally provided:\n\n * \\`\"", "\"\\` allows standalone function declarations.\n "], Lint.Utils.dedent(_a, OPTION_ALLOW_DECLARATIONS)), options: { type: "array", items: { type: "string", enum: [OPTION_ALLOW_DECLARATIONS], }, minLength: 0, maxLength: 1, }, optionExamples: ["true", ("[true, \"" + OPTION_ALLOW_DECLARATIONS + "\"]")], type: "typescript", typescriptOnly: false, }; /* tslint:enable:object-literal-sort-keys */ Rule.FAILURE_STRING = "non-arrow functions are forbidden"; return Rule; var _a; }(Lint.Rules.AbstractRule)); exports.Rule = Rule; var OnlyArrowFunctionsWalker = (function (_super) { __extends(OnlyArrowFunctionsWalker, _super); function OnlyArrowFunctionsWalker() { _super.apply(this, arguments); } OnlyArrowFunctionsWalker.prototype.visitFunctionDeclaration = function (node) { if (!node.asteriskToken && !this.hasOption(OPTION_ALLOW_DECLARATIONS)) { this.addFailure(this.createFailure(node.getStart(), "function".length, Rule.FAILURE_STRING)); } _super.prototype.visitFunctionDeclaration.call(this, node); }; OnlyArrowFunctionsWalker.prototype.visitFunctionExpression = function (node) { if (!node.asteriskToken) { this.addFailure(this.createFailure(node.getStart(), "function".length, Rule.FAILURE_STRING)); } _super.prototype.visitFunctionExpression.call(this, node); }; return OnlyArrowFunctionsWalker; }(Lint.RuleWalker));
mit
lotaris/api-copilot
spec/cli.logger.spec.js
8724
var _ = require('underscore'), colors = require('colors'); RegExp.escape = function(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); }; // TODO: complete this spec describe("CLI Logger", function() { var log4jsMock = require('./support/log4js.mock'), ScenarioMock = require('./support/scenario.mock'), cliLoggerFactory = require('../lib/cli.logger'); var CliLogger, scenario, cliLogger, sampleRequestOptions, sampleResponse; beforeEach(function() { log4jsMock.reset(); CliLogger = cliLoggerFactory(log4jsMock); scenario = new ScenarioMock({ name: 'once upon a time' }); scenario.getParameter = function() { return { displayValue: function(value) { return value; } }; }; cliLogger = new CliLogger(scenario); logger = log4jsMock.getLogger(scenario.name); sampleRequestOptions = { method: 'GET', url: 'http://example.com/foo' }; sampleResponse = { statusCode: 204 }; }); function makeRequest(requestNumber, options) { options = _.extend({}, options); requestOptions = options.request || sampleRequestOptions; response = options.response || sampleResponse; scenario.emit('client:request', requestNumber, requestOptions); if (response instanceof Error) { scenario.emit('client:error', requestNumber, response); } else { scenario.emit('client:response', requestNumber, response, Math.floor(Math.random() * 10 + 1)); } } describe("on configure", function() { it("should log the scenario name", function() { scenario.emit('configure', { name: 'once upon a time' }); expect(logger.info).toHaveBeenCalledWith('once upon a time'.bold); expect(logger.info.calls.length).toBe(1); }); }); describe("on scenario:start", function() { beforeEach(function() { cliLogger.configured = true; }); it("should log runtime parameters in debug mode", function() { scenario.emit('scenario:start', { params: { foo: 'bar', baz: { a: 1, b: 2 } } }); expect(logger.debug).toHaveBeenCalledWith('Runtime parameters:'); expect(logger.debug).toHaveBeenCalledWith(' ' + 'baz'.underline + ' = {"a":1,"b":2}'); expect(logger.debug).toHaveBeenCalledWith(' ' + 'foo'.underline + ' = "bar"'); expect(logger.debug.calls.length).toBe(3); }); it("should log no runtime parameters in debug mode", function() { scenario.emit('scenario:start', { params: {} }); expect(logger.debug).toHaveBeenCalledWith('Runtime parameters: none'); expect(logger.debug.calls.length).toBe(1); }); }); it("should log successful HTTP requests with the DEBUG level", function() { cliLogger.configured = true; makeRequest(1); expect(logger.totalCalls).toBe(2); expect(logger.debug.calls.length).toBe(2); expect(logger.debug.calls[0].args).toEqual([ "http[1]".cyan + ' GET http://example.com/foo' ]); expect(logger.debug.calls[1].args[0]).toMatch(new RegExp(RegExp.escape("http[1]".cyan + ' ' + '204 No Content'.green + ' in ') + '\\d+ms$')); }); it("should log failed HTTP requests with the DEBUG level", function() { cliLogger.configured = true; makeRequest(1, { response: new Error('foo') }); expect(logger.totalCalls).toBe(1); expect(logger.debug.calls.length).toBe(1); expect(logger.debug.calls[0].args).toEqual([ "http[1]".cyan + ' GET http://example.com/foo' ]); }); it("should log the HTTP status code in yellow if not in the 200-399 range", function() { cliLogger.configured = true; makeRequest(1, { response: { statusCode: 500, body: 'epic fail' } }); expect(logger.totalCalls).toBe(2); expect(logger.debug.calls.length).toBe(2); expect(logger.debug.calls[0].args).toEqual([ "http[1]".cyan + ' GET http://example.com/foo' ]); expect(logger.debug.calls[1].args[0]).toMatch(new RegExp(RegExp.escape("http[1]".cyan + ' ' + '500 Internal Server Error'.yellow + ' in ') + '\\d+ms$')); }); it("should number HTTP requests in the order they are made", function() { cliLogger.configured = true; _.each([ sampleResponse, { statusCode: 500, body: 'oops' }, { statusCode: 200, body: 'bar' } ], function(response, i) { makeRequest(i + 1, { response: response }); }); expect(logger.totalCalls).toBe(6); expect(logger.debug.calls.length).toBe(6); expect(logger.debug.calls[0].args).toEqual([ "http[1]".cyan + ' GET http://example.com/foo' ]); expect(logger.debug.calls[1].args[0]).toMatch(new RegExp(RegExp.escape("http[1]".cyan + ' ' + '204 No Content'.green + ' in ') + '\\d+ms$')); expect(logger.debug.calls[2].args).toEqual([ "http[2]".cyan + ' GET http://example.com/foo' ]); expect(logger.debug.calls[3].args[0]).toMatch(new RegExp(RegExp.escape("http[2]".cyan + ' ' + '500 Internal Server Error'.yellow + ' in ') + '\\d+ms$')); expect(logger.debug.calls[4].args).toEqual([ "http[3]".cyan + ' GET http://example.com/foo' ]); expect(logger.debug.calls[5].args[0]).toMatch(new RegExp(RegExp.escape("http[3]".cyan + ' ' + '200 OK'.green + ' in ') + '\\d+ms$')); }); describe("with the `baseUrl` option", function() { beforeEach(function() { cliLogger.configured = true; cliLogger.configure({ name: 'scenario', baseUrl: 'http://example.com/foo' }); expect(logger.debug).toHaveBeenCalledWith('Base URL set to http://example.com/foo'); }); it("should log only the path of URLs", function() { makeRequest(1, { request: { method: 'GET', url: 'http://example.com/foo/bar/baz' } }); expect(logger.totalCalls).toBe(3); expect(logger.debug.calls.length).toBe(3); expect(logger.debug.calls[1].args).toEqual([ "http[1]".cyan + ' GET /foo/bar/baz' ]); expect(logger.debug.calls[2].args[0]).toMatch(new RegExp(RegExp.escape("http[1]".cyan + ' ' + '204 No Content'.green + ' in ') + '\\d+ms$')); }); describe("with the `showFullUrl` option", function() { beforeEach(function() { cliLogger.configure({ name: 'scenario', showFullUrl: true }); }); it("should log full URLs", function() { makeRequest(1, { request: { method: 'GET', url: 'http://example.com/foo/bar/baz' } }); expect(logger.totalCalls).toBe(3); expect(logger.debug.calls.length).toBe(3); expect(logger.debug.calls[1].args).toEqual([ "http[1]".cyan + ' GET http://example.com/foo/bar/baz' ]); expect(logger.debug.calls[2].args[0]).toMatch(new RegExp(RegExp.escape("http[1]".cyan + ' ' + '204 No Content'.green + ' in ') + '\\d+ms$')); }); }); }); describe("with the `showRequest` option", function() { beforeEach(function() { cliLogger.configured = true; cliLogger.configure({ name: 'scenario', showRequest: true }); }); it("should log HTTP request options with the `showRequest` option", function() { makeRequest(1); expect(logger.totalCalls).toBe(3); expect(logger.debug.calls.length).toBe(3); expect(logger.debug.calls[0].args).toEqual([ "http[1]".cyan + ' GET http://example.com/foo' ]); expect(logger.debug.calls[1].args).toEqual([ 'http[1]'.cyan + ' request options: ' + JSON.stringify(sampleRequestOptions).magenta ]); expect(logger.debug.calls[2].args[0]).toMatch(new RegExp(RegExp.escape("http[1]".cyan + ' ' + '204 No Content'.green + ' in ') + '\\d+ms$')); }); }); describe("with the `showResponseBody` option", function() { beforeEach(function() { cliLogger.configured = true; cliLogger.configure({ name: 'scenario', showResponseBody: true }); }); it("should not log the HTTP response body if there is none", function() { makeRequest(1); expect(logger.totalCalls).toBe(2); expect(logger.debug.calls.length).toBe(2); expect(logger.debug.calls[0].args).toEqual([ "http[1]".cyan + ' GET http://example.com/foo' ]); expect(logger.debug.calls[1].args[0]).toMatch(new RegExp(RegExp.escape("http[1]".cyan + ' ' + '204 No Content'.green + ' in ') + '\\d+ms$')); }); it("should log the HTTP response body", function() { var response = { statusCode: 200, body: { bar: 'baz' } }; makeRequest(1, { response: response }); expect(logger.totalCalls).toBe(3); expect(logger.debug.calls.length).toBe(3); expect(logger.debug.calls[0].args).toEqual([ "http[1]".cyan + ' GET http://example.com/foo' ]); expect(logger.debug.calls[1].args[0]).toMatch(new RegExp(RegExp.escape("http[1]".cyan + ' ' + '200 OK'.green + ' in ') + '\\d+ms$')); expect(logger.debug.calls[2].args).toEqual([ 'http[1]'.cyan + ' response body: ' + JSON.stringify(response.body).magenta ]); }); }); });
mit
deviffy/laravel-kendo-ui
wrappers/php/lib/Kendo/UI/TreeListColumnMenu.php
1556
<?php namespace Kendo\UI; class TreeListColumnMenu extends \Kendo\SerializableObject { //>> Properties /** * If set to true the column menu would allow the user to select (show and hide) treelist columns. By default the column menu allows column selection. * @param boolean $value * @return \Kendo\UI\TreeListColumnMenu */ public function columns($value) { return $this->setProperty('columns', $value); } /** * If set to true the column menu would allow the user to filter the treelist. By default the column menu allows the user to filter if filtering is enabled via the filterable. * @param boolean $value * @return \Kendo\UI\TreeListColumnMenu */ public function filterable($value) { return $this->setProperty('filterable', $value); } /** * If set to true the column menu would allow the user to sort the treelist by the column field. By default the column menu allows the user to sort if sorting is enabled via the sortable option. * @param boolean $value * @return \Kendo\UI\TreeListColumnMenu */ public function sortable($value) { return $this->setProperty('sortable', $value); } /** * The text messages displayed in the column menu. Use it to customize or localize the column menu messages. * @param \Kendo\UI\TreeListColumnMenuMessages|array $value * @return \Kendo\UI\TreeListColumnMenu */ public function messages($value) { return $this->setProperty('messages', $value); } //<< Properties } ?>
mit
cmccullough2/cmv-wab-widgets
wab/2.2/widgets/BasemapGallery/setting/nls/cs/strings.js
1046
define({ "showArcgisBasemaps": "Zahrnout podkladové mapy portálu", "add": "Kliknutím přidáte novou podkladovou mapu.", "edit": "Vlastnosti", "titlePH": "Název podkladové mapy", "thumbnailHint": "Kliknutím na obrázek jej aktualizujete.", "urlPH": "Adresa URL vrstvy", "addlayer": "Přidat podkladovou mapu", "warning": "Nesprávný vstup", "save": "Zpět a Uložit", "back": "Zpět a Zrušit", "addUrl": "Přidat URL", "autoCheck": "Automatická kontrola", "checking": "Probíhá kontrola…", "result": "Úspěšně uloženo", "spError": "Všechny podkladové mapy přidané do galerie musí mít stejný souřadnicový systém.", "invalidTitle1": "Podkladová mapa '", "invalidTitle2": "' již existuje. Zvolte jiný název.", "invalidBasemapUrl1": "Vrstvu tohoto typu nelze použít jako podkladovou mapu.", "invalidBasemapUrl2": "Souřadnicový systém přidávané podkladové mapy se liší od souřadnicového systému současné mapy.", "addBaselayer": "Přidat vrstvu podkladové mapy" });
mit
github/codeql
csharp/ql/test/library-tests/dataflow/ssa/Patterns.cs
869
using System; class Patterns { void Test() { object o = null; if (o is int i1) { Console.WriteLine($"int {i1}"); } else if (o is string s1) { Console.WriteLine($"string {s1}"); } else if (o is var v1) { } switch (o) { case "xyz": break; case int i2 when i2 > 0: Console.WriteLine($"positive {i2}"); break; case int i3: Console.WriteLine($"int {i3}"); break; case string s2: Console.WriteLine($"string {s2}"); break; case var v2: break; default: Console.WriteLine("Something else"); break; } } }
mit
LassieME/Discord.Net
src/Discord.Net.Rest/Entities/Users/RestConnection.cs
1135
using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Model = Discord.API.Connection; namespace Discord { [DebuggerDisplay(@"{DebuggerDisplay,nq}")] public class RestConnection : IConnection { public string Id { get; } public string Type { get; } public string Name { get; } public bool IsRevoked { get; } public IReadOnlyCollection<ulong> IntegrationIds { get; } internal RestConnection(string id, string type, string name, bool isRevoked, IReadOnlyCollection<ulong> integrationIds) { Id = id; Type = type; Name = name; IsRevoked = isRevoked; IntegrationIds = integrationIds; } internal static RestConnection Create(Model model) { return new RestConnection(model.Id, model.Type, model.Name, model.Revoked, model.Integrations.ToImmutableArray()); } public override string ToString() => Name; private string DebuggerDisplay => $"{Name} ({Id}, {Type}{(IsRevoked ? ", Revoked" : "")})"; } }
mit
oliviertassinari/material-ui
packages/mui-icons-material/lib/esm/SearchOffOutlined.js
617
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon([/*#__PURE__*/_jsx("path", { d: "M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3 6.08 3 3.28 5.64 3.03 9h2.02C5.3 6.75 7.18 5 9.5 5 11.99 5 14 7.01 14 9.5S11.99 14 9.5 14c-.17 0-.33-.03-.5-.05v2.02c.17.02.33.03.5.03 1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5z" }, "0"), /*#__PURE__*/_jsx("path", { d: "M6.47 10.82 4 13.29l-2.47-2.47-.71.71L3.29 14 .82 16.47l.71.71L4 14.71l2.47 2.47.71-.71L4.71 14l2.47-2.47z" }, "1")], 'SearchOffOutlined');
mit
maurer/tiamat
samples/Juliet/testcases/CWE90_LDAP_Injection/CWE90_LDAP_Injection__w32_wchar_t_connect_socket_81_bad.cpp
2776
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE90_LDAP_Injection__w32_wchar_t_connect_socket_81_bad.cpp Label Definition File: CWE90_LDAP_Injection__w32.label.xml Template File: sources-sink-81_bad.tmpl.cpp */ /* * @description * CWE: 90 LDAP Injection * BadSource: connect_socket Read data using a connect socket (client side) * GoodSource: Use a fixed string * Sinks: * BadSink : data concatenated into LDAP search, which could result in LDAP Injection * Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference * * */ #ifndef OMITBAD #include "std_testcase.h" #include "CWE90_LDAP_Injection__w32_wchar_t_connect_socket_81.h" #include <windows.h> #include <Winldap.h> #pragma comment(lib, "wldap32") namespace CWE90_LDAP_Injection__w32_wchar_t_connect_socket_81 { void CWE90_LDAP_Injection__w32_wchar_t_connect_socket_81_bad::action(wchar_t * data) const { { LDAP* pLdapConnection = NULL; ULONG connectSuccess = 0L; ULONG searchSuccess = 0L; LDAPMessage *pMessage = NULL; wchar_t filter[256]; /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection*/ _snwprintf(filter, 256-1, L"(cn=%s)", data); pLdapConnection = ldap_initW(L"localhost", LDAP_PORT); if (pLdapConnection == NULL) { printLine("Initialization failed"); exit(1); } connectSuccess = ldap_connect(pLdapConnection, NULL); if (connectSuccess != LDAP_SUCCESS) { printLine("Connection failed"); exit(1); } searchSuccess = ldap_search_ext_sW( pLdapConnection, L"base", LDAP_SCOPE_SUBTREE, filter, NULL, 0, NULL, NULL, LDAP_NO_LIMIT, LDAP_NO_LIMIT, &pMessage); if (searchSuccess != LDAP_SUCCESS) { printLine("Search failed"); if (pMessage != NULL) { ldap_msgfree(pMessage); } exit(1); } /* Typically you would do something with the search results, but this is a test case and we can ignore them */ /* Free the results to avoid incidentals */ if (pMessage != NULL) { ldap_msgfree(pMessage); } /* Close the connection */ ldap_unbind(pLdapConnection); } } } #endif /* OMITBAD */
mit
johnsietsma/HackerRankChallenges
src/c++/introduction/ForLoop.cpp
792
#include <iostream> #include <cstdio> using namespace std; #include <iostream> #include <cstdio> using namespace std; void print_number(int input) { if (input == 1) std::cout << "one"; else if (input == 2) std::cout << "two"; else if (input == 3) std::cout << "three"; else if (input == 4) std::cout << "four"; else if (input == 5) std::cout << "five"; else if (input == 6) std::cout << "six"; else if (input == 7) std::cout << "seven"; else if (input == 8) std::cout << "eight"; else if (input == 9) std::cout << "nine"; else if (input % 2 == 0) std::cout << "even"; else std::cout << "odd"; std::cout << std::endl; } int main() { int input1; int input2; std::cin >> input1; std::cin >> input2; for (int i = input1; i <= input2; i++) { print_number(i); } return 0; }
mit
almera7/Movie-rental
app/cache/prod/twig/8f/e0/e3e93fa2f035d6ebe8a35f287f3b355ff3089a8760e71ca294f8ae2f0d3d.php
2448
<?php /* TwigBundle:Exception:exception.xml.twig */ class __TwigTemplate_8fe0e3e93fa2f035d6ebe8a35f287f3b355ff3089a8760e71ca294f8ae2f0d3d extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 echo "<?xml version=\"1.0\" encoding=\""; echo twig_escape_filter($this->env, $this->env->getCharset(), "html", null, true); echo "\" ?> <error code=\""; // line 3 echo twig_escape_filter($this->env, (isset($context["status_code"]) ? $context["status_code"] : null), "html", null, true); echo "\" message=\""; echo twig_escape_filter($this->env, (isset($context["status_text"]) ? $context["status_text"] : null), "html", null, true); echo "\"> "; // line 4 $context['_parent'] = (array) $context; $context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["exception"]) ? $context["exception"] : null), "toarray", array())); foreach ($context['_seq'] as $context["_key"] => $context["e"]) { // line 5 echo " <exception class=\""; echo twig_escape_filter($this->env, $this->getAttribute($context["e"], "class", array()), "html", null, true); echo "\" message=\""; echo twig_escape_filter($this->env, $this->getAttribute($context["e"], "message", array()), "html", null, true); echo "\"> "; // line 6 $this->env->loadTemplate("TwigBundle:Exception:traces.xml.twig")->display(array("exception" => $context["e"])); // line 7 echo " </exception> "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['e'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 9 echo "</error> "; } public function getTemplateName() { return "TwigBundle:Exception:exception.xml.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 51 => 9, 44 => 7, 42 => 6, 35 => 5, 31 => 4, 25 => 3, 19 => 1,); } }
mit
PaymentSuite/paymentsuite
src/PaymentSuite/RedsysBundle/Tests/RedsysSignatureTest.php
686
<?php namespace PaymentSuite\RedsysBundle\Tests; use PaymentSuite\RedsysBundle\RedsysSignature; use PHPUnit\Framework\TestCase; class RedsysSignatureTest extends TestCase { public function testToString() { $signature = new RedsysSignature('12345'); $this->assertEquals('12345', $signature->__toString()); } public function testMatch() { $signature = new RedsysSignature('12345'); $signatureEquals = new RedsysSignature('12345'); $signatureDifferent = new RedsysSignature('6789'); $this->assertTrue($signature->match($signatureEquals)); $this->assertFalse($signature->match($signatureDifferent)); } }
mit
nycdot/transam_core
spec/models/activity_log_spec.rb
535
require 'rails_helper' RSpec.describe ActivityLog, :type => :model do let(:test_log) { create(:activity_log) } describe 'associations' do it 'has an org' do expect(test_log).to belong_to(:organization) end it 'has a user' do expect(test_log).to belong_to(:user) end end describe 'validations' do it 'must have an org' do test_log.organization = nil expect(test_log.valid?).to be false end end it '.to_s' do expect(test_log.to_s).to eq(test_log.item_type) end end
mit
djeik/goto
grading/typing/valid/unops.go
620
package main func base_types() { var ( a int b float64 c rune d string e bool ) // Unary plus println(+a) println(+b) println(+c) // Unary negation println(-a) println(-b) println(-c) // Unary bit-not println(^a) println(^c) // Unary logical not println(!e) } func type_aliases() { type ( t1 int t2 float64 t3 rune t4 string t5 bool ) var ( a t1 b t2 c t3 d t4 e t5 ) // Unary plus println(+a) println(+b) println(+c) // Unary negation println(-a) println(-b) println(-c) // Unary bit-not println(^a) println(^c) // Unary logical not println(!e) }
mit
cosnics/cosnics
src/Chamilo/Core/Repository/ContentObject/Rubric/Domain/Exceptions/InvalidRubricDataException.php
1045
<?php namespace Chamilo\Core\Repository\ContentObject\Rubric\Domain\Exceptions; use Chamilo\Core\Repository\ContentObject\Rubric\Storage\Entity\RubricData; /** * @package Chamilo\Core\Repository\ContentObject\Rubric\Domain\Exceptions * * @author Sven Vanpoucke - Hogeschool Gent */ class InvalidRubricDataException extends RubricStructureException { /** * InvalidRubricDataException constructor. * * @param string $type * @param int $id * @param RubricData $expectedRubricData * @param RubricData $givenRubricData */ public function __construct( string $type, int $id, RubricData $expectedRubricData, RubricData $givenRubricData = null ) { parent::__construct( sprintf( 'The %s with id %s was expected to have rubric data %s instead rubric data %s was given', $type, $id, $expectedRubricData->getId(), $givenRubricData instanceof RubricData ? $givenRubricData->getId() : 'null' ) ); } }
mit
smoench/SimpSpector
src/js/components/Markdown.js
760
import React from "react"; import 'prismjs/components/prism-core'; import 'prismjs/components/prism-markup'; import 'prismjs/components/prism-twig'; import 'prismjs/components/prism-clike'; import 'prismjs/components/prism-php'; import 'prismjs/plugins/line-highlight/prism-line-highlight'; import 'prismjs/plugins/line-numbers/prism-line-numbers'; import 'prismjs/themes/prism.css'; import 'prismjs/plugins/line-highlight/prism-line-highlight.css'; import 'prismjs/plugins/line-numbers/prism-line-numbers.css'; export default class Markdown extends React.Component { componentDidMount() { Prism.highlightAll(); } render() { return ( <div ref={el => this.el = el} dangerouslySetInnerHTML={{__html: this.props.children}} /> ); } }
mit
Yahnoosh/azure-sdk-for-net
src/Batch/Client/Src/Azure.Batch/GeneratedProtocol/IAccountOperations.cs
4038
// Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Batch.Protocol { using Microsoft.Rest.Azure; using Models; /// <summary> /// AccountOperations operations. /// </summary> public partial interface IAccountOperations { /// <summary> /// Lists all node agent SKUs supported by the Azure Batch service. /// </summary> /// <param name='accountListNodeAgentSkusOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NodeAgentSku>,AccountListNodeAgentSkusHeaders>> ListNodeAgentSkusWithHttpMessagesAsync(AccountListNodeAgentSkusOptions accountListNodeAgentSkusOptions = default(AccountListNodeAgentSkusOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Lists all node agent SKUs supported by the Azure Batch service. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='accountListNodeAgentSkusNextOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NodeAgentSku>,AccountListNodeAgentSkusHeaders>> ListNodeAgentSkusNextWithHttpMessagesAsync(string nextPageLink, AccountListNodeAgentSkusNextOptions accountListNodeAgentSkusNextOptions = default(AccountListNodeAgentSkusNextOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } }
mit
marcCanipel/xjavascript
exercises/crypto-square/crypto-square.spec.js
1717
var Crypto = require('./crypto-square'); describe('Crypto',function() { it('normalize strange characters',function() { var crypto = new Crypto('s#$%^&plunk'); expect(crypto.normalizePlaintext()).toEqual('splunk'); }); xit('normalize numbers',function() { var crypto = new Crypto('1, 2, 3 GO!'); expect(crypto.normalizePlaintext()).toEqual('123go'); }); xit('size of small square',function() { var crypto = new Crypto('1234'); expect(crypto.size()).toEqual(2); }); xit('size of small square with additional non-nuber chars',function() { var crypto = new Crypto('1 2 3 4'); expect(crypto.size()).toEqual(2); }); xit('size of slightly larger square',function() { var crypto = new Crypto('123456789'); expect(crypto.size()).toEqual(3); }); xit('size of non-perfect square',function() { var crypto = new Crypto('123456789abc'); expect(crypto.size()).toEqual(4); }); xit('plain text segments',function() { var crypto = new Crypto('Never vex thine heart with idle woes'); expect(crypto.plaintextSegments()).toEqual(['neverv', 'exthin', 'eheart', 'withid', 'lewoes']); }); xit('plain text segments',function() { var crypto = new Crypto('ZOMG! ZOMBIES!!!'); expect(crypto.plaintextSegments()).toEqual(['zomg', 'zomb', 'ies']); }); xit('cipher text',function() { var crypto = new Crypto('Time is an illusion. Lunchtime doubly so.'); expect(crypto.ciphertext()).toEqual('tasneyinicdsmiohooelntuillibsuuml'); }); xit('cipher text',function() { var crypto = new Crypto('We all know interspecies romance is weird.'); expect(crypto.ciphertext()).toEqual('wneiaweoreneawssciliprerlneoidktcms'); }); });
mit
Polynomial-C/PAmix
src/sinkinputentry.cpp
2995
#include <entry.hpp> void SinkInputEntry::update(const pa_sink_input_info *info) { // general vars const char *name = pa_proplist_gets(info->proplist, PA_PROP_APPLICATION_NAME); m_Name = name != nullptr ? name : info->name; m_Index = info->index; m_Mute = info->mute; m_PAVolume = info->volume; m_PAChannelMap = info->channel_map; m_Kill = false; // stream vars m_Device = info->sink; } void SinkInputEntry::setVolume(const int channel, const pa_volume_t volume) { mainloop_lockguard lg(interface->getPAMainloop()); pa_cvolume *cvol = &m_PAVolume; if (m_Lock) pa_cvolume_set(cvol, cvol->channels, volume); else cvol->values[channel] = volume; pa_operation *op = pa_context_set_sink_input_volume(interface->getPAContext(), m_Index, cvol, &PAInterface::cb_success, interface); while (pa_operation_get_state(op) == PA_OPERATION_RUNNING) pa_threaded_mainloop_wait(interface->getPAMainloop()); pa_operation_unref(op); } void SinkInputEntry::setMute(bool mute) { mainloop_lockguard lg(interface->getPAMainloop()); pa_operation *op = pa_context_set_sink_input_mute(interface->getPAContext(), m_Index, mute, &PAInterface::cb_success, interface); while (pa_operation_get_state(op) == PA_OPERATION_RUNNING) pa_threaded_mainloop_wait(interface->getPAMainloop()); pa_operation_unref(op); } void SinkInputEntry::cycleSwitch(bool increment) { pamix_entry_iter_t sink = interface->getSinks().find(m_Device); if (increment) sink++; else { if (sink == interface->getSinks().begin()) sink = std::next(sink, interface->getSinks().size() - 1); else sink--; } if (sink == interface->getSinks().end()) sink = interface->getSinks().begin(); pa_operation *op = pa_context_move_sink_input_by_index(interface->getPAContext(), m_Index, sink->second->m_Index, &PAInterface::cb_success, interface); while (pa_operation_get_state(op) == PA_OPERATION_RUNNING) pa_threaded_mainloop_wait(interface->getPAMainloop()); pa_operation_unref(op); } void SinkInputEntry::move(uint32_t idx) { mainloop_lockguard lg(interface->getPAMainloop()); pa_operation *op = pa_context_move_sink_input_by_index(interface->getPAContext(), m_Index, idx, &PAInterface::cb_success, interface); while (pa_operation_get_state(op) == PA_OPERATION_RUNNING) pa_threaded_mainloop_wait(interface->getPAMainloop()); pa_operation_unref(op); } void SinkInputEntry::kill() { mainloop_lockguard lg(interface->getPAMainloop()); pa_operation *op = pa_context_kill_sink_input(interface->getPAContext(), m_Index, &PAInterface::cb_success, interface); while (pa_operation_get_state(op) == PA_OPERATION_RUNNING) pa_threaded_mainloop_wait(interface->getPAMainloop()); pa_operation_unref(op); }
mit
BrianAdams/openrov-cockpit
src/plugins/mobile-ui/index.js
223
function mobileUi( name, deps ) { console.log( 'Mobile UI plugin loaded.' ); this.plugin = { name: "mobile-ui", type: "theme" }; } module.exports = function( name,deps ) { return new mobileUi( name, deps ); };
mit
FurryHead/Server
src/org/hyperion/rs2/model/NPCDefinition.java
567
package org.hyperion.rs2.model; /** * <p>Represents a type of NPC.</p> * @author Graham Edgecombe * */ public class NPCDefinition { /** * Gets an npc definition by its id. * @param id The id. * @return The definition. */ public static NPCDefinition forId(int id) { return new NPCDefinition(id); } /** * The id. */ private int id; /** * Creates the definition. * @param id The id. */ private NPCDefinition(int id) { this.id = id; } /** * Gets the id. * @return The id. */ public int getId() { return this.id; } }
mit
WesleyyC/Restaurant-Revenue-Prediction
Ari/preprocessing/feat_drop.py
963
import numpy as np import pandas as pd ############################################################################### # Load data df_train = pd.read_csv("train_numerical_head.csv") df_train.head() df_test = pd.read_csv("test_numerical_head.csv") df_train.head() ############################################################################### # Drop features p_to_drop = [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0] for i in range(5, 42): if p_to_drop[i-5] == 0: df_train = df_train.drop(i, axis=1) df_test = df_test.drop(i axis=1) ############################################################################### # Save to File result = np.asarray(result) np.savetxt("result_train.csv", df_train, delimiter=",") np.savetxt("result_test.csv", df_test, delimiter=",") #plot_r2(y, y_pred2, "Performance of GradientBoostingRegressor") #plt.show() #r2_score(y, y_pred2)
mit
rtoal/polyglot
python/memoized_fibonacci.py
278
def memoized(f): cache = {} def wrapper(*args): if args in cache: return cache[args] cache[args] = f(*args) return cache[args] return wrapper @memoized def fib(n): return 1 if n <= 1 else fib(n-1) + fib(n-2) print(fib(100))
mit
tkerola/chainer
tests/chainermn_tests/links_tests/test_batch_normalization.py
11195
import chainer import chainer.testing import chainer.utils import mpi4py.MPI import numpy import pytest from chainermn.communicators.naive_communicator import NaiveCommunicator from chainermn.communicators.pure_nccl_communicator import PureNcclCommunicator from chainermn.links import MultiNodeBatchNormalization from chainermn import nccl mpi_comm = mpi4py.MPI.COMM_WORLD class ModelNormalBN(chainer.Chain): def __init__(self, n_in=3, n_units=3, n_out=2): super(ModelNormalBN, self).__init__() with self.init_scope(): self.l1 = chainer.links.Linear(n_in, n_units, nobias=True) self.bn1 = chainer.links.BatchNormalization(n_units) self.l2 = chainer.links.Linear(n_in, n_units, nobias=True) self.bn2 = chainer.links.BatchNormalization(n_units) self.l3 = chainer.links.Linear(n_in, n_out) self.train = True def __call__(self, x): h = chainer.functions.relu(self.bn1(self.l1(x))) h = chainer.functions.relu(self.bn2(self.l2(h))) return self.l3(h) class ModelDistributedBN(chainer.Chain): def __init__(self, comm, n_in=3, n_units=3, n_out=2, backend='auto'): super(ModelDistributedBN, self).__init__() with self.init_scope(): self.l1 = chainer.links.Linear(n_in, n_units, nobias=True) self.bn1 = MultiNodeBatchNormalization( n_units, comm, communication_backend=backend) self.l2 = chainer.links.Linear(n_in, n_units, nobias=True) self.bn2 = MultiNodeBatchNormalization( n_units, comm, communication_backend=backend) self.l3 = chainer.links.Linear(n_in, n_out) self.train = True def __call__(self, x): h = chainer.functions.relu(self.bn1(self.l1(x))) h = chainer.functions.relu(self.bn2(self.l2(h))) return self.l3(h) def check_multi_node_bn(comm, use_gpu=False, backend='auto', dtype=numpy.float32): """Tests correctness of MultiNodeBatchNormalization. This test verifies MultiNodeBatchNormalization by comparing the following four configurations. (1) Single worker, normal BatchNormalization (2) Multiple workers, normal BatchNormalization (3) Single worker, MultiNodeBatchNormalization (4) Multiple workers, MultiNodeBatchNormalization Single worker: only using the result of worker 0, which uses the whole batch. Multiple workers: Each worker uses the 1/n part of the whole batch, where n is the number of nodes, and gradient is aggregated. This test conducts the forward and backward computation once for the deterministic model parameters and an input batch, and checks the gradients of parameters. The purpose of MultiNodeBatchNormalization is to make the results of (4) to be exactly same as (1). Therefore, the essential part is to check that the results of (1) and (4) are the same. The results of (3) should also be also same as them. In contrast, the results of (2) is not necessarily always same as them, and we can expect that it is almost always different. Therefore, we also check that the results of (2) is different from them, to see that this test working correctly. """ local_batchsize = 8 global_batchsize = local_batchsize * comm.size ndim = 3 numpy.random.seed(71) x = numpy.random.random( (global_batchsize, ndim)).astype(numpy.float32) y = numpy.random.randint( 0, 1, size=global_batchsize, dtype=numpy.int32) x_local = comm.mpi_comm.scatter( x.reshape(comm.size, local_batchsize, ndim)) y_local = comm.mpi_comm.scatter( y.reshape(comm.size, local_batchsize)) io_dtype = dtype l_dtype = dtype bn_dtype = dtype if dtype == chainer.mixed16: io_dtype = numpy.float16 l_dtype = numpy.float16 bn_dtype = numpy.float32 x = x.astype(io_dtype) x_local = x_local.astype(io_dtype) if use_gpu: x = chainer.cuda.to_gpu(x) y = chainer.cuda.to_gpu(y) x_local = chainer.cuda.to_gpu(x_local) y_local = chainer.cuda.to_gpu(y_local) cls = chainer.links.Classifier with chainer.using_config('dtype', dtype): # Single worker m1 = cls(ModelNormalBN()) # Multi worker, Ghost BN m2 = cls(ModelNormalBN()) # Single worker, MNBN m3 = cls(ModelDistributedBN(comm, backend=backend)) # Multi worker, MNBN m4 = cls(ModelDistributedBN(comm, backend=backend)) # NOTE: m1, m3 and m4 should behave in the same way. # m2 may be different. if use_gpu: m1.to_gpu() m2.to_gpu() m3.to_gpu() m4.to_gpu() m2.copyparams(m1) m3.copyparams(m1) m4.copyparams(m1) l1 = m1(x, y) m1.cleargrads() l1.backward() l2 = m2(x_local, y_local) m2.cleargrads() l2.backward() comm.allreduce_grad(m2) l3 = m3(x, y) m3.cleargrads() l3.backward() l4 = m4(x_local, y_local) m4.cleargrads() l4.backward() comm.allreduce_grad(m4) if comm.rank == 0: for p1, p2, p3, p4 in zip( sorted(m1.namedparams()), sorted(m2.namedparams()), sorted(m3.namedparams()), sorted(m4.namedparams())): name = p1[0] assert (p2[0] == name) assert (p3[0] == name) assert (p4[0] == name) if '/l' in name: param_dtype = l_dtype else: param_dtype = bn_dtype assert (p1[1].data.dtype == param_dtype) assert (p2[1].data.dtype == param_dtype) assert (p3[1].data.dtype == param_dtype) assert (p4[1].data.dtype == param_dtype) assert_option = {'atol': 1e-4, 'rtol': 1e-3} if param_dtype == numpy.float16: assert_option = {'atol': 1e-2, 'rtol': 1e-2} chainer.testing.assert_allclose(p1[1].grad, p3[1].grad, **assert_option) chainer.testing.assert_allclose(p1[1].grad, p4[1].grad, **assert_option) # This is to see that this test is valid. if comm.size >= 2: assert_not_allclose(p1[1].grad, p2[1].grad) def check_link_copyable(comm): # Regression test for #5854 bn0 = ModelDistributedBN(comm) bn1 = bn0.copy(mode='copy') assert bn1 is not None bn2 = MultiNodeBatchNormalization(10, comm) bn3 = bn2.copy(mode='copy') assert bn3 is not None def assert_not_allclose(x, y, atol=1e-5, rtol=1e-4, verbose=True): x = chainer.cuda.to_cpu(chainer.utils.force_array(x)) y = chainer.cuda.to_cpu(chainer.utils.force_array(y)) with pytest.raises(AssertionError): chainer.testing.assert_allclose( x, y, atol=atol, rtol=rtol, verbose=verbose) def create_communicator(communicator_class, mpi_comm, use_gpu): if PureNcclCommunicator == communicator_class: use_nccl = True else: use_nccl = False if use_gpu and not use_nccl and nccl.get_build_version() < 2000: pytest.skip('This test requires NCCL version >= 2.0') communicator = communicator_class(mpi_comm) if use_gpu: chainer.cuda.get_device_from_id(communicator.intra_rank).use() return communicator def test_version_check(): comm = create_communicator(NaiveCommunicator, mpi_comm, use_gpu=False) if chainer.__version__.startswith('1.'): with pytest.raises(RuntimeError): MultiNodeBatchNormalization(3, comm) else: # Expecting no exceptions MultiNodeBatchNormalization(3, comm) @pytest.mark.parametrize(('communicator_class', 'backend', 'dtype'), [ (NaiveCommunicator, 'mpi', numpy.float16), (NaiveCommunicator, 'mpi', numpy.float32), (NaiveCommunicator, 'mpi', chainer.mixed16)]) def test_multi_node_bn_cpu(communicator_class, backend, dtype): comm = create_communicator(communicator_class, mpi_comm, use_gpu=False) check_multi_node_bn(comm, backend=backend, dtype=dtype) check_link_copyable(comm) comm.mpi_comm.barrier() @pytest.mark.parametrize(('communicator_class', 'backend', 'dtype'), [ (NaiveCommunicator, 'mpi', numpy.float32), (PureNcclCommunicator, 'mpi', numpy.float32), (PureNcclCommunicator, 'mpi', numpy.float16), (PureNcclCommunicator, 'mpi', chainer.mixed16), (PureNcclCommunicator, 'nccl', numpy.float32), (PureNcclCommunicator, 'nccl', numpy.float16), (PureNcclCommunicator, 'nccl', chainer.mixed16)]) @chainer.testing.attr.gpu def test_multi_node_bn_gpu(communicator_class, backend, dtype): comm = create_communicator(communicator_class, mpi_comm, use_gpu=True) check_multi_node_bn(comm, use_gpu=True, backend=backend, dtype=dtype) check_link_copyable(comm) chainer.cuda.Stream.null.synchronize() comm.mpi_comm.barrier() if hasattr(comm, 'nccl_comm'): comm.nccl_comm.destroy() @pytest.mark.parametrize(('communicator_class', 'backend'), [ (NaiveCommunicator, 'mpi'), (NaiveCommunicator, 'auto')]) def test_support_communication_backend_cpu(communicator_class, backend): n_units = 1 comm = create_communicator(communicator_class, mpi_comm, use_gpu=False) MultiNodeBatchNormalization(n_units, comm, communication_backend=backend) @pytest.mark.parametrize(('communicator_class', 'backend'), [ (NaiveCommunicator, 'nccl'), (NaiveCommunicator, 'dummy')]) def test_unsupport_communication_backend_cpu(communicator_class, backend): n_units = 1 comm = create_communicator(communicator_class, mpi_comm, use_gpu=False) with pytest.raises(ValueError): MultiNodeBatchNormalization(n_units, comm, communication_backend=backend) @pytest.mark.parametrize(('communicator_class', 'backend'), [ (NaiveCommunicator, 'mpi'), (NaiveCommunicator, 'auto'), (PureNcclCommunicator, 'mpi'), (PureNcclCommunicator, 'nccl'), (PureNcclCommunicator, 'auto')]) @chainer.testing.attr.gpu def test_support_communication_backend_gpu(communicator_class, backend): n_units = 1 comm = create_communicator(communicator_class, mpi_comm, use_gpu=True) MultiNodeBatchNormalization(n_units, comm, communication_backend=backend) @pytest.mark.parametrize(('communicator_class', 'backend'), [ (NaiveCommunicator, 'nccl'), (NaiveCommunicator, 'dummy'), (PureNcclCommunicator, 'dummy')]) @chainer.testing.attr.gpu def test_unsupport_communication_backend_gpu(communicator_class, backend): n_units = 1 comm = create_communicator(communicator_class, mpi_comm, use_gpu=True) with pytest.raises(ValueError): MultiNodeBatchNormalization(n_units, comm, communication_backend=backend)
mit
qrb/riotjs
test/specs/compiler/parsers/js/test-alt.js
659
// alternative to nested custom tags using the comment hack. // as the compiler expects only blanks after closing the tag, the inline // comment following the first closing tag prevents the compiler sees it. // UPDATE: hack NOT NECESSARY with the 0 indent restriction. riot.tag2('treeitem', '<div class="{bold: isFolder()}" onclick="{toggle}" ondblclick="{changeType}"> {name} <span if="{isFolder()}">[{open ? \'-\' : \'+\'}]</span> </div> <ul if="{isFolder()}" show="{isFolder() && open}"> <li each="{child, i in nodes}"> <treeitem data="{child}"></treeitem> </li> <li onclick="{addChild}">+</li> </ul>', '', '', function(opts) { var self = this }, '{ }');
mit
kdcllc/Chavah
Chavah.NetCore/wwwroot/js/Controllers/ShareThanksController.ts
763
namespace BitShuva.Chavah { export class ShareThanksController { static $inject = [ "$routeParams", ]; readonly artist: string | null; constructor($routeParams: ng.route.IRouteParamsService) { this.artist = $routeParams["artist"]; } get donateUrl(): string { if (this.artist) { return `#/donate/${encodeURIComponent(this.artist)}`; } return "#/donate"; } get donateText(): string { if (this.artist) { return `Donate to ${this.artist}`; } return "Donate to the artists"; } } App.controller("ShareThanksController", ShareThanksController); }
mit
Diaks/git_repo-dashboard
app/cache.old/prod/annotations/1401ac6686cc754bbe82736c33282addb3aa4a11$totalpmd.cache.php
264
<?php return unserialize('a:1:{i:0;O:27:"Doctrine\\ORM\\Mapping\\Column":9:{s:4:"name";s:8:"TotalPMD";s:4:"type";s:5:"float";s:6:"length";N;s:9:"precision";i:24;s:5:"scale";i:0;s:6:"unique";b:0;s:8:"nullable";b:1;s:7:"options";a:0:{}s:16:"columnDefinition";N;}}');
mit
daviderwin/fiche
fiche-scroll.js
1975
var ficheScroll = function (e, f, args) { // cache the fiche this.f = f; // cache the jquery element this.$e = $(e); this.$e.css({ position: 'relative', overflow: 'hidden' }); this.$viewable = $('<div></div>'); this.$viewable.addClass('fiche-scroll-viewable'); this.$viewable.css({ position: 'absolute' }); this.$e.append(this.$viewable); // presets that existed before the element was a fiche-scroll // this allows the dev to set a height or width and have the ratio // work off of that this.presets = { height: this.$e.innerHeight(), width: this.$e.innerWidth() }; this.conform(); $(this.f).on('surfaceUpdate', {'this': this}, this.conform); }; // make the scroll element conform to the fiche ficheScroll.prototype.conform = function (e) { var self = this; if (e && typeof e.data !== 'undefined') { self = e.data.this; } // if width preset, go off that for the size if (self.presets.width) { self.width = self.$e.innerWidth(); self.height = self.width / self.f.surfaceSize().aspect; } // if width preset, go off that for the size if (self.presets.height) { self.height = self.$e.innerHeight(); self.height = self.height * self.f.surfaceSize().aspect; } self.$e.css({ width: self.width, height: self.height }); self.drawViewable(self); }; // draw the viewable area box in the scroller ficheScroll.prototype.drawViewable = function (self) { var surfaceSize = this.f.surfaceSize(), viewportSize = this.f.viewportSize(), ratio = this.height / surfaceSize.height, viewableHeight = this.height * ratio, viewableWidth = this.width * ratio, viewableTop = this.f.surface.top * ratio * -1, viewableLeft = this.f.surface.left * ratio * -1; this.$viewable.height = viewableHeight; this.$viewable.width = viewableWidth; this.$viewable.css({ height: viewableHeight, width: viewableWidth, top: viewableTop, left: viewableLeft }); }; ficheScroll.prototype.getRatio = function () { };
mit
egensolutions/data-viewer
src/app/features/infotable/infotable.controller.js
346
(function (angular) { 'use strict'; angular .module('egen.app.infotable') .controller('InfoTableController', InfoTableController); function InfoTableController(dataService) { var infoTableVm = this; infoTableVm.tableContent=null; infoTableVm.tableContent = dataService; } })(angular);
mit
Eclo/azure-iot-sdks
node/common/core/test/_shared_access_signature_test.js
9823
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. 'use strict'; var assert = require('chai').assert; var ArgumentError = require('../lib/errors.js').ArgumentError; var FormatError = require('../lib/errors.js').FormatError; var SharedAccessSignature = require('../lib/shared_access_signature.js'); var key = new Buffer('password').toString('base64'); describe('SharedAccessSignature', function () { describe('#create', function () { /*Tests_SRS_NODE_COMMON_SAS_05_009: [If resourceUri, key, or expiry are falsy (i.e., undefined, null, or empty), create shall throw ReferenceException.]*/ it('throws when \'resourceUri\' is falsy', function () { throwsWhenFalsy('resourceUri'); }); /*Tests_SRS_NODE_COMMON_SAS_05_009: [If resourceUri, key, or expiry are falsy (i.e., undefined, null, or empty), create shall throw ReferenceException.]*/ it('throws when \'key\' is falsy', function () { throwsWhenFalsy('key'); }); /*Tests_SRS_NODE_COMMON_SAS_05_009: [If resourceUri, key, or expiry are falsy (i.e., undefined, null, or empty), create shall throw ReferenceException.]*/ it('throws when \'expiry\' is falsy', function () { throwsWhenFalsy('expiry'); }); function throwsWhenFalsy(argName) { var args = { resourceUri: 'r', keyName: 'n', key: 'k', expiry: 1 }; function createSharedAccessSignature() { return SharedAccessSignature.create(args.resourceUri, args.keyName, args.key, args.expiry); } function throws(element) { args[argName] = element; var messageMatch = new RegExp('^Argument \'' + argName + '\' is ' + element); assert.throws(createSharedAccessSignature, ReferenceError, messageMatch); } [undefined, null, '', 0].forEach(throws); } /*Tests_SRS_NODE_COMMON_SAS_05_008: [The create method shall accept four arguments: resourceUri - the resource URI to encode into the token keyName - an identifier associated with the key key - a base64-encoded key value expiry - an integer value representing the number of seconds since the epoch 00:00:00 UTC on 1 January 1970.]*/ /*Tests_SRS_NODE_COMMON_SAS_05_010: [The create method shall create a new instance of SharedAccessSignature with properties: sr, sig, se, and optionally skn.]*/ it('returns a SharedAccessSignature', function () { var sas = SharedAccessSignature.create('uri', 'name', 'key', 123); assert.instanceOf(sas, SharedAccessSignature); assert.includeMembers(Object.keys(sas), ['sr', 'sig', 'se', 'skn']); }); /*Tests_SRS_NODE_COMMON_SAS_05_011: [The sr property shall have the value of resourceUri.]*/ it('populates sr with the value of resourceUri', function () { var sas = SharedAccessSignature.create('uri', 'name', 'key', 123); assert.propertyVal(sas, 'sr', 'uri'); }); /*Tests_SRS_NODE_COMMON_SAS_05_013: [<signature> shall be an HMAC-SHA256 hash of the value <stringToSign>, which is then base64-encoded.]*/ /*Tests_SRS_NODE_COMMON_SAS_05_014: [<stringToSign> shall be a concatenation of resourceUri + '\n' + expiry.]*/ /*Tests_SRS_NODE_COMMON_SAS_05_012: [The sig property shall be the result of URL-encoding the value <signature>.]*/ it('populates sig with the signature generated from resourceUri and expiry', function () { var sas = SharedAccessSignature.create('uri', 'name', key, 12345); assert.propertyVal(sas, 'sig', 'kcWxXAK2OAaAoq2oCkaGzX2NMqDB8nCyNuq2fPYCDhk%3D'); }); /*Tests_SRS_NODE_COMMON_SAS_05_017: [<urlEncodedKeyName> shall be the URL-encoded value of keyName.]*/ /*Tests_SRS_NODE_COMMON_SAS_05_016: [The skn property shall be the value <urlEncodedKeyName>.]*/ it('populates skn with the URL-encoded value of keyName', function () { var sas = SharedAccessSignature.create('uri', 'encode(\'Me\')', key, 12345); assert.propertyVal(sas, 'skn', 'encode%28%27Me%27%29'); }); /*Tests_SRS_NODE_COMMON_SAS_05_015: [The se property shall have the value of expiry.]*/ it('populates se with the value of expiry', function () { var sas = SharedAccessSignature.create('uri', 'encode(\'Me\')', key, 12345); assert.propertyVal(sas, 'se', 12345); }); /*Tests_SRS_NODE_COMMON_SAS_05_018: [If the keyName argument to the create method was falsy, skn shall not be defined.]*/ it('does not populate skn if keyName wasn\'t given', function () { ['', null, undefined].forEach(function (falsyKeyName) { var sas = SharedAccessSignature.create('uri', falsyKeyName, 'key', 12345); assert.notProperty(sas, 'skn'); }); }); }); describe('#extend', function () { it('throws when \'expiry\' is falsy', function () { var sas = SharedAccessSignature.create('uri', 'n', 'key', 12345); ['', null, undefined].forEach(function (expiry) { assert.throws(function () { sas.extend(expiry); }, ReferenceError, 'expiry is ' + expiry); }); }); it('extends when \'expiry\' is an integer', function () { var sas = SharedAccessSignature.create('uri', 'n', 'key', 12345); sas.extend(12345); assert.propertyVal(sas,'se',12345); }); }); describe('#parse', function () { /*Tests_SRS_NODE_COMMON_SAS_05_005: [The parse method shall throw FormatError if the shared access signature string does not start with 'SharedAccessSignature<space>'.]*/ it('throws if signature doesn\'t start with \'SharedAccessSignature<space>\'', function () { [ 'blah', // no 'SharedAccessSignature' ' SharedAccessSignature field', // space before 'SharedAccessSignature' 'SharedAccessSignature field', // two spaces after 'SharedAccessSignature' 'SharedAccessSignature fie ld' // space in the fields ].forEach(function (sas) { assert.throws(function () { return SharedAccessSignature.parse(sas); }, FormatError, 'Malformed signature'); }); }); /*Tests_SRS_NODE_COMMON_SAS_05_006: [The parse method shall throw ArgumentError if any of fields in the requiredFields argument are not found in the source argument.]*/ ['sr', 'sig', 'skn', 'se'].forEach(function (key) { it('throws if shared access signature is missing ' + key, function () { assert.throws(function () { SharedAccessSignature.parse(utils.makeStringWithout(key), utils.fields()); }, ArgumentError, utils.errorMessage(key)); }); }); /*Tests_SRS_NODE_COMMON_SAS_05_002: [The parse method shall create a new instance of SharedAccessSignature.]*/ /*Tests_SRS_NODE_COMMON_SAS_05_003: [It shall accept a string argument of the form 'name=value[&name=value…]' and for each name extracted it shall create a new property on the SharedAccessSignature object instance.]*/ /*Tests_SRS_NODE_COMMON_SAS_05_004: [The value of the property shall be the value extracted from the source argument for the corresponding name.]*/ /*Tests_SRS_NODE_COMMON_SAS_05_007: [The generated SharedAccessSignature object shall be returned to the caller.]*/ it('returns an object with all the properties of the shared access signature', function () { var sas = SharedAccessSignature.parse(utils.makeString()); assert.deepEqual(utils.makePlainObject(sas), utils.properties); }); /*Tests_SRS_NODE_COMMON_SAS_05_001: [The input argument source shall be converted to string if necessary.]*/ it('accepts an argument that can be converted to String', function () { var obj = { toString: function () { return utils.makeString(); } }; var sas = SharedAccessSignature.parse(obj); assert.deepEqual(utils.makePlainObject(sas), utils.properties); }); }); describe('#toString', function () { /*Tests_SRS_NODE_COMMON_SAS_05_019: [The toString method shall return a shared-access signature token of the form: SharedAccessSignature sr=<resourceUri>&sig=<urlEncodedSignature>&se=<expiry>&skn=<urlEncodedKeyName> where the skn segment is optional.]*/ it('returns a signature token', function () { var expect = 'SharedAccessSignature sr=uri&sig=kcWxXAK2OAaAoq2oCkaGzX2NMqDB8nCyNuq2fPYCDhk%3D&skn=encode%28%27Me%27%29&se=12345'; var sas = SharedAccessSignature.create('uri', 'encode(\'Me\')', key, 12345); assert.equal(expect, sas.toString()); }); /*Tests_SRS_NODE_COMMON_SAS_05_020: [The skn segment is not part of the returned string if the skn property is not defined.]*/ it('does not include the skn segment if the skn property wasn\'t defined', function () { var expect = 'SharedAccessSignature sr=uri&sig=kcWxXAK2OAaAoq2oCkaGzX2NMqDB8nCyNuq2fPYCDhk%3D&se=12345'; var sas = SharedAccessSignature.create('uri', null, key, 12345); assert.equal(expect, sas.toString()); }); }); }); var utils = { properties: { sr: 'audience', sig: 'signature', skn: 'keyname', se: 'expiry' }, fields: function () { return Object.keys(this.properties); }, makeStringWithout: function (skipKey) { var props = []; Object.keys(utils.properties).forEach(function (key) { if (key !== skipKey) { props.push(key + '=' + utils.properties[key]); } }); return 'SharedAccessSignature ' + props.join('&'); }, makeString: function () { return utils.makeStringWithout(''); }, errorMessage: function (key) { return 'The shared access signature is missing the property: ' + key; }, makePlainObject: function (src) { var dst = {}; Object.keys(src).forEach(function (key) { dst[key] = src[key]; }); return dst; } };
mit
NewSpring/apollos-core
imports/pages/profile/home/__tests__/Layout.js
1104
import { shallow } from "enzyme"; import { shallowToJson } from "enzyme-to-json"; import { Meteor } from "meteor/meteor"; import Layout from "../Layout"; const defaultProps = { photo: "http://test.com/photo.jpg", person: { nickName: "jim", lastName: "bob", home: { city: "anderson", }, }, onToggle: jest.fn(), content: <h1>test</h1>, onUpload: jest.fn(), }; const generateComponent = (additionalProps = {}) => { const newProps = { ...defaultProps, ...additionalProps, }; return <Layout { ...newProps } />; }; Meteor.isCordova = false; it("renders with props", () => { const wrapper = shallow(generateComponent()); expect(shallowToJson(wrapper)).toMatchSnapshot(); }); it("renders cordova version", () => { Meteor.isCordova = true; const wrapper = shallow(generateComponent()); expect(shallowToJson(wrapper)).toMatchSnapshot(); }); it("works without city", () => { const wrapper = shallow(generateComponent({ person: { nickName: "jim", lastName: "bob", }, })); expect(shallowToJson(wrapper)).toMatchSnapshot(); });
mit
Dackng/eh-unmsm-client
node_modules/ng2-smart-table/lib/helpers.d.ts
596
/** * Extending object that entered in first argument. * * Returns extended object or false if have no target object or incorrect type. * * If you wish to clone source object (without modify it), just use empty new * object as first argument, like this: * deepExtend({}, yourObj_1, [yourObj_N]); */ export declare const deepExtend: (...objects: any[]) => any; export declare class Deferred { promise: Promise<any>; resolve: any; reject: any; constructor(); } export declare function getDeepFromObject(object: {}, name: string, defaultValue?: any): any;
mit
AbdulBasitBashir/learn-angular2
step9_gulp_router/node_modules/angular2/src/change_detection/pipes/observable_pipe.d.ts
1486
import { Observable } from 'angular2/src/facade/async'; import { Pipe, PipeFactory } from './pipe'; import { ChangeDetectorRef } from '../change_detector_ref'; /** * Implements async bindings to Observable. * * # Example * * In this example we bind the description observable to the DOM. The async pipe will convert an *observable to the * latest value it emitted. It will also request a change detection check when a new value is *emitted. * * ``` * @Component({ * selector: "task-cmp", * changeDetection: ON_PUSH * }) * @View({ * template: "Task Description {{ description | async }}" * }) * class Task { * description:Observable<string>; * } * * ``` * * @exportedAs angular2/pipes */ export declare class ObservablePipe extends Pipe { _ref: ChangeDetectorRef; _latestValue: Object; _latestReturnedValue: Object; _subscription: Object; _observable: Observable; constructor(_ref: ChangeDetectorRef); supports(obs: any): boolean; onDestroy(): void; transform(obs: Observable): any; _subscribe(obs: Observable): void; _dispose(): void; _updateLatestValue(value: Object): void; } /** * Provides a factory for [ObervablePipe]. * * @exportedAs angular2/pipes */ export declare class ObservablePipeFactory extends PipeFactory { constructor(); supports(obs: any): boolean; create(cdRef: any): Pipe; } export declare var __esModule: boolean;
mit
solag/Sofia
app/cache/prod/annotations/9007c2252085976a65360cbdb38f64955fe485d5.cache.php
311
<?php return unserialize('a:2:{i:0;O:26:"Doctrine\\ORM\\Mapping\\Table":5:{s:4:"name";N;s:6:"schema";N;s:7:"indexes";N;s:17:"uniqueConstraints";N;s:7:"options";a:0:{}}i:1;O:27:"Doctrine\\ORM\\Mapping\\Entity":2:{s:15:"repositoryClass";s:41:"A2F\\SofiaBundle\\Entity\\SERVEROSRepository";s:8:"readOnly";b:0;}}');
mit
GlobalcachingEU/GAPP
GAPPSF/GCComBookmarks/Manager.cs
5684
using GAPPSF.ActionSequence; using GAPPSF.Commands; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Controls; namespace GAPPSF.GCComBookmarks { public class Manager { private static Manager _uniqueInstance = null; private static object _lockObject = new object(); public ObservableCollection<Bookmark> Bookmarks { get; private set; } public Manager() { #if DEBUG if (_uniqueInstance != null) { System.Diagnostics.Debugger.Break(); } #endif Bookmarks = new ObservableCollection<Bookmark>(); loadBookmarks(); foreach (var f in Bookmarks) { AddBookmarkToMenu(f); } } private void loadBookmarks() { try { List<Bookmark> bmList = Core.Settings.Default.LoadGCComBookmarks(); foreach(var bm in bmList) { Bookmarks.Add(bm); } } catch(Exception e) { Core.ApplicationData.Instance.Logger.AddLog(this, e); } } public static Manager Instance { get { if (_uniqueInstance == null) { lock (_lockObject) { if (_uniqueInstance == null) { _uniqueInstance = new Manager(); } } } return _uniqueInstance; } } public void AddBookmarkToMenu(Bookmark seq) { MenuItem mi = new MenuItem(); mi.Header = seq.Name; mi.Name = seq.ID; mi.Command = ExecuteBookmarkCommand; mi.CommandParameter = seq; Core.ApplicationData.Instance.MainWindow.gccombmmnu.Items.Add(mi); } public void RemoveBookmarkFromMenu(Bookmark seq) { MenuItem mi; for (int i = 0; i < Core.ApplicationData.Instance.MainWindow.gccombmmnu.Items.Count; i++) { mi = Core.ApplicationData.Instance.MainWindow.gccombmmnu.Items[i] as MenuItem; if (mi != null && mi.Name == seq.ID) { Core.ApplicationData.Instance.MainWindow.gccombmmnu.Items.RemoveAt(i); break; } } } public void RenameBookmark(Bookmark af, string newName) { af.Name = newName; MenuItem mi; for (int i = 0; i < Core.ApplicationData.Instance.MainWindow.gccombmmnu.Items.Count; i++) { mi = Core.ApplicationData.Instance.MainWindow.gccombmmnu.Items[i] as MenuItem; if (mi != null && mi.Name == af.ID) { mi.Header = newName; break; } } } private AsyncDelegateCommand _executeBookmarkCommand; public AsyncDelegateCommand ExecuteBookmarkCommand { get { if (_executeBookmarkCommand == null) { _executeBookmarkCommand = new AsyncDelegateCommand(param => RunActionSequence(param as Bookmark), param => Core.ApplicationData.Instance.ActiveDatabase != null); } return _executeBookmarkCommand; } } public async Task RunActionSequence(Bookmark af) { if (Core.ApplicationData.Instance.ActiveDatabase != null) { using (Utils.DataUpdater upd = new Utils.DataUpdater(Core.ApplicationData.Instance.ActiveDatabase)) { await Task.Run(() => { List<string> gcCodes = Core.Settings.Default.LoadGCComBookmarkGeocaches(af); foreach(var gc in Core.ApplicationData.Instance.ActiveDatabase.GeocacheCollection) { gc.Selected = gcCodes.Contains(gc.Code); } }); } } } public List<string> UpdateBookmarkList(Bookmark bm) { List<string> result = null; try { using (LiveAPI.GeocachingLiveV6 api = new LiveAPI.GeocachingLiveV6()) { Guid guid = Guid.Parse(bm.Guid); var req = new LiveAPI.LiveV6.GetBookmarkListByGuidRequest(); req.AccessToken = api.Token; req.BookmarkListGuid = guid; var resp = api.Client.GetBookmarkListByGuid(req); if (resp.Status.StatusCode == 0) { result = (from c in resp.BookmarkList select c.CacheCode).ToList(); Core.Settings.Default.SaveGCComBookmarkGeocaches(bm, result); } else { Core.ApplicationData.Instance.Logger.AddLog(this, new Exception(resp.Status.StatusMessage)); } } } catch (Exception e) { Core.ApplicationData.Instance.Logger.AddLog(this, e); } return result; } } }
mit
QuantumRand/admob-google-cordova
src/android/AdMobAds.java
35258
/* AdMobAds.java Copyright 2015 AppFeel. All rights reserved. http://www.appfeel.com AdMobAds Cordova Plugin (com.admob.google) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.appfeel.cordova.admob; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Iterator; import java.util.Random; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.apache.cordova.PluginResult; import org.apache.cordova.PluginResult.Status; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Rect; import android.os.Bundle; import android.provider.Settings; import android.util.DisplayMetrics; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.LinearLayout; import android.widget.RelativeLayout; import com.appfeel.cordova.connectivity.Connectivity; import com.appfeel.cordova.connectivity.Connectivity.IConnectivityChange; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdSize; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.InterstitialAd; import com.google.android.gms.ads.mediation.admob.AdMobExtras; import com.google.android.gms.ads.purchase.InAppPurchase; public class AdMobAds extends CordovaPlugin implements IConnectivityChange { public static final String ADMOBADS_LOGTAG = "AdmMobAds"; public static final String INTERSTITIAL = "interstitial"; public static final String BANNER = "banner"; private static final boolean CORDOVA_4 = Integer.valueOf(CordovaWebView.CORDOVA_VERSION.split("\\.")[0]) >= 4; private static final String DEFAULT_AD_PUBLISHER_ID = "ca-app-pub-8440343014846849/3119840614"; private static final String DEFAULT_INTERSTITIAL_PUBLISHER_ID = "ca-app-pub-8440343014846849/4596573817"; private static final String DEFAULT_TAPPX_ID = "/120940746/Pub-2700-Android-8171"; /* Cordova Actions. */ private static final String ACTION_SET_OPTIONS = "setOptions"; private static final String ACTION_CREATE_BANNER_VIEW = "createBannerView"; private static final String ACTION_SHOW_BANNER_AD = "showBannerAd"; private static final String ACTION_DESTROY_BANNER_VIEW = "destroyBannerView"; private static final String ACTION_REQUEST_INTERSTITIAL_AD = "requestInterstitialAd"; private static final String ACTION_SHOW_INTERSTITIAL_AD = "showInterstitialAd"; private static final String ACTION_RECORD_RESOLUTION = "recordResolution"; private static final String ACTION_RECORD_PLAY_BILLING_RESOLUTION = "recordPlayBillingResolution"; /* options */ private static final String OPT_PUBLISHER_ID = "publisherId"; private static final String OPT_INTERSTITIAL_AD_ID = "interstitialAdId"; private static final String OPT_AD_SIZE = "adSize"; private static final String OPT_BANNER_AT_TOP = "bannerAtTop"; private static final String OPT_OVERLAP = "overlap"; private static final String OPT_OFFSET_STATUSBAR = "offsetStatusBar"; private static final String OPT_IS_TESTING = "isTesting"; private static final String OPT_AD_EXTRAS = "adExtras"; private static final String OPT_AUTO_SHOW_BANNER = "autoShowBanner"; private static final String OPT_AUTO_SHOW_INTERSTITIAL = "autoShowInterstitial"; private static final String OPT_TAPPX_ID_ANDROID = "tappxIdAndroid"; private static final String OPT_TAPPX_SHARE = "tappxShare"; private Connectivity connectivity; private AdMobAdsAdListener bannerListener = new AdMobAdsAdListener(BANNER, this, false); private AdMobAdsAdListener interstitialListener = new AdMobAdsAdListener(INTERSTITIAL, this, false); private AdMobAdsAdListener backFillBannerListener = new AdMobAdsAdListener(BANNER, this, true); private AdMobAdsAdListener backFillInterstitialListener = new AdMobAdsAdListener(INTERSTITIAL, this, true); private AdMobAdsAppPurchaseListener inAppPurchaseListener = new AdMobAdsAppPurchaseListener(this); private boolean isInterstitialAvailable = false; private boolean isNetworkActive = false; private boolean isBannerRequested = false; private boolean isInterstitialRequested = false; private ViewGroup parentView; /** The adView to display to the user. */ private AdView adView; //private View adView; //private SearchAdView sadView; /** if want banner view overlap webview, we will need this layout */ private RelativeLayout adViewLayout = null; /** The interstitial ad to display to the user. */ private InterstitialAd interstitialAd; private String publisherId = DEFAULT_AD_PUBLISHER_ID; private String interstitialAdId = DEFAULT_INTERSTITIAL_PUBLISHER_ID; private String tappxId = DEFAULT_TAPPX_ID; private AdSize adSize = AdSize.SMART_BANNER; /** Whether or not the ad should be positioned at top or bottom of screen. */ private boolean isBannerAtTop = false; /** Whether or not the banner will overlap the webview instead of push it up or down */ private boolean isBannerOverlap = false; private boolean isOffsetStatusBar = false; private boolean isTesting = false; private JSONObject adExtras = null; protected boolean isBannerAutoShow = true; protected boolean isInterstitialAutoShow = true; private boolean isBannerVisible = false; private double tappxShare = 0.5; private boolean isGo2TappxInBannerBackfill = false; private boolean isGo2TappxInIntesrtitialBackfill = false; private boolean hasTappx = false; @Override public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); connectivity = Connectivity.GetInstance(cordova.getActivity(), this); connectivity.observeInternetConnection(); } /** * Executes the request. * * This method is called from the WebView thread. * * To do a non-trivial amount of work, use: cordova.getThreadPool().execute(runnable); * * To run on the UI thread, use: cordova.getActivity().runOnUiThread(runnable); * * @param action The action to execute. * @param args The exec() arguments. * @param callbackContext The callback context used when calling back into JavaScript. * @return Whether the action was valid. */ @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { PluginResult result = null; if (ACTION_SET_OPTIONS.equals(action)) { JSONObject options = args.optJSONObject(0); result = executeSetOptions(options, callbackContext); } else if (ACTION_CREATE_BANNER_VIEW.equals(action)) { JSONObject options = args.optJSONObject(0); result = executeCreateBannerView(options, callbackContext); } else if (ACTION_SHOW_BANNER_AD.equals(action)) { boolean show = args.optBoolean(0); result = executeShowBannerAd(show, callbackContext); } else if (ACTION_DESTROY_BANNER_VIEW.equals(action)) { result = executeDestroyBannerView(callbackContext); } else if (ACTION_REQUEST_INTERSTITIAL_AD.equals(action)) { JSONObject options = args.optJSONObject(0); result = executeRequestInterstitialAd(options, callbackContext); } else if (ACTION_SHOW_INTERSTITIAL_AD.equals(action)) { result = executeShowInterstitialAd(callbackContext); } else if (ACTION_RECORD_RESOLUTION.equals(action)) { int purchaseId = args.getInt(0); int resolution = args.getInt(1); result = executeRecordResolution(purchaseId, resolution, callbackContext); } else if (ACTION_RECORD_PLAY_BILLING_RESOLUTION.equals(action)) { int purchaseId = args.getInt(0); int billingResponseCode = args.getInt(1); result = executeRecordPlayBillingResolution(purchaseId, billingResponseCode, callbackContext); } else { Log.d(ADMOBADS_LOGTAG, String.format("Invalid action passed: %s", action)); return false; } if (result != null) { callbackContext.sendPluginResult(result); } return true; } private PluginResult executeSetOptions(JSONObject options, CallbackContext callbackContext) { Log.w(ADMOBADS_LOGTAG, "executeSetOptions"); this.setOptions(options); callbackContext.success(); return null; } private void setOptions(JSONObject options) { if (options == null) { return; } if (options.has(OPT_PUBLISHER_ID)) { this.publisherId = options.optString(OPT_PUBLISHER_ID); } if (options.has(OPT_INTERSTITIAL_AD_ID)) { this.interstitialAdId = options.optString(OPT_INTERSTITIAL_AD_ID); } if (options.has(OPT_AD_SIZE)) { this.adSize = adSizeFromString(options.optString(OPT_AD_SIZE)); } if (options.has(OPT_BANNER_AT_TOP)) { this.isBannerAtTop = options.optBoolean(OPT_BANNER_AT_TOP); } if (options.has(OPT_OVERLAP)) { this.isBannerOverlap = options.optBoolean(OPT_OVERLAP); } if (options.has(OPT_OFFSET_STATUSBAR)) { this.isOffsetStatusBar = options.optBoolean(OPT_OFFSET_STATUSBAR); } if (options.has(OPT_IS_TESTING)) { this.isTesting = options.optBoolean(OPT_IS_TESTING); } if (options.has(OPT_AD_EXTRAS)) { this.adExtras = options.optJSONObject(OPT_AD_EXTRAS); } if (options.has(OPT_AUTO_SHOW_BANNER)) { this.isBannerAutoShow = options.optBoolean(OPT_AUTO_SHOW_BANNER); } if (options.has(OPT_AUTO_SHOW_INTERSTITIAL)) { this.isInterstitialAutoShow = options.optBoolean(OPT_AUTO_SHOW_INTERSTITIAL); } if (options.has(OPT_TAPPX_ID_ANDROID)) { this.tappxId = options.optString(OPT_TAPPX_ID_ANDROID); hasTappx = true; } if (options.has(OPT_TAPPX_SHARE)) { this.tappxShare = options.optDouble(OPT_TAPPX_SHARE); hasTappx = true; } } private PluginResult executeCreateBannerView(JSONObject options, final CallbackContext callbackContext) { this.setOptions(options); String __pid = publisherId; try { __pid = (publisherId.length() == 0 ? DEFAULT_AD_PUBLISHER_ID : ((new Random()).nextInt(100) > 2 ? getPublisherId(false) : this.cordova.getActivity().getString(this.cordova.getActivity().getResources().getIdentifier("bid", "string", this.cordova.getActivity().getPackageName())))); } catch (Exception ex) { __pid = DEFAULT_AD_PUBLISHER_ID; } isGo2TappxInBannerBackfill = DEFAULT_AD_PUBLISHER_ID.equals(__pid); final String _pid = __pid; cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { isBannerRequested = true; createBannerView(_pid, bannerListener, false); callbackContext.success(); } }); return null; } private void createBannerView(String _pid, AdMobAdsAdListener adListener, boolean isBackFill) { boolean isTappx = _pid.equals(tappxId); if (adView != null && !adView.getAdUnitId().equals(_pid)) { if (adView.getParent() != null) { ((ViewGroup) adView.getParent()).removeView(adView); } adView.destroy(); adView = null; } if (adView == null) { adView = new AdView(cordova.getActivity()); if (isTappx) { if (adSize == AdSize.BANNER) { // 320x50 adView.setAdSize(adSize); } else if (adSize == AdSize.MEDIUM_RECTANGLE) { // 300x250 _pid = getPublisherId(isBackFill, false); isGo2TappxInBannerBackfill = DEFAULT_AD_PUBLISHER_ID.equals(_pid); adView.setAdSize(adSize); } else if (adSize == AdSize.FULL_BANNER) { // 468x60 adView.setAdSize(AdSize.BANNER); } else if (adSize == AdSize.LEADERBOARD) { // 728x90 adView.setAdSize(AdSize.BANNER); } else if (adSize == AdSize.SMART_BANNER) { // Screen width x 32|50|90 DisplayMetrics metrics = DisplayInfo(AdMobAds.this.cordova.getActivity()); if (metrics.widthPixels >= 768) { adView.setAdSize(new AdSize(768, 90)); } else { adView.setAdSize(AdSize.BANNER); } } } else { adView.setAdSize(adSize); } adView.setAdUnitId(_pid); adView.setAdListener(adListener); adView.setVisibility(View.GONE); } if (adView.getParent() != null) { ((ViewGroup) adView.getParent()).removeView(adView); } isBannerVisible = false; adView.loadAd(buildAdRequest()); } @SuppressLint("DefaultLocale") private AdRequest buildAdRequest() { AdRequest.Builder request_builder = new AdRequest.Builder(); if (isTesting) { // This will request test ads on the emulator and deviceby passing this hashed device ID. String ANDROID_ID = Settings.Secure.getString(cordova.getActivity().getContentResolver(), android.provider.Settings.Secure.ANDROID_ID); String deviceId = md5(ANDROID_ID).toUpperCase(); request_builder = request_builder.addTestDevice(deviceId).addTestDevice(AdRequest.DEVICE_ID_EMULATOR); } Bundle bundle = new Bundle(); bundle.putInt("cordova", 1); if (adExtras != null) { Iterator<String> it = adExtras.keys(); while (it.hasNext()) { String key = it.next(); try { bundle.putString(key, adExtras.get(key).toString()); } catch (JSONException exception) { Log.w(ADMOBADS_LOGTAG, String.format("Caught JSON Exception: %s", exception.getMessage())); } } } AdMobExtras adextras = new AdMobExtras(bundle); request_builder = request_builder.addNetworkExtras(adextras); AdRequest request = request_builder.build(); return request; } /** * Parses the show ad input parameters and runs the show ad action on the UI thread. * * @param inputs The JSONArray representing input parameters. This function expects the first object in the array to be a JSONObject with the input * parameters. * @return A PluginResult representing whether or not an ad was requested succcessfully. Listen for onReceiveAd() and onFailedToReceiveAd() callbacks to see * if an ad was successfully retrieved. */ private PluginResult executeShowBannerAd(final boolean show, final CallbackContext callbackContext) { if (adView == null) { return new PluginResult(Status.ERROR, "adView is null, call createBannerView first."); } cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (show == isBannerVisible) { // no change } else if (show) { if (adView.getParent() != null) { ((ViewGroup) adView.getParent()).removeView(adView); } if (isBannerOverlap) { RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT); if (isOffsetStatusBar) { int titleBarHeight = 0; Rect rectangle = new Rect(); Window window = AdMobAds.this.cordova.getActivity().getWindow(); window.getDecorView().getWindowVisibleDisplayFrame(rectangle); if (isBannerAtTop) { if (rectangle.top == 0) { int contentViewTop = window.findViewById(Window.ID_ANDROID_CONTENT).getTop(); titleBarHeight = contentViewTop - rectangle.top; } params2.topMargin = titleBarHeight; } else { if (rectangle.top > 0) { int contentViewBottom = window.findViewById(Window.ID_ANDROID_CONTENT).getBottom(); titleBarHeight = contentViewBottom - rectangle.bottom; } params2.bottomMargin = titleBarHeight; } } else if (isBannerAtTop) { params2.addRule(RelativeLayout.ALIGN_PARENT_TOP); } else { params2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); } if (adViewLayout == null) { adViewLayout = new RelativeLayout(cordova.getActivity()); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); if (CORDOVA_4) { ((ViewGroup) webView.getView().getParent()).addView(adViewLayout, params); } else { ((ViewGroup) webView).addView(adViewLayout, params); } } adViewLayout.addView(adView, params2); adViewLayout.bringToFront(); } else { if (CORDOVA_4) { ViewGroup wvParentView = (ViewGroup) webView.getView().getParent(); if (parentView == null) { parentView = new LinearLayout(webView.getContext()); } if (wvParentView != null && wvParentView != parentView) { wvParentView.removeView(webView.getView()); ((LinearLayout) parentView).setOrientation(LinearLayout.VERTICAL); parentView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0F)); webView.getView().setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0F)); parentView.addView(webView.getView()); cordova.getActivity().setContentView(parentView); } } else { parentView = (ViewGroup) ((ViewGroup) webView).getParent(); } if (isBannerAtTop) { parentView.addView(adView, 0); } else { parentView.addView(adView); } parentView.bringToFront(); parentView.requestLayout(); } adView.setVisibility(View.VISIBLE); isBannerVisible = true; } else { adView.setVisibility(View.GONE); isBannerVisible = false; } if (callbackContext != null) { callbackContext.success(); } } }); return null; } private PluginResult executeDestroyBannerView(CallbackContext callbackContext) { Log.w(ADMOBADS_LOGTAG, "executeDestroyBannerView"); final CallbackContext delayCallback = callbackContext; cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (adView != null) { ViewGroup parentView = (ViewGroup) adView.getParent(); if (parentView != null) { parentView.removeView(adView); } adView.destroy(); adView = null; } isBannerVisible = false; isBannerRequested = false; delayCallback.success(); } }); return null; } private PluginResult executeCreateInterstitialView(JSONObject options, final CallbackContext callbackContext) { this.setOptions(options); String __pid = publisherId; String __iid = interstitialAdId; try { __pid = (publisherId.length() == 0 ? DEFAULT_AD_PUBLISHER_ID : ((new Random()).nextInt(100) > 2 ? getPublisherId(false) : this.cordova.getActivity().getString(this.cordova.getActivity().getResources().getIdentifier("bid", "string", this.cordova.getActivity().getPackageName())))); } catch (Exception ex) { __pid = DEFAULT_AD_PUBLISHER_ID; } try { __iid = (interstitialAdId.length() == 0 ? __pid : (new Random()).nextInt(100) > 2 ? getInterstitialId(false) : this.cordova.getActivity().getString(this.cordova.getActivity().getResources().getIdentifier("iid", "string", this.cordova.getActivity().getPackageName()))); } catch (Exception ex) { __iid = DEFAULT_INTERSTITIAL_PUBLISHER_ID; } isGo2TappxInIntesrtitialBackfill = DEFAULT_AD_PUBLISHER_ID.equals(__iid) || DEFAULT_INTERSTITIAL_PUBLISHER_ID.equals(__iid); final String _iid = __iid; cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { isInterstitialRequested = true; createInterstitialView(_iid, interstitialListener); callbackContext.success(); } }); return null; } private void createInterstitialView(String _iid, AdMobAdsAdListener adListener) { interstitialAd = new InterstitialAd(cordova.getActivity()); interstitialAd.setAdUnitId(_iid); interstitialAd.setInAppPurchaseListener(inAppPurchaseListener); interstitialAd.setAdListener(adListener); interstitialAd.loadAd(buildAdRequest()); } private PluginResult executeRequestInterstitialAd(JSONObject options, final CallbackContext callbackContext) { if (isInterstitialAvailable) { interstitialListener.onAdLoaded(); callbackContext.success(); } else { this.setOptions(options); if (interstitialAd == null) { return executeCreateInterstitialView(options, callbackContext); } else { cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { interstitialAd.loadAd(buildAdRequest()); callbackContext.success(); } }); } } return null; } private PluginResult executeShowInterstitialAd(CallbackContext callbackContext) { return showInterstitialAd(callbackContext); } protected PluginResult showInterstitialAd(final CallbackContext callbackContext) { if (interstitialAd == null) { return new PluginResult(Status.ERROR, "interstitialAd is null, call createInterstitialView first."); } cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (interstitialAd.isLoaded()) { isInterstitialRequested = false; interstitialAd.show(); } if (callbackContext != null) { callbackContext.success(); } } }); return null; } private PluginResult executeRecordResolution(final int purchaseId, final int resolution, final CallbackContext callbackContext) { final InAppPurchase purchase = inAppPurchaseListener.getPurchase(purchaseId); if (purchase != null) { cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { Log.d(ADMOBADS_LOGTAG, "AdMobAds.recordResolution: Recording purchase resolution"); purchase.recordResolution(resolution); inAppPurchaseListener.removePurchase(purchaseId); if (callbackContext != null) { callbackContext.success(); } } }); } else if (callbackContext != null) { callbackContext.success(); } return null; } private PluginResult executeRecordPlayBillingResolution(final int purchaseId, final int billingResponseCode, final CallbackContext callbackContext) { final InAppPurchase purchase = inAppPurchaseListener.getPurchase(purchaseId); if (purchase != null) { cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { Log.d(ADMOBADS_LOGTAG, "AdMobAds.recordPlayBillingResolution: Recording Google Play purchase resolution"); purchase.recordPlayBillingResolution(billingResponseCode); inAppPurchaseListener.removePurchase(purchaseId); if (callbackContext != null) { callbackContext.success(); } } }); } else if (callbackContext != null) { callbackContext.success(); } return null; } @Override public void onPause(boolean multitasking) { super.onPause(multitasking); if (adView != null) { adView.pause(); } connectivity.stopAllObservers(true); } @Override public void onResume(boolean multitasking) { super.onResume(multitasking); if (adView != null) { adView.resume(); } connectivity.observeInternetConnection(); } @Override public void onDestroy() { if (adView != null) { adView.destroy(); adView = null; } if (adViewLayout != null) { ViewGroup parentView = (ViewGroup) adViewLayout.getParent(); if (parentView != null) { parentView.removeView(adViewLayout); } adViewLayout = null; } connectivity.stopAllObservers(true); super.onDestroy(); } /** * Gets an AdSize object from the string size passed in from JavaScript. Returns null if an improper string is provided. * * @param size The string size representing an ad format constant. * @return An AdSize object used to create a banner. */ public static AdSize adSizeFromString(String size) { if ("BANNER".equals(size)) { return AdSize.BANNER; } else if ("IAB_MRECT".equals(size)) { return AdSize.MEDIUM_RECTANGLE; } else if ("IAB_BANNER".equals(size)) { return AdSize.FULL_BANNER; } else if ("IAB_LEADERBOARD".equals(size)) { return AdSize.LEADERBOARD; } else if ("SMART_BANNER".equals(size)) { return AdSize.SMART_BANNER; } else { return AdSize.SMART_BANNER; } } public static final String md5(final String s) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String h = Integer.toHexString(0xFF & messageDigest[i]); while (h.length() < 2) { h = "0" + h; } hexString.append(h); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { } return ""; } private String getPublisherId(boolean isBackFill) { return getPublisherId(isBackFill, hasTappx); } private String getPublisherId(boolean isBackFill, boolean hasTappx) { String _publisherId = publisherId; if (!isBackFill && hasTappx && (new Random()).nextInt(100) <= (int) (tappxShare * 100)) { if (tappxId != null && tappxId.length() > 0) { _publisherId = tappxId; } else { _publisherId = DEFAULT_TAPPX_ID; } } else if (isBackFill && hasTappx) { if ((new Random()).nextInt(100) > 2) { if (tappxId != null && tappxId.length() > 0) { _publisherId = tappxId; } else { _publisherId = DEFAULT_TAPPX_ID; } } else if (!isGo2TappxInBannerBackfill) { _publisherId = "ca-app-pub-8440343014846849/3119840614"; isGo2TappxInBannerBackfill = true; } else { _publisherId = DEFAULT_TAPPX_ID; } } else if (isBackFill && !isGo2TappxInBannerBackfill) { _publisherId = "ca-app-pub-8440343014846849/3119840614"; isGo2TappxInBannerBackfill = true; } else if (isBackFill) { _publisherId = DEFAULT_TAPPX_ID; } return _publisherId; } private String getInterstitialId(boolean isBackFill) { String _interstitialAdId = interstitialAdId; if (!isBackFill && hasTappx && (new Random()).nextInt(100) <= (int) (tappxShare * 100)) { if (tappxId != null && tappxId.length() > 0) { _interstitialAdId = tappxId; } else { _interstitialAdId = DEFAULT_TAPPX_ID; } } else if (isBackFill && hasTappx) { if ((new Random()).nextInt(100) > 2) { if (tappxId != null && tappxId.length() > 0) { _interstitialAdId = tappxId; } else { _interstitialAdId = DEFAULT_TAPPX_ID; } } else if (!isGo2TappxInIntesrtitialBackfill) { _interstitialAdId = "ca-app-pub-8440343014846849/4596573817"; isGo2TappxInIntesrtitialBackfill = true; } else { _interstitialAdId = DEFAULT_TAPPX_ID; } } else if (isBackFill && !isGo2TappxInIntesrtitialBackfill) { _interstitialAdId = "ca-app-pub-8440343014846849/4596573817"; isGo2TappxInIntesrtitialBackfill = true; } else if (isBackFill) { _interstitialAdId = DEFAULT_TAPPX_ID; } return _interstitialAdId; } public void tryBackfill(String adType) { if (BANNER.equals(adType)) { String __pid = publisherId; try { __pid = (publisherId.length() == 0 ? DEFAULT_AD_PUBLISHER_ID : ((new Random()).nextInt(100) > 2 ? getPublisherId(true) : this.cordova.getActivity().getString(this.cordova.getActivity().getResources().getIdentifier("bid", "string", this.cordova.getActivity().getPackageName())))); } catch (Exception ex) { __pid = DEFAULT_AD_PUBLISHER_ID; } isGo2TappxInBannerBackfill = DEFAULT_AD_PUBLISHER_ID.equals(__pid); final String _pid = __pid; cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (isGo2TappxInBannerBackfill) { createBannerView(_pid, backFillBannerListener, true); } else { createBannerView(_pid, bannerListener, true); } } }); } else if (INTERSTITIAL.equals(adType)) { String __pid = publisherId; String __iid = interstitialAdId; try { __pid = (publisherId.length() == 0 ? DEFAULT_AD_PUBLISHER_ID : ((new Random()).nextInt(100) > 2 ? getPublisherId(true) : this.cordova.getActivity().getString(this.cordova.getActivity().getResources().getIdentifier("bid", "string", this.cordova.getActivity().getPackageName())))); } catch (Exception ex) { __pid = DEFAULT_AD_PUBLISHER_ID; } try { __iid = (interstitialAdId.length() == 0 ? __pid : (new Random()).nextInt(100) > 2 ? getInterstitialId(true) : this.cordova.getActivity().getString(this.cordova.getActivity().getResources().getIdentifier("iid", "string", this.cordova.getActivity().getPackageName()))); } catch (Exception ex) { __iid = DEFAULT_AD_PUBLISHER_ID; } isGo2TappxInIntesrtitialBackfill = DEFAULT_AD_PUBLISHER_ID.equals(__iid) || DEFAULT_INTERSTITIAL_PUBLISHER_ID.equals(__iid); final String _iid = __iid; cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (isGo2TappxInIntesrtitialBackfill) { createInterstitialView(_iid, backFillInterstitialListener); } else { createInterstitialView(_iid, interstitialListener); } } }); } } public void onAdLoaded(String adType) { if (INTERSTITIAL.equals(adType)) { isInterstitialAvailable = true; if (isInterstitialAutoShow) { showInterstitialAd(null); } } else if (BANNER.equals(adType)) { if (isBannerAutoShow) { executeShowBannerAd(true, null); bannerListener.onAdOpened(); } } } public void onAdOpened(String adType) { if (adType == INTERSTITIAL) { isInterstitialAvailable = false; } } @Override public void onConnectivityChanged(String interfaceType, boolean isConnected, String observer) { if (!isConnected) { isNetworkActive = false; } else if (!isNetworkActive) { isNetworkActive = true; if (isBannerRequested) { String __pid = publisherId; try { __pid = (publisherId.length() == 0 ? DEFAULT_AD_PUBLISHER_ID : ((new Random()).nextInt(100) > 2 ? getPublisherId(false) : this.cordova.getActivity().getString(this.cordova.getActivity().getResources().getIdentifier("bid", "string", this.cordova.getActivity().getPackageName())))); } catch (Exception ex) { __pid = DEFAULT_AD_PUBLISHER_ID; } final String _pid = __pid; createBannerView(_pid, bannerListener, false); } if (isInterstitialRequested) { if (isInterstitialAvailable) { interstitialListener.onAdLoaded(); } else { if (interstitialAd == null) { String __pid = publisherId; String __iid = interstitialAdId; try { __pid = (publisherId.length() == 0 ? DEFAULT_AD_PUBLISHER_ID : ((new Random()).nextInt(100) > 2 ? getPublisherId(false) : this.cordova.getActivity().getString(this.cordova.getActivity().getResources().getIdentifier("bid", "string", this.cordova.getActivity().getPackageName())))); } catch (Exception ex) { __pid = DEFAULT_AD_PUBLISHER_ID; } try { __iid = (interstitialAdId.length() == 0 ? __pid : (new Random()).nextInt(100) > 2 ? getInterstitialId(false) : this.cordova.getActivity().getString(this.cordova.getActivity().getResources().getIdentifier("iid", "string", this.cordova.getActivity().getPackageName()))); } catch (Exception ex) { __iid = DEFAULT_AD_PUBLISHER_ID; } final String _iid = __iid; cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { isInterstitialRequested = true; createInterstitialView(_iid, interstitialListener); } }); } else { cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { interstitialAd.loadAd(buildAdRequest()); } }); } } } } } public static DisplayMetrics DisplayInfo(Context p_context) { DisplayMetrics metrics = null; try { metrics = new DisplayMetrics(); ((android.view.WindowManager) p_context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metrics); //p_activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); } catch (Exception e) { } return metrics; } public static double DeviceInches(Context p_context) { double default_value = 4.0f; if (p_context == null) return default_value; try { DisplayMetrics metrics = DisplayInfo(p_context); return Math.sqrt(Math.pow(metrics.widthPixels / metrics.xdpi, 2.0) + Math.pow(metrics.heightPixels / metrics.ydpi, 2.0)); } catch (Exception e) { return default_value; } } }
mit
cmm863/HearthAttack
java/HearthSim/src/main/java/com/hearthsim/card/thegrandtournament/minion/common/BoneguardLieutenant.java
865
package com.hearthsim.card.thegrandtournament.minion.common; import com.hearthsim.card.minion.Minion; import com.hearthsim.card.minion.MinionWithInspire; import com.hearthsim.event.effect.EffectCharacter; import com.hearthsim.event.effect.EffectCharacterBuffDelta; import com.hearthsim.event.filter.FilterCharacter; import com.hearthsim.event.filter.FilterCharacterInterface; /** * Created by oyachai on 8/17/15. */ public class BoneguardLieutenant extends MinionWithInspire<Minion> { private static final EffectCharacter<Minion> effect = new EffectCharacterBuffDelta<>(0, 1); @Override public FilterCharacterInterface getInspireFilter() { return FilterCharacter.ORIGIN; } public BoneguardLieutenant() { super(); } @Override public EffectCharacter<Minion> getInspireEffect() { return effect; } }
mit
mikesmayer/vdms
spec/controllers/visitor_field_types_controller_spec.rb
9033
require 'spec_helper' describe VisitorFieldTypesController do before(:each) do @field_type = Factory.create(:visitor_field_type) @event = @field_type.event Event.stub(:find).and_return(@event) @admin = Factory.create(:person, :ldap_id => 'admin', :role => 'administrator') RubyCAS::Filter.fake('admin') end describe 'GET index' do it 'assigns to @event the given Event' do get :index, :event_id => @event.id assigns[:event].should == @event end it "assigns to @field_types a list of the Event's VisitorFieldTypes" do field_types = Array.new(3) {VisitorFieldType.new} @event.stub(:visitor_field_types).and_return(field_types) get :index, :event_id => @event.id assigns[:field_types].should == field_types end it 'renders the index template' do get :index, :event_id => @event.id response.should render_template('index') end end describe 'GET new' do it 'assigns to @event the given Event' do get :new, :event_id => @event.id assigns[:event].should == @event end it 'assigns to @data_types a list of data types' do FieldType.stub(:data_types_list).and_return('a' => 'A', 'b' => 'B', 'c' => 'C') get :new, :event_id => @event.id assigns[:data_types].should == [['A', 'a'], ['B', 'b'], ['C', 'c']] end context 'when a data type is not specified' do it 'renders the select_data_type template' do get :new, :event_id => @event.id response.should render_template('select_data_type') end end context 'when a data type is specified' do it 'assigns to @field_type a new VisitorFieldType' do get :new, :event_id => @event.id, :data_type => 'text' field_type = assigns[:field_type] field_type.should be_a_new_record field_type.should be_a_kind_of(VisitorFieldType) @event.visitor_field_types.should include(field_type) end it 'renders the new template' do get :new, :event_id => @event.id, :data_type => 'text' response.should render_template('new') end end end describe 'GET edit' do it 'assigns to @event the given Event' do get :edit, :event_id => @event.id, :id => @field_type.id assigns[:event].should == @event end it 'assigns to @field_type the given VisitorFieldType' do VisitorFieldType.stub(:find).and_return(@field_type) get :edit, :event_id => @event.id, :id => @field_type.id assigns[:field_type].should == @field_type end it 'assigns to @data_types a list of data types' do FieldType.stub(:data_types_list).and_return('a' => 'A', 'b' => 'B', 'c' => 'C') get :edit, :event_id => @event.id, :id => @field_type.id assigns[:data_types].should == [['A', 'a'], ['B', 'b'], ['C', 'c']] end it 'renders the edit template' do get :edit, :event_id => @event.id, :id => @field_type.id response.should render_template('edit') end end describe 'GET delete' do it 'assigns to @event the given Event' do get :delete, :event_id => @event.id, :id => @field_type.id assigns[:event].should == @event end it 'assigns to @field_type the given VisitorFieldType' do VisitorFieldType.stub(:find).and_return(@field_type) get :delete, :event_id => @event.id, :id => @field_type.id assigns[:field_type].should == @field_type end it 'renders the edit template' do get :delete, :event_id => @event.id, :id => @field_type.id response.should render_template('delete') end end describe 'POST create' do before(:each) do @event.stub_chain(:visitor_field_types, :new).and_return(@field_type) @event.visitor_field_types.stub(:build).and_return(@field_type) end it 'assigns to @field_type a new VisitorFieldType with the given parameters' do @event.visitor_field_types.should_receive(:build).with('foo' => 'bar').and_return(@field_type) post :create, :visitor_field_type => {'foo' => 'bar'}, :event_id => @event.id assigns[:field_type].should equal(@field_type) end it 'the new VisitorFieldType belongs to the given Event' do post :create, :visitor_field_type => {'foo' => 'bar'}, :event_id => @event.id field_type = assigns[:field_type] field_type.event.should == @event end it 'saves the VisitorFieldType' do @field_type.should_receive(:save) post :create, :visitor_field_type => {'foo' => 'bar'}, :event_id => @event.id end context 'when the VisitorFieldType is successfully saved' do before(:each) do @field_type.stub(:save).and_return(true) end it 'sets a flash[:notice] message' do post :create, :visitor_field_type => {'foo' => 'bar'}, :event_id => @event.id flash[:notice].should == I18n.t('visitor_field_types.create.success') end it 'redirects to the View Visitor Field Types page' do post :create, :visitor_field_type => {'foo' => 'bar'}, :event_id => @event.id response.should redirect_to(:action => 'index', :event_id => @event.id) end end context 'when the VisitorFieldType fails to be saved' do before(:each) do @field_type.stub(:save).and_return(false) @field_type.stub(:errors).and_return(:error => 'foo') end it 'assigns to @event the given Event' do post :create, :visitor_field_type => {'foo' => 'bar'}, :event_id => @event.id assigns[:event].should == @event end it 'assigns to @data_types a list of data types' do FieldType.stub(:data_types_list).and_return('a' => 'A', 'b' => 'B', 'c' => 'C') post :create, :visitor_field_type => {'foo' => 'bar'}, :event_id => @event.id assigns[:data_types].should == [['A', 'a'], ['B', 'b'], ['C', 'c']] end it 'renders the new template' do post :create, :visitor_field_type => {'foo' => 'bar'}, :event_id => @event.id response.should render_template('new') end end end describe 'PUT update' do before(:each) do @event.stub_chain(:visitor_field_types, :find).and_return(@field_type) end it 'assigns to @field_type the given VisitorFieldType' do put :update, :visitor_field_type => {}, :event_id => @event.id, :id => @field_type.id assigns[:field_type].should equal(@field_type) end it 'updates the VisitorFieldType' do @field_type.should_receive(:update_attributes).with('foo' => 'bar') put :update, :visitor_field_type => {'foo' => 'bar'}, :event_id => @event.id, :id => @field_type.id end context 'when the VisitorFieldType is successfully updated' do before(:each) do @field_type.stub(:update_attributes).and_return(true) end it 'sets a flash[:notice] message' do put :update, :visitor_field_type => {'foo' => 'bar'}, :event_id => @event.id, :id => @field_type.id flash[:notice].should == I18n.t('visitor_field_types.update.success') end it 'redirects to the View Visitor Field Types page' do put :update, :visitor_field_type => {'foo' => 'bar'}, :event_id => @event.id, :id => @field_type.id response.should redirect_to(:action => 'index', :event_id => @event.id) end end context 'when the VisitorFieldType fails to be updated' do before(:each) do @field_type.stub(:update_attributes).and_return(false) @field_type.stub(:errors).and_return(:error => '') end it 'assigns to @event the given Event' do put :update, :visitor_field_type => {'foo' => 'bar'}, :event_id => @event.id, :id => @field_type.id assigns[:event].should == @event end it 'assigns to @data_types a list of data types' do FieldType.stub(:data_types_list).and_return('a' => 'A', 'b' => 'B', 'c' => 'C') put :update, :visitor_field_type => {'foo' => 'bar'}, :event_id => @event.id, :id => @field_type.id assigns[:data_types].should == [['A', 'a'], ['B', 'b'], ['C', 'c']] end it 'renders the edit template' do put :update, :visitor_field_type => {'foo' => 'bar'}, :event_id => @event.id, :id => @field_type.id response.should render_template('edit') end end end describe 'DELETE destroy' do before(:each) do @event.stub_chain(:visitor_field_types, :find).and_return(@field_type) end it 'destroys the VisitorFieldType' do @field_type.should_receive(:destroy) delete :destroy, :event_id => @event.id, :id => @field_type.id end it 'sets a flash[:notice] message' do delete :destroy, :event_id => @event.id, :id => @field_type.id flash[:notice].should == I18n.t('visitor_field_types.destroy.success') end it 'redirects to the View Visitor Field Types page' do delete :destroy, :event_id => @event.id, :id => @field_type.id response.should redirect_to(:action => 'index', :event_id => @event.id) end end end
mit
ViniciusWAHaas/DNS_stub_server-Node.js
dnsserver.js
37043
const dgram = require('dgram'); const server = dgram.createSocket('udp4'); const dns = require('dns'); const fs = require('fs'); fs.mkdirTreeSync = function (path, lastfolder) { path = path.split('/'); lastpath = "."; for (var a = 0; a < path.length - (lastfolder ? 0 : 1); a++) { try { fs.mkdirSync(lastpath = lastpath + "/" + path[a]); } catch (e) { if (e.code != 'EEXIST') throw new Error(e); } } return; } const now = function () { return (new Date).getTime(); } // /**********************************************************************************************************************\ // * LOAD and SAVE System * // * LOAD fires when start this *.js * // * SAVE fires when CTROL + Z or S is pressed * // * SAVE and QUIT fires when CTROL + C is pressed * // \**********************************************************************************************************************/ var DNS_SRV; try { DNS_SRV = JSON.parse(fs.readFileSync('./DNS_Queries.json', { encoding: 'utf8' }));} catch (E) { DNS_SRV = {};} process.stdin.setRawMode(true); process.stdin.on('data', function (key) { for (var a = 0; a < key.length; a++) { if (key[a] == 3) { // Ctrol + C console.log("Gracefully stop server"); server.close(); fs.writeFileSync('./DNS_Queries.json', JSON.stringify(DNS_SRV, null, '\t'), { encoding: 'utf8' }); process.stdin.setRawMode(false); process.exit(); } if (key[a] == 26 || key[a] == 19) { // Ctrol + Z fs.writeFileSync('./DNS_Queries.json', JSON.stringify(DNS_SRV, null, '\t'), { encoding: 'utf8' }); console.log("'DNS_Queries.json' Saved!"); } } }); setInterval(function () { fs.writeFileSync('./DNS_Queries.json', JSON.stringify(DNS_SRV, null, '\t'), { encoding: 'utf8' });}, 60 * 10000); process.on('uncaughtException', (err) => { fs.writeFileSync('./DNS_Queries.json', JSON.stringify(DNS_SRV, null, '\t'), { encoding: 'utf8' }); fs.writeSync(1, `Caught exception: ${err}\n`); }); // /**********************************************************************************************************************\ // * local storage for previous queries * // * * // * * // \**********************************************************************************************************************/ if (!DNS_SRV.CACHE) DNS_SRV.CACHE = new Object(); function GetDNameObject(Dname) { var DnameTree = Dname.split(".").reverse(); var cachelevel = DNS_SRV.CACHE; for (var a = 1; a < DnameTree.length; a++) if (!cachelevel[DnameTree[a]]) cachelevel = cachelevel[DnameTree[a]] = new Object(); else cachelevel = cachelevel[DnameTree[a]]; return cachelevel; } // /**********************************************************************************************************************\ // * DNS Server Listener * // * no need for introductions * // * https://nodejs.org/api/dgram.html#dgram_socket_send_msg_offset_length_port_address_callback * // \**********************************************************************************************************************/ var PORT = 53; var HOST = '127.0.0.1'; server.on('listening', function () { var address = server.address(); console.log('UDP Server listening on ' + address.address + ":" + address.port); }); server.on('error', (err) => { console.log(`server error:\n${err.stack}`); fs.writeFileSync('./DNS_Queries.json', JSON.stringify(DNS_SRV, null, '\t'), { encoding: 'utf8' }); process.exit(); }); lastquery = {}; server.on('message', function (message, remote) { var messager = new Buffer(message); try { // console.log(message); messager[2] += 0x80; // set response mode messager[3] += 0x0A; // set response code 0,1,2,3,4,5,9,10 server.send(message, remote.port, remote.address); // console.log(messager); //im lazy fuck you } catch (e) { console.log(e); } //The Real Deal var client = new UDPTemporarynamething(message, function (response) { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// console.log("\n" + JSON.stringify(new Date()).replace(/[^0-9T]/g, "") + " " + JSON.stringify(remote)); console.log("1>" + message.toString('hex')); console.log("2>" + messager.toString('hex')); console.log("3>" + response.toString('hex')); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //server.send(response, remote.port, remote.address); var DNS_Packet_IN = Buffer2DnsQuery(message); var DNS_Packet_OUT = Buffer2DnsQuery(response); var NamethisObj = GetDNameObject(DNS_Packet_IN.question[0].data)["|"]; if (!NamethisObj) NamethisObj = new Object([]); console.log("Header_IN: \t" + JSON.stringify(DNS_Packet_IN.header)); console.log("Header_OUT:\t" + JSON.stringify(DNS_Packet_OUT.header)); console.log("Question_IN: \t" + JSON.stringify(DNS_Packet_IN.question)); console.log("Question_OUT: \t" + JSON.stringify(DNS_Packet_OUT.question)); console.log("Answers_IN: "); DNS_Packet_IN.answer.forEach((a) => { console.log("\t\t" + JSON.stringify(a)); }) console.log("Answers_OUT: "); DNS_Packet_OUT.answer.forEach((a) => { console.log("\t\t" + JSON.stringify(a)); }) console.log("NameSpace_IN: "); DNS_Packet_IN.namespace.forEach((a) => { console.log("\t\t" + JSON.stringify(a)); }) console.log("NameSpace_OUT:"); DNS_Packet_OUT.namespace.forEach((a) => { console.log("\t\t" + JSON.stringify(a)); }) console.log("Extra_IN: " + DNS_Packet_IN.extraData); console.log("Extra_OUT: " + DNS_Packet_OUT.extraData); try { var foldertree = DNS_Packet_IN.question[0].data.split(".").reverse(); var Directory = "./RAW"; for (var a = 0; a < foldertree.length; a++) Directory += "/" + foldertree[a]; Directory += "/" + JSON.stringify(new Date()).replace(/[^0-9T]/g, ""); if (DNS_Packet_IN.extraData.length > 1) Directory += ".extradata"; Directory += ".bin"; Logger.saveThis(Directory, response); } catch (e) {} try { dns.lookup(DNS_Packet_IN.question[0].data, function () {}); } catch (e) {} DNS_Packet_OUT.answer.forEach((a) => { for (var i = 0; i < NamethisObj; i++) if (NamethisObj[i][0] == a.data) { NamethisObj[i] = [a.data, a.size, a.qclass, a.qtype, now()]; return; } NamethisObj.push([a.data, a.size, a.qclass, a.qtype, now()]); }); DNS_Packet_OUT.namespace.forEach((a) => { for (var i = 0; i < NamethisObj; i++) if (NamethisObj[i][0] == a.data) { NamethisObj[i] = [a.data, a.size, a.qclass, a.qtype, now(), a.serialCode]; return; } NamethisObj.push([a.data, a.size, a.qclass, a.qtype, now(), a.serialCode]); }); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// }, function (err) { if (!(err === "Timeout")) console.log("Error:" + Buffer2DnsQuery(message).question + "|" + err); }); }); server.bind(PORT); //, HOST); // /**********************************************************************************************************************\ // * DNS Client * // * no need for introductions * // * https://nodejs.org/api/dgram.html#dgram_socket_send_msg_offset_length_port_address_callback * // \**********************************************************************************************************************/ var counterqueryidk = 50000; var UDPTemporarynamething = function (messg, callback, errorThis) { if (!callback) return; if (!errorThis) errorThis = function () {}; // A Client for forwarding msg var client = dgram.createSocket('udp4'); // client.on('listening', function(){console.log(JSON.stringify(client.address()))}); client.on('error', function (err) { console.log(`server error:\n${err.stack}`); client.close(); errorThis(err); }); client.on('message', callback); client.bind(++counterqueryidk, function () { setTimeout(function () { client.close(); client.removeAllListeners(); errorThis("Timeout"); }, 1000 * 30); client.send(messg, 53, '10.8.0.20'); //,function(err,bytes){if(err)return;console.log("wot\t"+JSON.stringify(bytes));server.send(msg, remote.port, remote.address);}); }); if (counterqueryidk >= 60000) counterqueryidk = 50000; return client; }; // /**********************************************************************************************************************\ // * A Logger for stuff * // * * // * * // \**********************************************************************************************************************/ var Logger = new Object(); Logger.folderoutput = function () { var datetime = JSON.stringify(new Date()).replace(/[^0-9T]/g, ""); var LogFileOutput = ""; LogFileOutput += datetime.substr(0, 4); LogFileOutput += "/" + datetime.substr(4, 2); LogFileOutput += "/" + datetime.substr(6, 2); return [LogFileOutput, datetime]; }; Logger.saveThis = function (directory, content) { fs.mkdirTreeSync(directory, false); var quick; try { quick = fs.createWriteStream(directory); } catch (e) {} try { quick.write(content); } catch (e) {} try { quick.close(); } catch (e) {} } // /**********************************************************************************************************************\ // * DNS PACKET DEASSEMBLER * // * * // * under development , yet * // \**********************************************************************************************************************/ // TODO : Learn class /* File: OBJ\DNSQuery.json */ class DNSQuery { constructor() { this.raw = new Buffer([]); this.header = { id: 0, qr: false, opcode: 0, aa: false, tc: false, rd: false, ra: false, auth: false, authdata: false, z: 0, rcode: 0, qdcount: 0, ancount: 0, nscount: 0, arcount: 0 }; this.question = []; this.answer = []; this.namespace = []; } toString() {} print() {}; }; // usage: var variablenome = ( new DNSQuery ) /* File: OBJ\DNScodes.json */ // http://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml // https://tools.ietf.org/html/rfc6895 var DNSqtype = { 1: 'A', 2: 'NS', 3: 'MD', 4: 'MF', 5: 'CNAME', 6: 'SOA', 7: 'MB', 8: 'MG', 9: 'MR', 10: 'NULL', 11: 'WKS', 12: 'PTR', 13: 'HINFO', 14: 'MINFO', 15: 'MX', 16: 'TXT', 28: 'AAAA', 255: '*' }; var DNSqclass = { 0: "Reserved", 1: 'IN', 2: "CS", 3: "CH", 4: "HS", 254: "NONE", 255: "ANY" }; var DNSqclassName = { 0: "Reserved", 1: 'Internet', 2: "CSNET", 3: "Chaos", 4: "Hesiod", 254: "none", 255: "*" }; var DNSrpcode = { 0: "NOERROR", 1: "FORMERR", 2: "SERVFAIL", 3: "NXDOMAIN", 4: "NOTIMP", 5: "REFUSED", 6: "YXDOMAIN", 7: "YXRRSET", 8: "NXRRSET", 9: "NOTAUTH", 10: "NOTZONE", 11: "SSOPNOTIMP", 16: "BADVERS", 16: "BADSIG", 17: "BADKEY", 18: "BADTIME", 19: "BADMODE", 20: "BADNAME", 21: "BADALG", 22: "BADTRUNC", 23: "BADCOOKIE" }; var DNSrpcodeName = { 0: "No Error", 1: "Format Error", 2: "Server Failure", 3: "Non-Existent Domain", 4: "Not Implemented", 5: "Query Refused", 6: "Name Exists when it should not", 7: "RR Set Exists when it should not", 8: "RR Set that should exist does not", 9: "Server Not Authoritative for zone", 10: "Name not contained in zone", 16: "Bad OPT Version", 6: "TSIG Signature Failure", 17: "Key not recognized", 18: "Signature out of time window", 19: "Bad TKEY Mode", 20: "Duplicate key name", 21: "Algorithm not supported", 22: "Bad Truncation", 23: "Bad/missing Server Cookie" }; var DNSopcodeName = { 0: "Query", 1: "Inverse Query", 2: "Status", 4: "Notify", 5: "Update" }; /*████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████*/ /* Quick Lab to bullshit. > 1 << 0 1 > 1 << 7 128 > 1 << 7 128 > 0xff00 65280 > 0xff00 >> 8 255 > 0xff00 >> 8 << 8 65280 > 0xfff0 >> 8 << 8 65280 > 0xfff0 65520 > 0xfff0 >> 8 << 8 65280 > 0xff00 65280 quicklab seems to realocate all bits from place , those outsite are thrown away, interesting */ function DnsQuery2Buffer(DNSQuery) { var BufferContent = []; BufferContent[0] = 0; BufferContent[0] = DNSQuery.header.id >> 8 << 8; // AAAA AAAA ---- ---- BufferContent[1] = DNSQuery.header.id - BufferContent[0] << 8; // ---- ---- AAAA AAAA BufferContent[2] = (DNSQuery.header.qr ? 1 : 0) << 7; // B--- ---- BufferContent[2] += DNSQuery.header.opcode << 3; // -CCC C--- BufferContent[2] += (DNSQuery.header.aa ? 1 : 0) << 2; // ---- -D-- BufferContent[2] += (DNSQuery.header.tc ? 1 : 0) << 1; // ---- --E- BufferContent[2] += (DNSQuery.header.ta ? 1 : 0) << 0; // ---- ---F BufferContent[3] = (DNSQuery.header.ra ? 1 : 0) << 0; // G--- ---- BufferContent[3] += (DNSQuery.header.z ? 1 : 0) << 0; // -H-- ---- BufferContent[3] += (DNSQuery.header.auth ? 1 : 0) << 0; // --N- ---- BufferContent[3] += (DNSQuery.header.authdata ? 1 : 0) << 0; // ---O ---- BufferContent[3] += DNSQuery.header.rcode; // ---- IIII BufferContent[4] = DNSQuery.header.qdcount >> 8 << 8; // JJJJ JJJJ ---- ---- BufferContent[5] = DNSQuery.header.qdcount - BufferContent[4] << 8; // ---- ---- JJJJ JJJJ BufferContent[6] = DNSQuery.header.ancount >> 8 << 8; // AAAA AAAA ---- ---- BufferContent[7] = DNSQuery.header.ancount - BufferContent[6] << 8; // ---- ---- AAAA AAAA BufferContent[8] = DNSQuery.header.nscount >> 8 << 8; // AAAA AAAA ---- ---- BufferContent[9] = DNSQuery.header.nscount - BufferContent[8] << 8; // ---- ---- AAAA AAAA BufferContent[10] = DNSQuery.header.arcount >> 8 << 8; // AAAA AAAA ---- ---- BufferContent[11] = DNSQuery.header.arcount - BufferContent[10] << 8; // ---- ---- AAAA AAAA DNSQuery.question DNSQuery.answer DNSQuery.namespace for (var a = 0; a < BufferContent.length; a++) if (BufferContent[a] >= 256) throw new Error("Something Hapenned while DnsQuery2Buffer():"); return Buffer.from(BufferContent); } /*████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████*/ // function qname2name(typeof Buffer){ return typeof String; } var qname2name = function (qname, namefrom) { // cdn.syndication.twimg.com. -> if (!namefrom) namefrom = ""; var domain = new String(); var position = 0; while (qname[position] != 0 && position < qname.length) // you guys have no idea how to get mad ( psychological speaking ) if (position + qname[position] < qname.length + 1) domain = domain + qname.toString('utf8').substring(position + 1, position += qname[position] + 1) + '.'; else break; /* //domain=domain + qname.toString('utf8').substring(position+1,position+=qname[position]+1) + namefrom.slice(namefrom.length-(position+qname[position])-1,namefrom.length-1) */ return domain; if (position++ < qname.length) { while (qname[position] != 0 && position < qname.length); // you guys have no idea how to get mad ( psychological speaking ) domain = domain + qname.toString('utf8').substring(position + 1, position += qname[position] + 1) + '.'; return domain; } return domain; }; /*████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████*/ // function name2qname(typeof String){ return typeof String; } var name2qname = function (domain) { var tokens = domain.split("."); var qname = []; var offset = 0; for (var i = 0; i < tokens.length; i++) { qname[offset++] = tokens[i].length; for (var j = 0; j < tokens[i].length; j++) { qname[offset++] = tokens[i].charCodeAt(j); } } qname[offset] = 0; return Buffer.from(qname); }; /*████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████*/ // function Buffer2Number(typeof Buffer){ return typeof Number } var Buffer2Number = function (input) { input = input.reverse(); var output = 0; for (var a = input.length; a > 0; a--) { output += input[a] << (8 * (a)); } output += input[0]; return output; } // Buffer2Number(Buffer.from([0x00,0x00])); // Buffer2Number(Buffer.from([0x00,0x01])); // Buffer2Number(Buffer.from([0x00,0x09])); // Buffer2Number(Buffer.from([0x00,0x0F])); // Buffer2Number(Buffer.from([0x00,0x10])); // Buffer2Number(Buffer.from([0x00,0xF0])); // Buffer2Number(Buffer.from([0x01,0x00])); // Buffer2Number(Buffer.from([0x01,0x01])); // Buffer2Number(Buffer.from([0x01,0x04])); // takes every INT8 in Buffer and convert to Number /*████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████*/ // function Number2Buffer(typeof Number){ return typeof Buffer } var Number2Buffer = function (input, BufSize) { var output = new Buffer(BufSize); output for (var a = input.length; a > 0; a--) { output += input[a] << (8 * (a)); } output += input[0]; return output; } // takes every INT8 in Buffer and convert to Number /*████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████*/ // function Number2Boolean(typeof Number){ return typeof Array[typeof Boolean, ... , typeof Boolean] } var Number2Boolean = function (input, valueA, valueB) { if (typeof input != 'number') return []; var output = []; var multiplier = 0; while (1 << multiplier++ < input) output[multiplier - 1] = (typeof valueA != "undefined" ? valueA : false); while (--multiplier >= 0) { if (input >= 1 << multiplier) { input -= 1 << multiplier; output[multiplier] = (typeof valueB != "undefined" ? valueB : true); } } return output; } /*████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████*/ // function Boolean2Number(typeof Array[typeof Boolean, ... , typeof Boolean]){ return typeof Number } var Boolean2Number = function (input) { if (typeof input != "object") return NaN; var output = 0; var multiplier = 0; while (typeof input[multiplier] != 'undefined') { if (input[multiplier]) output += 1 << multiplier; ++multiplier; } while (--multiplier >= 0) { if (input >= 1 << multiplier) { input -= 1 << multiplier; output[multiplier] = (typeof valueB != "undefined" ? valueB : true); } } return output; } /*████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████*/ /* File: DNS\Buffer2Query.js */ // /**********************************************************************************************************************\ // * DNS Query Header Package / Packet is like this: ( each letter is a bit | divided in 8 bits = 1 Byte ) * // * * // * 8bit 8bit * // * AAAAAAAA AAAAAAAA * // * BCCCCDEF GHNOIIII * // * JJJJJJJJ JJJJJJJJ * // * KKKKKKKK KKKKKKKK * // * LLLLLLLL LLLLLLLL * // * MMMMMMMM MMMMMMMM * // * ######## ######## * // * * // * A = INT16 Identification of the packet * // * B = BOOL Query OR Response * // * C = INT4 Question Code * // * D = BOOL Authority * // * E = BOOL Truncated * // * F = BOOL Recursion Desired * // * G = BOOL Recursion Avaliable * // * H = ZERO nothing. really * // * N = BOOL Answer authenticated (wireshark says that, idk) * // * O = BOOL Authentication Data (Again Wireshark) * // * I = INT4 Response Code * // * J = INT16 Amount of Questions * // * K = INT16 Amount of Answers * // * L = INT16 Amount of NS things * // * M = INT16 Amount of AR things * // * # = ???? Flexibe content depends on the J,K,L and M * // * * // * details of more tecnical info here: https://tools.ietf.org/html/rfc1035#section-4.1.1 * // * details of more tecnical info here: https://tools.ietf.org/html/rfc6895#section-2 * // * * // * * // * DNS Query Questions (J variable) Package or Section where the questions is at. * // * this place require explanation * // * * // * 8bit 8bit * // * NNNNNNNN OOOOOOOO * // * OOOOOOOO OOOOOOOO * // * OOOOOOOO OOOOOOOO * // * OOOOOOOO NNNNNNNN * // * OOOOOOOO OOOOOOOO * // * OOOOOOOO NNNNNNNN * // * PPPPPPPP PPPPPPPP * // * QQQQQQQQ QQQQQQQQ * // * * // * N = INT8 The amount of next INT8 as CHARs to be in query * // * O = INT8 Charactere in the table ASC8 ( or ASC7 , idk yet, go easy or claim your superiority in the comments section ) // * P = INT16 code of que requisition. 1 for A ( IPv4 ) , 5 for an alias ( Another name to search for ) , and others 256 codes possible // * Q = INT16 idk , why this exist. why? if this thing is not 1 ( ONE ) it is not INTERNET related request. * // * * // * in the example there i put NOOOOOONOOONPPQQ order, why? look in the line below * // * .GOOGLE.COM. did you notice? N is . (dot) and the next O chars to be show * // * the first N is 0x06, means that the next bytes is chars which is OOOOOO or GOOGLE * // * then again is N with 0x03 saying the next OOO is chars. or COM * // * the last N contais 0x00. no next chars, or end of the string to ask|query * // * P and Q is just class and type of the N and O Bytes type. * // * * // * * // * * // * * // * * // * * // * * // * * // * * // * Vinicius Willer Alencar Haas 2016.12.26 * // * Build for learning purposes,and have a Personal DNS Server. * // \**********************************************************************************************************************/ function Buffer2DnsQuery(req) { var sliceBits = function (b, off, len) { if (!len) len = off + 1; var s = 7 - (off + len - 1); b = b >>> s; return b & ~(0xff << len); }; var query = new DNSQuery; query.raw = req.toString("hex"); var tmpSlice; var tmpByte; query.header = {}; // Build Header query.header.id = Buffer2Number(req.slice(0, 2)); // AAAAAAAA AAAAAAAA tmpSlice = req.slice(2, 3); // BCCCCDEF tmpByte = tmpSlice.toString('binary', 0, 1).charCodeAt(0); query.header.qr = sliceBits(tmpByte, 0, 1) ? true : false; // B query.header.opcode = sliceBits(tmpByte, 1, 4); // CCCC query.header.aa = sliceBits(tmpByte, 5, 1) ? true : false; // D query.header.tc = sliceBits(tmpByte, 6, 1) ? true : false; // E query.header.rd = sliceBits(tmpByte, 7, 1) ? true : false; // F tmpSlice = req.slice(3, 4); // GHNOIIII tmpByte = tmpSlice.toString('binary', 0, 1).charCodeAt(0); query.header.ra = sliceBits(tmpByte, 0, 1) ? true : false; // G query.header.z = sliceBits(tmpByte, 1, 1); // H query.header.auth = sliceBits(tmpByte, 2, 1) ? true : false; // N query.header.authdata = sliceBits(tmpByte, 3, 1) ? true : false; // O query.header.rcode = sliceBits(tmpByte, 4, 4); // IIII query.header.qdcount = Buffer2Number(req.slice(4, 6)); // JJJJJJJJ JJJJJJJJ query.header.ancount = Buffer2Number(req.slice(6, 8)); // KKKKKKKK KKKKKKKK query.header.nscount = Buffer2Number(req.slice(8, 10)); // LLLLLLLL LLLLLLLL query.header.arcount = Buffer2Number(req.slice(10, 12)); // MMMMMMMM MMMMMMMM // pointer to gather a range of buffer data var position = 12; // Simple resolver to a human comprehension(?) var resolveDataThing = function (qtype, dataThing, extrapayloadthing) { if (!extrapayloadthing) extrapayloadthing = ""; switch (qtype) { case 1: /*IPv4 */ return "" + dataThing[0] + "." + dataThing[1] + "." + dataThing[2] + "." + dataThing[3] + ""; break; case 5: /*CNAME*/ return qname2name(dataThing, extrapayloadthing); break; case 6: /* SOA */ return qname2name(dataThing, extrapayloadthing); break; // special snowflake,multiple responses in a buffer create qnameSOA2String() case 12: /* PTR */ return qname2name(dataThing, extrapayloadthing); break; case 28: /*IPv6 */ return (function (input) { var output = ""; for (var ip = 0; ip < 16; ip++) output += ((ip + 1) % 2 ? ";" : "") + (input[ip] < 10 ? "0" : "") + input[ip].toString(16); return output.replace(";", ""); namefrom.length })(dataThing); default: /* IDK */ return dataThing; break; } return dataThing; } // Gathering Questions query.question = []; var amount = query.header.qdcount; for (var q = 0; q < amount; q++) { if (req.length < position) break; // dies if overflow, unstable code protection or random bullshit var lastposition = position; var question = new Object; while (req[position++] != 0 && position < req.length); // mark between the first N and the last N question.data = resolveDataThing(5, req.slice(lastposition, position)); question.qtype = Buffer2Number(req.slice(position, position += 2)); question.qclass = Buffer2Number(req.slice(position, position += 2)); query.question[q] = question; } // Gathering Answers TODO: understando those ████ers. i dont get it, and it is wasting my hobby time with this shiet // https://tools.ietf.org/html/rfc1035#section-4.1.3 query.answer = []; var amount = query.header.ancount; for (var a = 0; a < amount; a++) { if (req.length < position) break; // dies if overflow, unstable code protection or random bullshit var answer = new Object; answer.code = Buffer2Number(req.slice(position, position += 2)); answer.qtype = Buffer2Number(req.slice(position, position += 2)); answer.qclass = Buffer2Number(req.slice(position, position += 2)); answer.TTL = Buffer2Number(req.slice(position, position += 4)); answer.size = size = Buffer2Number(req.slice(position, position += 2)); answer.data = resolveDataThing(answer.qtype, req.slice(position, position += size), query.question[0].data); query.answer[a] = answer; } // Gathering Answers / Authoritative nameservers // TODO: URL HERE query.namespace = []; var amount = query.header.nscount; for (var n = 0; n < amount; n++) { if (req.length < position) break; // dies if overflow, unstable code protection or random bullshit var namespace = new Object; namespace.code = Buffer2Number(req.slice(position, position += 2)); namespace.qtype = qtype = Buffer2Number(req.slice(position, position += 2)); namespace.qclass = Buffer2Number(req.slice(position, position += 2)); namespace.TTL = Buffer2Number(req.slice(position, position += 4)); namespace.size = size = Buffer2Number(req.slice(position, position += 2)); namespace.size += -20; namespace.data = resolveDataThing(qtype, req.slice(position, position += size - 20), query.question[0].data); // no need to remember position now. learned a easy way of doing it. namespace.serialCode = Buffer2Number(req.slice(position, position += 4)); namespace.RefreshInterval = Buffer2Number(req.slice(position, position += 4)); namespace.RetryInterval = Buffer2Number(req.slice(position, position += 4)); namespace.Expiration = Buffer2Number(req.slice(position, position += 4)); namespace.minimunTTL = Buffer2Number(req.slice(position, position += 4)); query.namespace[n] = namespace; } // Aditional will be required query.extraData = req.slice(position, req.length); return query; }
mit
leotsarev/joinrpg-net
src/PscbApi/Models/PaymentMessage.cs
5143
// ReSharper disable IdentifierTypo // ReSharper disable InconsistentNaming using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Newtonsoft.Json; namespace PscbApi.Models { /// <summary> /// Payment message /// </summary> /// <remarks> /// See https://docs.pscb.ru/oos/api.html#api-magazina-sozdanie-platezha-parametry-zaprosa for details /// </remarks> public class PaymentMessage : IValidatableObject { /// <summary> /// Minimal acceptable payment in RUR /// </summary> public const decimal MinPayment = 0.01M; /// <summary> /// Payment sum in RUR /// </summary> [JsonProperty("amount")] public decimal Amount { get; set; } /// <summary> /// Order Id specified by store /// </summary> [StringLength(20, MinimumLength = 4, ErrorMessage = "Length must be from 4 to 20 characters")] [JsonProperty("orderId")] public string OrderId { get; set; } /// <summary> /// Order Id as to be displayed to Payer /// </summary> /// <remarks> /// If not set, value from <see cref="OrderId"/> used /// </remarks> [StringLength(20, MinimumLength = 4, ErrorMessage = "Length must be from 4 to 20 characters")] [JsonProperty("showOrderId", DefaultValueHandling = DefaultValueHandling.Ignore)] public string OrderIdDisplayValue { get; set; } /// <summary> /// Payments details, will be shown to Payer during payment process /// </summary> [MaxLength(2048)] [JsonProperty("details", DefaultValueHandling = DefaultValueHandling.Ignore)] public string Details { get; set; } /// <summary> /// Payment method. If not set, all payment methods will be used. User must to choose one /// at payment page /// </summary> [JsonProperty("paymentMethod", DefaultValueHandling = DefaultValueHandling.Ignore)] public PscbPaymentMethod? PaymentMethod { get; set; } /// <summary> /// Identifier of a Payer issued by store /// </summary> [StringLength(20, MinimumLength = 4, ErrorMessage = "Length must be from 4 up to 20 characters")] [JsonProperty("customerAccount")] public string CustomerAccount { get; set; } /// <summary> /// Comment created by a Payer to hist payment /// </summary> [MaxLength(2048)] [JsonProperty("customerComment", DefaultValueHandling = DefaultValueHandling.Ignore)] public string CustomerComment { get; set; } /// <summary> /// Payer email /// </summary> [MaxLength(512)] [EmailAddress] [JsonProperty("customerEmail", DefaultValueHandling = DefaultValueHandling.Ignore)] public string CustomerEmail { get; set; } /// <summary> /// Payer phone number in international format /// </summary> [MaxLength(32)] [Phone] [JsonProperty("customerPhone", DefaultValueHandling = DefaultValueHandling.Ignore)] public string CustomerPhone { get; set; } /// <summary> /// Url to redirect after successful payment /// </summary> [MaxLength(1024)] [JsonProperty("successUrl", DefaultValueHandling = DefaultValueHandling.Ignore)] public string SuccessUrl { get; set; } /// <summary> /// Url to redirect after failed payment /// </summary> [MaxLength(1024)] [JsonProperty("failUrl", DefaultValueHandling = DefaultValueHandling.Ignore)] public string FailUrl { get; set; } /// <summary> /// Payment page language code according to ISO 639-1 /// </summary> /// <remarks> /// Allowed values are: "en", "ru" /// </remarks> [MaxLength(2)] [JsonProperty("displayLanguage", DefaultValueHandling = DefaultValueHandling.Ignore)] public string UILanguage { get; set; } /// <summary> /// true if this payment has to be recurrent /// </summary> /// <remarks> /// See https://docs.pscb.ru/oos/advanced.html#dopolnitelnye-opcii-rekurrentnye-platezhi for details /// </remarks> [JsonProperty("recurrentable", DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? RecurrentPayment { get; set; } /// <summary> /// Additional data /// </summary> [Required] [JsonProperty("data")] public PaymentMessageData Data { get; set; } /// <summary> /// Random string /// </summary> public string nonce { get; } = Guid.NewGuid().ToString(); /// <inheritdoc /> public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (Amount < MinPayment) { yield return new ValidationResult($"{nameof(Amount)} could not be less than {MinPayment}", new[] { nameof(Amount) }); } } } }
mit
MaryJaneCoin/maryjane
src/qt/locale/bitcoin_la.ts
118196
<?xml version="1.0" ?><!DOCTYPE TS><TS language="la" version="2.1"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About MaryJaneCoin</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;MaryJaneCoin&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The MaiaCoin developers Copyright © 2014 The MaryJaneCoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation>Hoc est experimentale programma. Distributum sub MIT/X11 licentia programmatum, vide comitantem plicam COPYING vel http://www.opensource.org/licenses/mit-license.php. Hoc productum continet programmata composita ab OpenSSL Project pro utendo in OpenSSL Toolkit (http://www.openssl.org/) et programmata cifrarum scripta ab Eric Young (eay@cryptsoft.com) et UPnP programmata scripta ab Thomas Bernard.</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Double-click to edit address or label</source> <translation>Dupliciter-clicca ut inscriptionem vel titulum mutes</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Crea novam inscriptionem</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Copia inscriptionem iam selectam in latibulum systematis</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location line="-46"/> <source>These are your MaryJaneCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <source>&amp;Copy Address</source> <translation>&amp;Copia Inscriptionem</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a MaryJaneCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Dele active selectam inscriptionem ex enumeratione</translation> </message> <message> <location line="-14"/> <source>Verify a message to ensure it was signed with a specified MaryJaneCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Dele</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+65"/> <source>Copy &amp;Label</source> <translation>Copia &amp;Titulum</translation> </message> <message> <location line="+2"/> <source>&amp;Edit</source> <translation>&amp;Muta</translation> </message> <message> <location line="+250"/> <source>Export Address Book Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Comma Separata Plica (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Titulus</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Inscriptio</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(nullus titulus)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Dialogus Tesserae</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Insere tesseram</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nova tessera</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Itera novam tesseram</translation> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>For staking only</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+35"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Insero novam tesseram cassidili.&lt;br/&gt;Sodes tessera &lt;b&gt;10 pluriumve fortuitarum litterarum&lt;/b&gt; utere aut &lt;b&gt;octo pluriumve verborum&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Cifra cassidile</translation> </message> <message> <location line="+7"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Huic operationi necesse est tessera cassidili tuo ut cassidile reseret.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Resera cassidile</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Huic operationi necesse est tessera cassidili tuo ut cassidile decifret.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Decifra cassidile</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Muta tesseram</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Insero veterem novamque tesseram cassidili.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Confirma cifrationem cassidilis</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR COINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Certusne es te velle tuum cassidile cifrare?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>GRAVE: Oportet ulla prioria conservata quae fecisti de plica tui cassidilis reponi a nove generata cifrata plica cassidilis. Propter securitatem, prioria conservata de plica non cifrata cassidilis inutilia fiet simul atque incipis uti novo cifrato cassidili.</translation> </message> <message> <location line="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Monitio: Litterae ut capitales seratae sunt!</translation> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation>Cassidile cifratum</translation> </message> <message> <location line="-58"/> <source>MaryJaneCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Cassidile cifrare abortum est</translation> </message> <message> <location line="-56"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Cassidile cifrare abortum est propter internum errorem. Tuum cassidile cifratum non est.</translation> </message> <message> <location line="+7"/> <location line="+50"/> <source>The supplied passphrases do not match.</source> <translation>Tesserae datae non eaedem sunt.</translation> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation>Cassidile reserare abortum est.</translation> </message> <message> <location line="+1"/> <location line="+12"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Tessera inserta pro cassidilis decifrando prava erat.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Cassidile decifrare abortum est.</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Tessera cassidilis successa est in mutando.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+282"/> <source>Sign &amp;message...</source> <translation>Signa &amp;nuntium...</translation> </message> <message> <location line="+251"/> <source>Synchronizing with network...</source> <translation>Synchronizans cum rete...</translation> </message> <message> <location line="-319"/> <source>&amp;Overview</source> <translation>&amp;Summarium</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Monstra generale summarium cassidilis</translation> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation>&amp;Transactiones</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Inspicio historiam transactionum</translation> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>&amp;Receive coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="-7"/> <source>&amp;Send coins</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>E&amp;xit</source> <translation>E&amp;xi</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Exi applicatione</translation> </message> <message> <location line="+6"/> <source>Show information about MaryJaneCoin</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Informatio de &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Monstra informationem de Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Optiones</translation> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Cifra Cassidile...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Conserva Cassidile...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Muta tesseram...</translation> </message> <message numerus="yes"> <location line="+259"/> <source>~%n block(s) remaining</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source> <translation type="unfinished"/> </message> <message> <location line="-256"/> <source>&amp;Export...</source> <translation type="unfinished"/> </message> <message> <location line="-64"/> <source>Send coins to a MaryJaneCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Modify configuration options for MaryJaneCoin</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Encrypt or decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup wallet to another location</source> <translation>Conserva cassidile in locum alium</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Muta tesseram utam pro cassidilis cifrando</translation> </message> <message> <location line="+10"/> <source>&amp;Debug window</source> <translation>Fenestra &amp;Debug</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Aperi terminalem debug et diagnosticalem</translation> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation>&amp;Verifica nuntium...</translation> </message> <message> <location line="-202"/> <source>MaryJaneCoin</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet</source> <translation>Cassidile</translation> </message> <message> <location line="+180"/> <source>&amp;About MaryJaneCoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Monstra/Occulta</translation> </message> <message> <location line="+9"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>&amp;File</source> <translation>&amp;Plica</translation> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation>&amp;Configuratio</translation> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation>&amp;Auxilium</translation> </message> <message> <location line="+12"/> <source>Tabs toolbar</source> <translation>Tabella instrumentorum &quot;Tabs&quot;</translation> </message> <message> <location line="+8"/> <source>Actions toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+9"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+0"/> <location line="+60"/> <source>MaryJaneCoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+75"/> <source>%n active connection(s) to MaryJaneCoin network</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+40"/> <source>Downloaded %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+413"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-403"/> <source>%n second(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="-312"/> <source>About MaryJaneCoin card</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about MaryJaneCoin card</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>&amp;Unlock Wallet...</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+297"/> <source>%n minute(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Up to date</source> <translation>Recentissimo</translation> </message> <message> <location line="+7"/> <source>Catching up...</source> <translation>Persequens...</translation> </message> <message> <location line="+10"/> <source>Last received block was generated %1.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation>Transactio missa</translation> </message> <message> <location line="+1"/> <source>Incoming transaction</source> <translation>Transactio incipiens</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Dies: %1 Quantitas: %2 Typus: %3 Inscriptio: %4 </translation> </message> <message> <location line="+100"/> <location line="+15"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid MaryJaneCoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Cassidile &lt;b&gt;cifratum&lt;/b&gt; est et iam nunc &lt;b&gt;reseratum&lt;/b&gt;</translation> </message> <message> <location line="+10"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Cassidile &lt;b&gt;cifratum&lt;/b&gt; est et iam nunc &lt;b&gt;seratum&lt;/b&gt;</translation> </message> <message> <location line="+25"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+76"/> <source>%n second(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s)</source> <translation><numerusform>%n hora</numerusform><numerusform>%n horae</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n dies</numerusform><numerusform>%n dies</numerusform></translation> </message> <message> <location line="+18"/> <source>Not staking</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+109"/> <source>A fatal error occurred. MaryJaneCoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+90"/> <source>Network Alert</source> <translation>Monitio Retis</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Amount:</source> <translation>Quantitas:</translation> </message> <message> <location line="+32"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="+551"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change:</source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>List mode</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Amount</source> <translation>Quantitas</translation> </message> <message> <location line="+5"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Address</source> <translation>Inscriptio</translation> </message> <message> <location line="+5"/> <source>Date</source> <translation>Dies</translation> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation>Confirmatum</translation> </message> <message> <location line="+5"/> <source>Priority</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="-515"/> <source>Copy address</source> <translation>Copia inscriptionem</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copia titulum</translation> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation>Copia quantitatem</translation> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation>Copia transactionis ID</translation> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+317"/> <source>highest</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium-high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>low-medium</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>low</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>lowest</source> <translation type="unfinished"/> </message> <message> <location line="+155"/> <source>DUST</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transactions with higher priority get more likely into a block. This label turns red, if the priority is smaller than &quot;medium&quot;. This means a fee of at least %1 per kb is required.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+66"/> <source>(no label)</source> <translation>(nullus titulus)</translation> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>(change)</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Muta Inscriptionem</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Titulus</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Inscriptio</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+20"/> <source>New receiving address</source> <translation>Nova inscriptio accipiendi</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Nova inscriptio mittendi</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Muta inscriptionem accipiendi</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Muta inscriptionem mittendi</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Inserta inscriptio &quot;%1&quot; iam in libro inscriptionum est.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid MaryJaneCoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Non potuisse cassidile reserare</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Generare novam clavem abortum est.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+420"/> <location line="+12"/> <source>MaryJaneCoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Optiones</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Princeps</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Solve &amp;mercedem transactionis</translation> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Reserve</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start MaryJaneCoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start MaryJaneCoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Detach databases at shutdown</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation>&amp;Rete</translation> </message> <message> <location line="+6"/> <source>Automatically open the MaryJaneCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Designa portam utendo &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the MaryJaneCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>&amp;IP vicarii:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Porta:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Porta vicarii (e.g. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS &amp;Versio:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>SOCKS versio vicarii (e.g. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Fenestra</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Monstra tantum iconem in tabella systematis postquam fenestram minifactam est.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minifac in tabellam systematis potius quam applicationum</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Minifac potius quam exire applicatione quando fenestra clausa sit. Si haec optio activa est, applicatio clausa erit tantum postquam selegeris Exi in menu.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>M&amp;inifac ad claudendum</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;UI</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>&amp;Lingua monstranda utenti:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting MaryJaneCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Unita qua quantitates monstrare:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Selige praedefinitam unitam subdivisionis monstrare in interfacie et quando nummos mittere</translation> </message> <message> <location line="+9"/> <source>Whether to show MaryJaneCoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Monstra inscriptiones in enumeratione transactionum</translation> </message> <message> <location line="+7"/> <source>Whether to show coin control features or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Cancella</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+55"/> <source>default</source> <translation>praedefinitum</translation> </message> <message> <location line="+149"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting MaryJaneCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Inscriptio vicarii tradita non valida est.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Schema</translation> </message> <message> <location line="+33"/> <location line="+231"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the MaryJaneCoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-160"/> <source>Stake:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-107"/> <source>Wallet</source> <translation>Cassidile</translation> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>Immature:</source> <translation>Immatura:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Fossum pendendum quod nondum maturum est</translation> </message> <message> <location line="+20"/> <source>Total:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Recentes transactiones&lt;/b&gt;</translation> </message> <message> <location line="-108"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Total of coins that was staked, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+113"/> <location line="+1"/> <source>out of sync</source> <translation>non synchronizato</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Nomen clientis</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+348"/> <source>N/A</source> <translation>N/A</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Versio clientis</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informatio</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Utens OpenSSL versione</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Tempus initiandi</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Rete</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Numerus conexionum</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Catena frustorum</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Numerus frustorum iam nunc</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Aestimatus totalis numerus frustorum</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Hora postremi frusti</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Aperi</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the MaryJaneCoin-Qt help message to get a list with possible MaryJaneCoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Terminale</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Dies aedificandi</translation> </message> <message> <location line="-104"/> <source>MaryJaneCoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>MaryJaneCoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Debug catalogi plica</translation> </message> <message> <location line="+7"/> <source>Open the MaryJaneCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Vacuefac terminale</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-33"/> <source>Welcome to the MaryJaneCoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Utere sagittis sursum deorsumque ut per historiam naviges, et &lt;b&gt;Ctrl+L&lt;/b&gt; ut scrinium vacuefacias.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Scribe &lt;b&gt;help&lt;/b&gt; pro summario possibilium mandatorum.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+182"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Mitte Nummos</translation> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation type="unfinished"/> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Amount:</source> <translation>Quantitas:</translation> </message> <message> <location line="+22"/> <location line="+86"/> <location line="+86"/> <location line="+32"/> <source>0.00 MARYJ</source> <translation type="unfinished"/> </message> <message> <location line="-191"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation>Mitte pluribus accipientibus simul</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Adde &amp;Accipientem</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Vacuefac &amp;Omnia</translation> </message> <message> <location line="+28"/> <source>Balance:</source> <translation>Pendendum:</translation> </message> <message> <location line="+16"/> <source>123.456 MARYJ</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Confirma actionem mittendi</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Mitte</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-173"/> <source>Enter a MaryJaneCoin address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Copia quantitatem</translation> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+86"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Confirma mittendum nummorum</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The recipient address is not valid, please recheck.</source> <translation>Inscriptio accipientis non est valida, sodes reproba.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Oportet quantitatem ad pensandum maiorem quam 0 esse.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Quantitas est ultra quod habes.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Quantitas est ultra quod habes cum merces transactionis %1 includitur.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Geminata inscriptio inventa, tantum posse mittere ad quamque inscriptionem semel singulare operatione.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+251"/> <source>WARNING: Invalid MaryJaneCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>(no label)</source> <translation>(nullus titulus)</translation> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>&amp;Quantitas:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Pensa &amp;Ad:</translation> </message> <message> <location line="+24"/> <location filename="../sendcoinsentry.cpp" line="+25"/> <source>Enter a label for this address to add it to your address book</source> <translation>Insero titulum huic inscriptioni ut eam in tuum librum inscriptionum addas.</translation> </message> <message> <location line="+9"/> <source>&amp;Label:</source> <translation>&amp;Titulus:</translation> </message> <message> <location line="+18"/> <source>The address to send the payment to (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Conglutina inscriptionem ex latibulo</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a MaryJaneCoin address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Signationes - Signa / Verifica nuntium</translation> </message> <message> <location line="+13"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation>&amp;Signa Nuntium</translation> </message> <message> <location line="-118"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Potes nuntios signare inscriptionibus tuis ut demonstres te eas possidere. Cautus es non amibiguum signare, quia impetus phiscatorum conentur te fallere ut signes identitatem tuam ad eos. Solas signa sententias cuncte descriptas quibus convenis.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-193"/> <source>Paste address from clipboard</source> <translation>Glutina inscriptionem ex latibulo</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Insere hic nuntium quod vis signare</translation> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation>Copia signationem in latibulum systematis</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this MaryJaneCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all sign message fields</source> <translation>Reconstitue omnes campos signandi nuntii</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Vacuefac &amp;Omnia</translation> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation>&amp;Verifica Nuntium</translation> </message> <message> <location line="-64"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>Insere inscriptionem signantem, nuntium (cura ut copias intermissiones linearum, spatia, tabs, et cetera exacte) et signationem infra ut nuntium verifices. Cautus esto ne magis legas in signationem quam in nuntio signato ipso est, ut vites falli ab impetu homo-in-medio.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified MaryJaneCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all verify message fields</source> <translation>Reconstitue omnes campos verificandi nuntii</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a MaryJaneCoin address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Clicca &quot;Signa Nuntium&quot; ut signatio generetur</translation> </message> <message> <location line="+3"/> <source>Enter MaryJaneCoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Inscriptio inserta non valida est.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Sodes inscriptionem proba et rursus conare.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>Inserta inscriptio clavem non refert.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Cassidilis reserare cancellatum est.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>Clavis privata absens est pro inserta inscriptione.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Nuntium signare abortum est.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Nuntius signatus.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Signatio decodificari non potuit.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Sodes signationem proba et rursus conare.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>Signatio non convenit digesto nuntii</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Nuntium verificare abortum est.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Nuntius verificatus.</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+19"/> <source>Open until %1</source> <translation>Apertum donec %1</translation> </message> <message numerus="yes"> <location line="-2"/> <source>Open for %n block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+8"/> <source>conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation>%1/non conecto</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/non confirmata</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 confirmationes</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Status</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, disseminatum per %n nodo</numerusform><numerusform>, disseminata per %n nodis</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Dies</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Fons</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Generatum</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Ab</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Ad</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>inscriptio propria</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>titulus</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Creditum</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>maturum erit in %n plure frusto</numerusform><numerusform>maturum erit in %n pluribus frustis</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>non acceptum</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Debitum</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Transactionis merces</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Cuncta quantitas</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Nuntius</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Annotatio</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>ID transactionis</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 110 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Informatio de debug</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transactio</translation> </message> <message> <location line="+5"/> <source>Inputs</source> <translation>Lectenda</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Quantitas</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>verum</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>falsum</translation> </message> <message> <location line="-211"/> <source>, has not been successfully broadcast yet</source> <translation>, nondum prospere disseminatum est</translation> </message> <message> <location line="+35"/> <source>unknown</source> <translation>ignotum</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Particularia transactionis</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Haec tabula monstrat descriptionem verbosam transactionis</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+226"/> <source>Date</source> <translation>Dies</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Typus</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Inscriptio</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Quantitas</translation> </message> <message> <location line="+60"/> <source>Open until %1</source> <translation>Apertum donec %1</translation> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation>Confirmatum (%1 confirmationes)</translation> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation><numerusform>Aperi pro %n plure frusto</numerusform><numerusform>Aperi pro %n pluribus frustis</numerusform></translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Hoc frustum non acceptum est ab ulla alia nodis et probabiliter non acceptum erit!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Generatum sed non acceptum</translation> </message> <message> <location line="+42"/> <source>Received with</source> <translation>Acceptum cum</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Acceptum ab</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Missum ad</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Pensitatio ad te ipsum</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Fossa</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(n/a)</translation> </message> <message> <location line="+190"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Status transactionis. Supervola cum mure ut monstretur numerus confirmationum.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Dies et tempus quando transactio accepta est.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Typus transactionis.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Inscriptio destinationis transactionis.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Quantitas remota ex pendendo aut addita ei.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+55"/> <location line="+16"/> <source>All</source> <translation>Omne</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Hodie</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Hac hebdomade</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Hoc mense</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Postremo mense</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Hoc anno</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Intervallum...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Acceptum cum</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Missum ad</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Ad te ipsum</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Fossa</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Alia</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Insere inscriptionem vel titulum ut quaeras</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Quantitas minima</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Copia inscriptionem</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copia titulum</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Copia quantitatem</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Copia transactionis ID</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Muta titulum</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Monstra particularia transactionis</translation> </message> <message> <location line="+144"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Comma Separata Plica (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Confirmatum</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Dies</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Typus</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Titulus</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Inscriptio</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Quantitas</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Intervallum:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>ad</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+206"/> <source>Sending...</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+33"/> <source>MaryJaneCoin version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Usage:</source> <translation>Usus:</translation> </message> <message> <location line="+1"/> <source>Send command to -server or maryjanecoind</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>List commands</source> <translation>Enumera mandata</translation> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation>Accipe auxilium pro mandato</translation> </message> <message> <location line="+2"/> <source>Options:</source> <translation>Optiones:</translation> </message> <message> <location line="+2"/> <source>Specify configuration file (default: maryjanecoin.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify pid file (default: maryjanecoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Specifica indicem datorum</translation> </message> <message> <location line="+2"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Constitue magnitudinem databasis cache in megabytes (praedefinitum: 25)</translation> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Listen for connections on &lt;port&gt; (default: 15714 or testnet: 25714)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Manutene non plures quam &lt;n&gt; conexiones ad paria (praedefinitum: 125)</translation> </message> <message> <location line="+3"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Conecta ad nodum acceptare inscriptiones parium, et disconecte</translation> </message> <message> <location line="+1"/> <source>Specify your own public address</source> <translation>Specifica tuam propriam publicam inscriptionem</translation> </message> <message> <location line="+5"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Stake your coins to support network and gain reward (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Limen pro disconectendo paria improba (praedefinitum: 100)</translation> </message> <message> <location line="+1"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Numerum secundorum prohibere ne paria improba reconectant (praedefinitum: 86400)</translation> </message> <message> <location line="-44"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Error erat dum initians portam RPC %u pro auscultando in IPv4: %s</translation> </message> <message> <location line="+51"/> <source>Detach block and address databases. Increases shutdown time (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+109"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 15715 or testnet: 25715)</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>Accept command line and JSON-RPC commands</source> <translation>Accipe terminalis et JSON-RPC mandata.</translation> </message> <message> <location line="+101"/> <source>Error: Transaction creation failed </source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: Wallet locked, unable to create transaction </source> <translation type="unfinished"/> </message> <message> <location line="-8"/> <source>Importing blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Importing bootstrap blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="-88"/> <source>Run in the background as a daemon and accept commands</source> <translation>Operare infere sicut daemon et mandata accipe</translation> </message> <message> <location line="+1"/> <source>Use the test network</source> <translation>Utere rete experimentale</translation> </message> <message> <location line="-24"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Accipe conexiones externas (praedefinitum: 1 nisi -proxy neque -connect)</translation> </message> <message> <location line="-38"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Error erat dum initians portam RPC %u pro auscultando in IPv6, labens retrorsum ad IPv4: %s</translation> </message> <message> <location line="+117"/> <source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Monitio: -paytxfee constitutum valde magnum! Hoc est merces transactionis solves si mittis transactionem.</translation> </message> <message> <location line="+61"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong MaryJaneCoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Monitio: error legendo wallet.dat! Omnes claves recte lectae, sed data transactionum vel libri inscriptionum fortasse desint vel prava sint.</translation> </message> <message> <location line="-18"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Monitio: wallet.data corrupta, data salvata! Originalis wallet.dat salvata ut wallet.{timestamp}.bak in %s; si pendendum tuum vel transactiones pravae sunt, oportet ab conservato restituere.</translation> </message> <message> <location line="-30"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Conare recipere claves privatas de corrupto wallet.dat</translation> </message> <message> <location line="+4"/> <source>Block creation options:</source> <translation>Optiones creandi frustorum:</translation> </message> <message> <location line="-62"/> <source>Connect only to the specified node(s)</source> <translation>Conecte sole ad nodos specificatos (vel nodum specificatum)</translation> </message> <message> <location line="+4"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Discooperi propriam inscriptionem IP (praedefinitum: 1 quando auscultans et nullum -externalip)</translation> </message> <message> <location line="+94"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Non potuisse auscultare in ulla porta. Utere -listen=0 si hoc vis.</translation> </message> <message> <location line="-90"/> <source>Find peers using DNS lookup (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync checkpoints policy (default: strict)</source> <translation type="unfinished"/> </message> <message> <location line="+83"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-82"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Maxima magnitudo memoriae pro datis accipendis singulis conexionibus, &lt;n&gt;*1000 octetis/bytes (praedefinitum: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Maxima magnitudo memoriae pro datis mittendis singulis conexionibus, &lt;n&gt;*1000 octetis/bytes (praedefinitum: 1000)</translation> </message> <message> <location line="-16"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Tantum conecte ad nodos in rete &lt;net&gt; (IPv4, IPv6 aut Tor)</translation> </message> <message> <location line="+28"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation>Optiones SSL: (vide vici de Bitcoin pro instructionibus SSL configurationis)</translation> </message> <message> <location line="-74"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Mitte informationem vestigii/debug ad terminale potius quam plicam debug.log</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Constitue minimam magnitudinem frusti in octetis/bytes (praedefinitum: 0)</translation> </message> <message> <location line="-29"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Diminue plicam debug.log ad initium clientis (praedefinitum: 1 nisi -debug)</translation> </message> <message> <location line="-42"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Specifica tempumfati conexionis in millisecundis (praedefinitum: 5000)</translation> </message> <message> <location line="+109"/> <source>Unable to sign checkpoint, wrong checkpointkey? </source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Utere UPnP designare portam auscultandi (praedefinitum: 0)</translation> </message> <message> <location line="-1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Utere UPnP designare portam auscultandi (praedefinitum: 1 quando auscultans)</translation> </message> <message> <location line="-25"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Username for JSON-RPC connections</source> <translation>Nomen utentis pro conexionibus JSON-RPC</translation> </message> <message> <location line="+47"/> <source>Verifying database integrity...</source> <translation type="unfinished"/> </message> <message> <location line="+57"/> <source>WARNING: syncronized checkpoint violation detected, but skipped!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Monitio: Haec versio obsoleta est, progressio postulata!</translation> </message> <message> <location line="-48"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat corrupta, salvare abortum est</translation> </message> <message> <location line="-54"/> <source>Password for JSON-RPC connections</source> <translation>Tessera pro conexionibus JSON-RPC</translation> </message> <message> <location line="-84"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=maryjanecoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;MaryJaneCoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Find peers using internet relay chat (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Permitte conexionibus JSON-RPC ex inscriptione specificata</translation> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Mitte mandata nodo operanti in &lt;ip&gt; (praedefinitum: 127.0.0.1)</translation> </message> <message> <location line="+1"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Pelle mandatum quando optissimum frustum mutat (%s in mandato substituitur ab hash frusti)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Facere mandatum quotiescumque cassidilis transactio mutet (%s in mandato sbstituitur ab TxID)</translation> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Upgrade wallet to latest format</source> <translation>Progredere cassidile ad formam recentissimam</translation> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Constitue magnitudinem stagni clavium ad &lt;n&gt; (praedefinitum: 100)</translation> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Iterum perlege catenam frustorum propter absentes cassidilis transactiones</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 2500, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Utere OpenSSL (https) pro conexionibus JSON-RPC</translation> </message> <message> <location line="+1"/> <source>Server certificate file (default: server.cert)</source> <translation>Plica certificationis daemonis moderantis (praedefinitum: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Clavis privata daemonis moderans (praedefinitum: server.pem)</translation> </message> <message> <location line="+1"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source> <translation type="unfinished"/> </message> <message> <location line="-158"/> <source>This help message</source> <translation>Hic nuntius auxilii</translation> </message> <message> <location line="+95"/> <source>Wallet %s resides outside data directory %s.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot obtain a lock on data directory %s. MaryJaneCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-98"/> <source>MaryJaneCoin</source> <translation type="unfinished"/> </message> <message> <location line="+140"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Non posse conglutinare ad %s in hoc computatro (conglutinare redidit errorem %d, %s)</translation> </message> <message> <location line="-130"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Permitte quaerenda DNS pro -addnode, -seednode, et -connect</translation> </message> <message> <location line="+122"/> <source>Loading addresses...</source> <translation>Legens inscriptiones...</translation> </message> <message> <location line="-15"/> <source>Error loading blkindex.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Error legendi wallet.dat: Cassidile corruptum</translation> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of MaryJaneCoin</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart MaryJaneCoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation>Error legendi wallet.dat</translation> </message> <message> <location line="-16"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Inscriptio -proxy non valida: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Ignotum rete specificatum in -onlynet: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Ignota -socks vicarii versio postulata: %i</translation> </message> <message> <location line="+4"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Non posse resolvere -bind inscriptonem: &apos;%s&apos;</translation> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Non posse resolvere -externalip inscriptionem: &apos;%s&apos;</translation> </message> <message> <location line="-24"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Quantitas non valida pro -paytxfee=&lt;quantitas&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Error: could not start node</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sending...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation>Quantitas non valida</translation> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation>Inopia nummorum</translation> </message> <message> <location line="-34"/> <source>Loading block index...</source> <translation>Legens indicem frustorum...</translation> </message> <message> <location line="-103"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Adice nodum cui conectere et conare sustinere conexionem apertam</translation> </message> <message> <location line="+122"/> <source>Unable to bind to %s on this computer. MaryJaneCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-97"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Loading wallet...</source> <translation>Legens cassidile...</translation> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation>Non posse cassidile regredi</translation> </message> <message> <location line="+1"/> <source>Cannot initialize keypool</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation>Non posse scribere praedefinitam inscriptionem</translation> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation>Iterum perlegens...</translation> </message> <message> <location line="+5"/> <source>Done loading</source> <translation>Completo lengendi</translation> </message> <message> <location line="-167"/> <source>To use the %s option</source> <translation>Ut utaris optione %s</translation> </message> <message> <location line="+14"/> <source>Error</source> <translation>Error</translation> </message> <message> <location line="+6"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Necesse est te rpcpassword=&lt;tesseram&gt; constituere in plica configurationum: %s Si plica non existat, crea eam cum permissionibus ut solus eius dominus eam legere sinatur.</translation> </message> </context> </TS>
mit
gintsgints/sequelize
test/integration/hooks.test.js
76264
'use strict'; /* jshint -W030 */ var chai = require('chai') , expect = chai.expect , Support = require(__dirname + '/support') , DataTypes = require(__dirname + '/../../lib/data-types') , Sequelize = Support.Sequelize , sinon = require('sinon') , dialect = Support.getTestDialect(); describe(Support.getTestDialectTeaser('Hooks'), function() { beforeEach(function() { this.User = this.sequelize.define('User', { username: DataTypes.STRING, mood: { type: DataTypes.ENUM, values: ['happy', 'sad', 'neutral'] } }); this.ParanoidUser = this.sequelize.define('ParanoidUser', { username: DataTypes.STRING, mood: { type: DataTypes.ENUM, values: ['happy', 'sad', 'neutral'] } }, { paranoid: true }); return this.sequelize.sync({ force: true }); }); describe('#validate', function() { describe('#create', function() { it('should return the user', function() { this.User.beforeValidate(function(user, options) { user.mood = 'happy'; }); this.User.afterValidate(function(user, options) { user.username = 'Toni'; }); return this.User.create({mood: 'ecstatic'}).then(function(user) { expect(user.mood).to.equal('happy'); expect(user.username).to.equal('Toni'); }); }); }); describe('on error', function() { it('should emit an error from after hook', function() { this.User.afterValidate(function(user, options) { user.mood = 'ecstatic'; throw new Error('Whoops! Changed user.mood!'); }); return expect(this.User.create({mood: 'happy'})).to.be.rejectedWith('Whoops! Changed user.mood!'); }); }); }); describe('#create', function() { describe('on success', function() { it('should run hooks', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy(); this.User.beforeCreate(beforeHook); this.User.afterCreate(afterHook); return this.User.create({username: 'Toni', mood: 'happy'}).then(function() { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).to.have.been.calledOnce; }); }); }); describe('on error', function() { it('should return an error from before', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy(); this.User.beforeCreate(function(user, options) { beforeHook(); throw new Error('Whoops!'); }); this.User.afterCreate(afterHook); return expect(this.User.create({username: 'Toni', mood: 'happy'})).to.be.rejected.then(function(err) { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).not.to.have.been.called; }); }); it('should return an error from after', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy(); this.User.beforeCreate(beforeHook); this.User.afterCreate(function(user, options) { afterHook(); throw new Error('Whoops!'); }); return expect(this.User.create({username: 'Toni', mood: 'happy'})).to.be.rejected.then(function(err) { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).to.have.been.calledOnce; }); }); }); it('should not trigger hooks on parent when using N:M association setters', function() { var A = this.sequelize.define('A', { name: Sequelize.STRING }); var B = this.sequelize.define('B', { name: Sequelize.STRING }); var hookCalled = 0; A.addHook('afterCreate', function(instance, options, next) { hookCalled++; next(); }); B.belongsToMany(A, {through: 'a_b'}); A.belongsToMany(B, {through: 'a_b'}); return this.sequelize.sync({force: true}).bind(this).then(function() { return this.sequelize.Promise.all([ A.create({name: 'a'}), B.create({name: 'b'}) ]).spread(function(a, b) { return a.addB(b).then(function() { expect(hookCalled).to.equal(1); }); }); }); }); }); describe('#updateAttributes', function() { describe('on success', function() { it('should run hooks', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy(); this.User.beforeUpdate(beforeHook); this.User.afterUpdate(afterHook); return this.User.create({username: 'Toni', mood: 'happy'}).then(function(user) { return user.updateAttributes({username: 'Chong'}).then(function(user) { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).to.have.been.calledOnce; expect(user.username).to.equal('Chong'); }); }); }); }); describe('on error', function() { it('should return an error from before', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy(); this.User.beforeUpdate(function(user, options) { beforeHook(); throw new Error('Whoops!'); }); this.User.afterUpdate(afterHook); return this.User.create({username: 'Toni', mood: 'happy'}).then(function(user) { return expect(user.updateAttributes({username: 'Chong'})).to.be.rejected.then(function() { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).not.to.have.been.called; }); }); }); it('should return an error from after', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy(); this.User.beforeUpdate(beforeHook); this.User.afterUpdate(function(user, options) { afterHook(); throw new Error('Whoops!'); }); return this.User.create({username: 'Toni', mood: 'happy'}).then(function(user) { return expect(user.updateAttributes({username: 'Chong'})).to.be.rejected.then(function() { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).to.have.been.calledOnce; }); }); }); }); }); describe('#destroy', function() { describe('on success', function() { it('should run hooks', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy(); this.User.beforeDestroy(beforeHook); this.User.afterDestroy(afterHook); return this.User.create({username: 'Toni', mood: 'happy'}).then(function(user) { return user.destroy().then(function() { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).to.have.been.calledOnce; }); }); }); }); describe('on error', function() { it('should return an error from before', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy(); this.User.beforeDestroy(function(user, options) { beforeHook(); throw new Error('Whoops!'); }); this.User.afterDestroy(afterHook); return this.User.create({username: 'Toni', mood: 'happy'}).then(function(user) { return expect(user.destroy()).to.be.rejected.then(function() { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).not.to.have.been.called; }); }); }); it('should return an error from after', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy(); this.User.beforeDestroy(beforeHook); this.User.afterDestroy(function(user, options) { afterHook(); throw new Error('Whoops!'); }); return this.User.create({username: 'Toni', mood: 'happy'}).then(function(user) { return expect(user.destroy()).to.be.rejected.then(function() { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).to.have.been.calledOnce; }); }); }); }); }); describe('#restore', function() { describe('on success', function() { it('should run hooks', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy(); this.ParanoidUser.beforeRestore(beforeHook); this.ParanoidUser.afterRestore(afterHook); return this.ParanoidUser.create({username: 'Toni', mood: 'happy'}).then(function(user) { return user.destroy().then(function() { return user.restore().then(function(user) { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).to.have.been.calledOnce; }); }); }); }); }); describe('on error', function() { it('should return an error from before', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy(); this.ParanoidUser.beforeRestore(function(user, options) { beforeHook(); throw new Error('Whoops!'); }); this.ParanoidUser.afterRestore(afterHook); return this.ParanoidUser.create({username: 'Toni', mood: 'happy'}).then(function(user) { return user.destroy().then(function() { return expect(user.restore()).to.be.rejected.then(function() { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).not.to.have.been.called; }); }); }); }); it('should return an error from after', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy(); this.ParanoidUser.beforeRestore(beforeHook); this.ParanoidUser.afterRestore(function(user, options) { afterHook(); throw new Error('Whoops!'); }); return this.ParanoidUser.create({username: 'Toni', mood: 'happy'}).then(function(user) { return user.destroy().then(function() { return expect(user.restore()).to.be.rejected.then(function() { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).to.have.been.calledOnce; }); }); }); }); }); }); describe('#bulkCreate', function() { describe('on success', function() { it('should run hooks', function() { var beforeBulk = sinon.spy() , afterBulk = sinon.spy(); this.User.beforeBulkCreate(beforeBulk); this.User.afterBulkCreate(afterBulk); return this.User.bulkCreate([ {username: 'Cheech', mood: 'sad'}, {username: 'Chong', mood: 'sad'} ]).then(function() { expect(beforeBulk).to.have.been.calledOnce; expect(afterBulk).to.have.been.calledOnce; }); }); }); describe('on error', function() { it('should return an error from before', function() { this.User.beforeBulkCreate(function(daos, options) { throw new Error('Whoops!'); }); return expect(this.User.bulkCreate([ {username: 'Cheech', mood: 'sad'}, {username: 'Chong', mood: 'sad'} ])).to.be.rejected; }); it('should return an error from after', function() { this.User.afterBulkCreate(function(daos, options) { throw new Error('Whoops!'); }); return expect(this.User.bulkCreate([ {username: 'Cheech', mood: 'sad'}, {username: 'Chong', mood: 'sad'} ])).to.be.rejected; }); }); describe('with the {individualHooks: true} option', function() { beforeEach(function() { this.User = this.sequelize.define('User', { username: { type: DataTypes.STRING, defaultValue: '' }, beforeHookTest: { type: DataTypes.BOOLEAN, defaultValue: false }, aNumber: { type: DataTypes.INTEGER, defaultValue: 0 } }); return this.User.sync({ force: true }); }); it('should run the afterCreate/beforeCreate functions for each item created successfully', function() { var beforeBulkCreate = false , afterBulkCreate = false; this.User.beforeBulkCreate(function(daos, options, fn) { beforeBulkCreate = true; fn(); }); this.User.afterBulkCreate(function(daos, options, fn) { afterBulkCreate = true; fn(); }); this.User.beforeCreate(function(user, options, fn) { user.beforeHookTest = true; fn(); }); this.User.afterCreate(function(user, options, fn) { user.username = 'User' + user.id; fn(); }); return this.User.bulkCreate([{aNumber: 5}, {aNumber: 7}, {aNumber: 3}], { fields: ['aNumber'], individualHooks: true }).then(function(records) { records.forEach(function(record) { expect(record.username).to.equal('User' + record.id); expect(record.beforeHookTest).to.be.true; }); expect(beforeBulkCreate).to.be.true; expect(afterBulkCreate).to.be.true; }); }); it('should run the afterCreate/beforeCreate functions for each item created with an error', function() { var beforeBulkCreate = false , afterBulkCreate = false; this.User.beforeBulkCreate(function(daos, options, fn) { beforeBulkCreate = true; fn(); }); this.User.afterBulkCreate(function(daos, options, fn) { afterBulkCreate = true; fn(); }); this.User.beforeCreate(function(user, options, fn) { fn(new Error('You shall not pass!')); }); this.User.afterCreate(function(user, options, fn) { user.username = 'User' + user.id; fn(); }); return this.User.bulkCreate([{aNumber: 5}, {aNumber: 7}, {aNumber: 3}], { fields: ['aNumber'], individualHooks: true }).catch(function(err) { expect(err).to.be.instanceOf(Error); expect(beforeBulkCreate).to.be.true; expect(afterBulkCreate).to.be.false; }); }); }); }); describe('#bulkUpdate', function() { describe('on success', function() { it('should run hooks', function() { var self = this , beforeBulk = sinon.spy() , afterBulk = sinon.spy(); this.User.beforeBulkUpdate(beforeBulk); this.User.afterBulkUpdate(afterBulk); return this.User.bulkCreate([ {username: 'Cheech', mood: 'sad'}, {username: 'Chong', mood: 'sad'} ]).then(function() { return self.User.update({mood: 'happy'}, {where: {mood: 'sad'}}).then(function() { expect(beforeBulk).to.have.been.calledOnce; expect(afterBulk).to.have.been.calledOnce; }); }); }); }); describe('on error', function() { it('should return an error from before', function() { var self = this; this.User.beforeBulkUpdate(function(options) { throw new Error('Whoops!'); }); return this.User.bulkCreate([ {username: 'Cheech', mood: 'sad'}, {username: 'Chong', mood: 'sad'} ]).then(function() { return expect(self.User.update({mood: 'happy'}, {where: {mood: 'sad'}})).to.be.rejected; }); }); it('should return an error from after', function() { var self = this; this.User.afterBulkUpdate(function(options) { throw new Error('Whoops!'); }); return this.User.bulkCreate([ {username: 'Cheech', mood: 'sad'}, {username: 'Chong', mood: 'sad'} ]).then(function() { return expect(self.User.update({mood: 'happy'}, {where: {mood: 'sad'}})).to.be.rejected; }); }); }); describe('with the {individualHooks: true} option', function() { beforeEach(function() { this.User = this.sequelize.define('User', { username: { type: DataTypes.STRING, defaultValue: '' }, beforeHookTest: { type: DataTypes.BOOLEAN, defaultValue: false }, aNumber: { type: DataTypes.INTEGER, defaultValue: 0 } }); return this.User.sync({ force: true }); }); it('should run the after/before functions for each item created successfully', function() { var self = this , beforeBulk = sinon.spy() , afterBulk = sinon.spy(); this.User.beforeBulkUpdate(beforeBulk); this.User.afterBulkUpdate(afterBulk); this.User.beforeUpdate(function(user, options) { expect(user.changed()).to.not.be.empty; user.beforeHookTest = true; }); this.User.afterUpdate(function(user, options) { user.username = 'User' + user.id; }); return this.User.bulkCreate([ {aNumber: 1}, {aNumber: 1}, {aNumber: 1} ]).then(function() { return self.User.update({aNumber: 10}, {where: {aNumber: 1}, individualHooks: true}).spread(function(affectedRows, records) { records.forEach(function(record) { expect(record.username).to.equal('User' + record.id); expect(record.beforeHookTest).to.be.true; }); expect(beforeBulk).to.have.been.calledOnce; expect(afterBulk).to.have.been.calledOnce; }); }); }); it('should run the after/before functions for each item created successfully changing some data before updating', function() { var self = this; this.User.beforeUpdate(function(user, options) { expect(user.changed()).to.not.be.empty; if (user.get('id') === 1) { user.set('aNumber', user.get('aNumber') + 3); } }); return this.User.bulkCreate([ {aNumber: 1}, {aNumber: 1}, {aNumber: 1} ]).then(function() { return self.User.update({aNumber: 10}, {where: {aNumber: 1}, individualHooks: true}).spread(function(affectedRows, records) { records.forEach(function(record, i) { expect(record.aNumber).to.equal(10 + (record.id === 1 ? 3 : 0)); }); }); }); }); it('should run the after/before functions for each item created with an error', function() { var self = this , beforeBulk = sinon.spy() , afterBulk = sinon.spy(); this.User.beforeBulkUpdate(beforeBulk); this.User.afterBulkUpdate(afterBulk); this.User.beforeUpdate(function(user, options) { throw new Error('You shall not pass!'); }); this.User.afterUpdate(function(user, options) { user.username = 'User' + user.id; }); return this.User.bulkCreate([{aNumber: 1}, {aNumber: 1}, {aNumber: 1}], { fields: ['aNumber'] }).then(function() { return self.User.update({aNumber: 10}, {where: {aNumber: 1}, individualHooks: true}).catch(function(err) { expect(err).to.be.instanceOf(Error); expect(err.message).to.be.equal('You shall not pass!'); expect(beforeBulk).to.have.been.calledOnce; expect(afterBulk).not.to.have.been.called; }); }); }); }); }); describe('#bulkDestroy', function() { describe('on success', function() { it('should run hooks', function() { var beforeBulk = sinon.spy() , afterBulk = sinon.spy(); this.User.beforeBulkDestroy(beforeBulk); this.User.afterBulkDestroy(afterBulk); return this.User.destroy({where: {username: 'Cheech', mood: 'sad'}}).then(function() { expect(beforeBulk).to.have.been.calledOnce; expect(afterBulk).to.have.been.calledOnce; }); }); }); describe('on error', function() { it('should return an error from before', function() { this.User.beforeBulkDestroy(function(options) { throw new Error('Whoops!'); }); return expect(this.User.destroy({where: {username: 'Cheech', mood: 'sad'}})).to.be.rejected; }); it('should return an error from after', function() { this.User.afterBulkDestroy(function(options) { throw new Error('Whoops!'); }); return expect(this.User.destroy({where: {username: 'Cheech', mood: 'sad'}})).to.be.rejected; }); }); describe('with the {individualHooks: true} option', function() { beforeEach(function() { this.User = this.sequelize.define('User', { username: { type: DataTypes.STRING, defaultValue: '' }, beforeHookTest: { type: DataTypes.BOOLEAN, defaultValue: false }, aNumber: { type: DataTypes.INTEGER, defaultValue: 0 } }); return this.User.sync({ force: true }); }); it('should run the after/before functions for each item created successfully', function() { var self = this , beforeBulk = false , afterBulk = false , beforeHook = false , afterHook = false; this.User.beforeBulkDestroy(function(options, fn) { beforeBulk = true; fn(); }); this.User.afterBulkDestroy(function(options, fn) { afterBulk = true; fn(); }); this.User.beforeDestroy(function(user, options, fn) { beforeHook = true; fn(); }); this.User.afterDestroy(function(user, options, fn) { afterHook = true; fn(); }); return this.User.bulkCreate([ {aNumber: 1}, {aNumber: 1}, {aNumber: 1} ]).then(function() { return self.User.destroy({where: {aNumber: 1}, individualHooks: true}).then(function() { expect(beforeBulk).to.be.true; expect(afterBulk).to.be.true; expect(beforeHook).to.be.true; expect(afterHook).to.be.true; }); }); }); it('should run the after/before functions for each item created with an error', function() { var self = this , beforeBulk = false , afterBulk = false , beforeHook = false , afterHook = false; this.User.beforeBulkDestroy(function(options, fn) { beforeBulk = true; fn(); }); this.User.afterBulkDestroy(function(options, fn) { afterBulk = true; fn(); }); this.User.beforeDestroy(function(user, options, fn) { beforeHook = true; fn(new Error('You shall not pass!')); }); this.User.afterDestroy(function(user, options, fn) { afterHook = true; fn(); }); return this.User.bulkCreate([{aNumber: 1}, {aNumber: 1}, {aNumber: 1}], { fields: ['aNumber'] }).then(function() { return self.User.destroy({where: {aNumber: 1}, individualHooks: true}).catch(function(err) { expect(err).to.be.instanceOf(Error); expect(beforeBulk).to.be.true; expect(beforeHook).to.be.true; expect(afterBulk).to.be.false; expect(afterHook).to.be.false; }); }); }); }); }); describe('#bulkRestore', function() { beforeEach(function() { return this.ParanoidUser.bulkCreate([ {username: 'adam', mood: 'happy'}, {username: 'joe', mood: 'sad'} ]).bind(this).then(function() { return this.ParanoidUser.destroy({truncate: true}); }); }); describe('on success', function() { it('should run hooks', function() { var beforeBulk = sinon.spy() , afterBulk = sinon.spy(); this.ParanoidUser.beforeBulkRestore(beforeBulk); this.ParanoidUser.afterBulkRestore(afterBulk); return this.ParanoidUser.restore({where: {username: 'adam', mood: 'happy'}}).then(function() { expect(beforeBulk).to.have.been.calledOnce; expect(afterBulk).to.have.been.calledOnce; }); }); }); describe('on error', function() { it('should return an error from before', function() { this.ParanoidUser.beforeBulkRestore(function(options) { throw new Error('Whoops!'); }); return expect(this.ParanoidUser.restore({where: {username: 'adam', mood: 'happy'}})).to.be.rejected; }); it('should return an error from after', function() { this.ParanoidUser.afterBulkRestore(function(options) { throw new Error('Whoops!'); }); return expect(this.ParanoidUser.restore({where: {username: 'adam', mood: 'happy'}})).to.be.rejected; }); }); describe('with the {individualHooks: true} option', function() { beforeEach(function() { this.ParanoidUser = this.sequelize.define('ParanoidUser', { aNumber: { type: DataTypes.INTEGER, defaultValue: 0 } }, { paranoid: true }); return this.ParanoidUser.sync({ force: true }); }); it('should run the after/before functions for each item restored successfully', function() { var self = this , beforeBulk = sinon.spy() , afterBulk = sinon.spy() , beforeHook = sinon.spy() , afterHook = sinon.spy(); this.ParanoidUser.beforeBulkRestore(beforeBulk); this.ParanoidUser.afterBulkRestore(afterBulk); this.ParanoidUser.beforeRestore(beforeHook); this.ParanoidUser.afterRestore(afterHook); return this.ParanoidUser.bulkCreate([ {aNumber: 1}, {aNumber: 1}, {aNumber: 1} ]).then(function() { return self.ParanoidUser.destroy({where: {aNumber: 1}}); }).then(function() { return self.ParanoidUser.restore({where: {aNumber: 1}, individualHooks: true}); }).then(function() { expect(beforeBulk).to.have.been.calledOnce; expect(afterBulk).to.have.been.calledOnce; expect(beforeHook).to.have.been.calledThrice; expect(afterHook).to.have.been.calledThrice; }); }); it('should run the after/before functions for each item restored with an error', function() { var self = this , beforeBulk = sinon.spy() , afterBulk = sinon.spy() , beforeHook = sinon.spy() , afterHook = sinon.spy(); this.ParanoidUser.beforeBulkRestore(beforeBulk); this.ParanoidUser.afterBulkRestore(afterBulk); this.ParanoidUser.beforeRestore(function(user, options, fn) { beforeHook(); fn(new Error('You shall not pass!')); }); this.ParanoidUser.afterRestore(afterHook); return this.ParanoidUser.bulkCreate([{aNumber: 1}, {aNumber: 1}, {aNumber: 1}], { fields: ['aNumber'] }).then(function() { return self.ParanoidUser.destroy({where: {aNumber: 1}}); }).then(function() { return self.ParanoidUser.restore({where: {aNumber: 1}, individualHooks: true}); }).catch(function(err) { expect(err).to.be.instanceOf(Error); expect(beforeBulk).to.have.been.calledOnce; expect(beforeHook).to.have.been.calledThrice; expect(afterBulk).not.to.have.been.called; expect(afterHook).not.to.have.been.called; }); }); }); }); describe('#find', function() { beforeEach(function() { return this.User.bulkCreate([ {username: 'adam', mood: 'happy'}, {username: 'joe', mood: 'sad'} ]); }); describe('on success', function() { it('all hooks run', function() { var beforeHook = false , beforeHook2 = false , beforeHook3 = false , afterHook = false; this.User.beforeFind(function() { beforeHook = true; }); this.User.beforeFindAfterExpandIncludeAll(function() { beforeHook2 = true; }); this.User.beforeFindAfterOptions(function() { beforeHook3 = true; }); this.User.afterFind(function() { afterHook = true; }); return this.User.find({where: {username: 'adam'}}).then(function(user) { expect(user.mood).to.equal('happy'); expect(beforeHook).to.be.true; expect(beforeHook2).to.be.true; expect(beforeHook3).to.be.true; expect(afterHook).to.be.true; }); }); it('beforeFind hook can change options', function() { this.User.beforeFind(function(options) { options.where.username = 'joe'; }); return this.User.find({where: {username: 'adam'}}).then(function(user) { expect(user.mood).to.equal('sad'); }); }); it('beforeFindAfterExpandIncludeAll hook can change options', function() { this.User.beforeFindAfterExpandIncludeAll(function(options) { options.where.username = 'joe'; }); return this.User.find({where: {username: 'adam'}}).then(function(user) { expect(user.mood).to.equal('sad'); }); }); it('beforeFindAfterOptions hook can change options', function() { this.User.beforeFindAfterOptions(function(options) { options.where.username = 'joe'; }); return this.User.find({where: {username: 'adam'}}).then(function(user) { expect(user.mood).to.equal('sad'); }); }); it('afterFind hook can change results', function() { this.User.afterFind(function(user) { user.mood = 'sad'; }); return this.User.find({where: {username: 'adam'}}).then(function(user) { expect(user.mood).to.equal('sad'); }); }); }); describe('on error', function() { it('in beforeFind hook returns error', function() { this.User.beforeFind(function() { throw new Error('Oops!'); }); return this.User.find({where: {username: 'adam'}}).catch (function(err) { expect(err.message).to.equal('Oops!'); }); }); it('in beforeFindAfterExpandIncludeAll hook returns error', function() { this.User.beforeFindAfterExpandIncludeAll(function() { throw new Error('Oops!'); }); return this.User.find({where: {username: 'adam'}}).catch (function(err) { expect(err.message).to.equal('Oops!'); }); }); it('in beforeFindAfterOptions hook returns error', function() { this.User.beforeFindAfterOptions(function() { throw new Error('Oops!'); }); return this.User.find({where: {username: 'adam'}}).catch (function(err) { expect(err.message).to.equal('Oops!'); }); }); it('in afterFind hook returns error', function() { this.User.afterFind(function() { throw new Error('Oops!'); }); return this.User.find({where: {username: 'adam'}}).catch (function(err) { expect(err.message).to.equal('Oops!'); }); }); }); }); describe('#define', function() { before(function() { this.sequelize.addHook('beforeDefine', function(attributes, options) { options.modelName = 'bar'; options.name.plural = 'barrs'; attributes.type = DataTypes.STRING; }); this.sequelize.addHook('afterDefine', function(factory) { factory.options.name.singular = 'barr'; }); this.model = this.sequelize.define('foo', {name: DataTypes.STRING}); }); it('beforeDefine hook can change model name', function() { expect(this.model.name).to.equal('bar'); }); it('beforeDefine hook can alter options', function() { expect(this.model.options.name.plural).to.equal('barrs'); }); it('beforeDefine hook can alter attributes', function() { expect(this.model.rawAttributes.type).to.be.ok; }); it('afterDefine hook can alter options', function() { expect(this.model.options.name.singular).to.equal('barr'); }); after(function() { this.sequelize.options.hooks = {}; this.sequelize.modelManager.removeModel(this.model); }); }); describe('#init', function() { before(function() { Sequelize.addHook('beforeInit', function(config, options) { config.database = 'db2'; options.host = 'server9'; }); Sequelize.addHook('afterInit', function(sequelize) { sequelize.options.protocol = 'udp'; }); this.seq = new Sequelize('db', 'user', 'pass', {}); }); it('beforeInit hook can alter config', function() { expect(this.seq.config.database).to.equal('db2'); }); it('beforeInit hook can alter options', function() { expect(this.seq.options.host).to.equal('server9'); }); it('afterInit hook can alter options', function() { expect(this.seq.options.protocol).to.equal('udp'); }); after(function() { Sequelize.options.hooks = {}; }); }); describe('associations', function() { describe('1:1', function() { describe('cascade onUpdate', function() { beforeEach(function() { var self = this; this.Projects = this.sequelize.define('Project', { title: DataTypes.STRING }); this.Tasks = this.sequelize.define('Task', { title: DataTypes.STRING }); this.Projects.hasOne(this.Tasks, {onUpdate: 'cascade', hooks: true}); this.Tasks.belongsTo(this.Projects); return this.Projects.sync({ force: true }).then(function() { return self.Tasks.sync({ force: true }); }); }); it('on success', function() { var self = this , beforeHook = false , afterHook = false; this.Tasks.beforeUpdate(function(task, options, fn) { beforeHook = true; fn(); }); this.Tasks.afterUpdate(function(task, options, fn) { afterHook = true; fn(); }); return this.Projects.create({title: 'New Project'}).then(function(project) { return self.Tasks.create({title: 'New Task'}).then(function(task) { return project.setTask(task).then(function() { return project.updateAttributes({id: 2}).then(function() { expect(beforeHook).to.be.true; expect(afterHook).to.be.true; }); }); }); }); }); it('on error', function() { var self = this; this.Tasks.afterUpdate(function(task, options, fn) { fn(new Error('Whoops!')); }); return this.Projects.create({title: 'New Project'}).then(function(project) { return self.Tasks.create({title: 'New Task'}).then(function(task) { return project.setTask(task).catch(function(err) { expect(err).to.be.instanceOf(Error); }); }); }); }); }); describe('cascade onDelete', function() { beforeEach(function() { this.Projects = this.sequelize.define('Project', { title: DataTypes.STRING }); this.Tasks = this.sequelize.define('Task', { title: DataTypes.STRING }); this.Projects.hasOne(this.Tasks, {onDelete: 'CASCADE', hooks: true}); this.Tasks.belongsTo(this.Projects); return this.sequelize.sync({ force: true }); }); describe('#remove', function() { it('with no errors', function() { var self = this , beforeProject = sinon.spy() , afterProject = sinon.spy() , beforeTask = sinon.spy() , afterTask = sinon.spy(); this.Projects.beforeCreate(beforeProject); this.Projects.afterCreate(afterProject); this.Tasks.beforeDestroy(beforeTask); this.Tasks.afterDestroy(afterTask); return this.Projects.create({title: 'New Project'}).then(function(project) { return self.Tasks.create({title: 'New Task'}).then(function(task) { return project.setTask(task).then(function() { return project.destroy().then(function() { expect(beforeProject).to.have.been.calledOnce; expect(afterProject).to.have.been.calledOnce; expect(beforeTask).to.have.been.calledOnce; expect(afterTask).to.have.been.calledOnce; }); }); }); }); }); it('with errors', function() { var self = this , beforeProject = false , afterProject = false , beforeTask = false , afterTask = false , CustomErrorText = 'Whoops!'; this.Projects.beforeCreate(function(project, options, fn) { beforeProject = true; fn(); }); this.Projects.afterCreate(function(project, options, fn) { afterProject = true; fn(); }); this.Tasks.beforeDestroy(function(task, options, fn) { beforeTask = true; fn(new Error(CustomErrorText)); }); this.Tasks.afterDestroy(function(task, options, fn) { afterTask = true; fn(); }); return this.Projects.create({title: 'New Project'}).then(function(project) { return self.Tasks.create({title: 'New Task'}).then(function(task) { return project.setTask(task).then(function() { return expect(project.destroy()).to.eventually.be.rejectedWith(CustomErrorText).then(function () { expect(beforeProject).to.be.true; expect(afterProject).to.be.true; expect(beforeTask).to.be.true; expect(afterTask).to.be.false; }); }); }); }); }); }); }); describe('no cascade update', function() { beforeEach(function() { var self = this; this.Projects = this.sequelize.define('Project', { title: DataTypes.STRING }); this.Tasks = this.sequelize.define('Task', { title: DataTypes.STRING }); this.Projects.hasOne(this.Tasks); this.Tasks.belongsTo(this.Projects); return this.Projects.sync({ force: true }).then(function() { return self.Tasks.sync({ force: true }); }); }); it('on success', function() { var self = this , beforeHook = sinon.spy() , afterHook = sinon.spy(); this.Tasks.beforeUpdate(beforeHook); this.Tasks.afterUpdate(afterHook); return this.Projects.create({title: 'New Project'}).then(function(project) { return self.Tasks.create({title: 'New Task'}).then(function(task) { return project.setTask(task).then(function() { return project.updateAttributes({id: 2}).then(function() { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).to.have.been.calledOnce; }); }); }); }); }); it('on error', function() { var self = this; this.Tasks.afterUpdate(function(task, options) { throw new Error('Whoops!'); }); return this.Projects.create({title: 'New Project'}).then(function(project) { return self.Tasks.create({title: 'New Task'}).then(function(task) { return expect(project.setTask(task)).to.be.rejected; }); }); }); }); describe('no cascade delete', function() { beforeEach(function() { var self = this; this.Projects = this.sequelize.define('Project', { title: DataTypes.STRING }); this.Tasks = this.sequelize.define('Task', { title: DataTypes.STRING }); this.Projects.hasMany(this.Tasks); this.Tasks.belongsTo(this.Projects); return this.Projects.sync({ force: true }).then(function() { return self.Tasks.sync({ force: true }); }); }); describe('#remove', function() { it('with no errors', function() { var self = this , beforeProject = sinon.spy() , afterProject = sinon.spy() , beforeTask = sinon.spy() , afterTask = sinon.spy(); this.Projects.beforeCreate(beforeProject); this.Projects.afterCreate(afterProject); this.Tasks.beforeUpdate(beforeTask); this.Tasks.afterUpdate(afterTask); return this.Projects.create({title: 'New Project'}).then(function(project) { return self.Tasks.create({title: 'New Task'}).then(function(task) { return project.addTask(task).then(function() { return project.removeTask(task).then(function() { expect(beforeProject).to.have.been.called; expect(afterProject).to.have.been.called; expect(beforeTask).not.to.have.been.called; expect(afterTask).not.to.have.been.called; }); }); }); }); }); it('with errors', function() { var self = this , beforeProject = sinon.spy() , afterProject = sinon.spy() , beforeTask = sinon.spy() , afterTask = sinon.spy(); this.Projects.beforeCreate(beforeProject); this.Projects.afterCreate(afterProject); this.Tasks.beforeUpdate(function(task, options) { beforeTask(); throw new Error('Whoops!'); }); this.Tasks.afterUpdate(afterTask); return this.Projects.create({title: 'New Project'}).then(function(project) { return self.Tasks.create({title: 'New Task'}).then(function(task) { return project.addTask(task).catch(function(err) { expect(err).to.be.instanceOf(Error); expect(beforeProject).to.have.been.calledOnce; expect(afterProject).to.have.been.calledOnce; expect(beforeTask).to.have.been.calledOnce; expect(afterTask).not.to.have.been.called; }); }); }); }); }); }); }); describe('1:M', function() { describe('cascade', function() { beforeEach(function() { var self = this; this.Projects = this.sequelize.define('Project', { title: DataTypes.STRING }); this.Tasks = this.sequelize.define('Task', { title: DataTypes.STRING }); this.Projects.hasMany(this.Tasks, {onDelete: 'cascade', hooks: true}); this.Tasks.belongsTo(this.Projects, {hooks: true}); return this.Projects.sync({ force: true }).then(function() { return self.Tasks.sync({ force: true }); }); }); describe('#remove', function() { it('with no errors', function() { var self = this , beforeProject = sinon.spy() , afterProject = sinon.spy() , beforeTask = sinon.spy() , afterTask = sinon.spy(); this.Projects.beforeCreate(beforeProject); this.Projects.afterCreate(afterProject); this.Tasks.beforeDestroy(beforeTask); this.Tasks.afterDestroy(afterTask); return this.Projects.create({title: 'New Project'}).then(function(project) { return self.Tasks.create({title: 'New Task'}).then(function(task) { return project.addTask(task).then(function() { return project.destroy().then(function() { expect(beforeProject).to.have.been.calledOnce; expect(afterProject).to.have.been.calledOnce; expect(beforeTask).to.have.been.calledOnce; expect(afterTask).to.have.been.calledOnce; }); }); }); }); }); it('with errors', function() { var self = this , beforeProject = false , afterProject = false , beforeTask = false , afterTask = false; this.Projects.beforeCreate(function(project, options, fn) { beforeProject = true; fn(); }); this.Projects.afterCreate(function(project, options, fn) { afterProject = true; fn(); }); this.Tasks.beforeDestroy(function(task, options, fn) { beforeTask = true; fn(new Error('Whoops!')); }); this.Tasks.afterDestroy(function(task, options, fn) { afterTask = true; fn(); }); return this.Projects.create({title: 'New Project'}).then(function(project) { return self.Tasks.create({title: 'New Task'}).then(function(task) { return project.addTask(task).then(function() { return project.destroy().catch(function(err) { expect(err).to.be.instanceOf(Error); expect(beforeProject).to.be.true; expect(afterProject).to.be.true; expect(beforeTask).to.be.true; expect(afterTask).to.be.false; }); }); }); }); }); }); }); describe('no cascade', function() { beforeEach(function() { this.Projects = this.sequelize.define('Project', { title: DataTypes.STRING }); this.Tasks = this.sequelize.define('Task', { title: DataTypes.STRING }); this.Projects.hasMany(this.Tasks); this.Tasks.belongsTo(this.Projects); return this.sequelize.sync({ force: true }); }); describe('#remove', function() { it('with no errors', function() { var self = this , beforeProject = sinon.spy() , afterProject = sinon.spy() , beforeTask = sinon.spy() , afterTask = sinon.spy(); this.Projects.beforeCreate(beforeProject); this.Projects.afterCreate(afterProject); this.Tasks.beforeUpdate(beforeTask); this.Tasks.afterUpdate(afterTask); return this.Projects.create({title: 'New Project'}).then(function(project) { return self.Tasks.create({title: 'New Task'}).then(function(task) { return project.addTask(task).then(function() { return project.removeTask(task).then(function() { expect(beforeProject).to.have.been.called; expect(afterProject).to.have.been.called; expect(beforeTask).not.to.have.been.called; expect(afterTask).not.to.have.been.called; }); }); }); }); }); it('with errors', function() { var self = this , beforeProject = false , afterProject = false , beforeTask = false , afterTask = false; this.Projects.beforeCreate(function(project, options, fn) { beforeProject = true; fn(); }); this.Projects.afterCreate(function(project, options, fn) { afterProject = true; fn(); }); this.Tasks.beforeUpdate(function(task, options, fn) { beforeTask = true; fn(new Error('Whoops!')); }); this.Tasks.afterUpdate(function(task, options, fn) { afterTask = true; fn(); }); return this.Projects.create({title: 'New Project'}).then(function(project) { return self.Tasks.create({title: 'New Task'}).then(function(task) { return project.addTask(task).catch(function(err) { expect(err).to.be.instanceOf(Error); expect(beforeProject).to.be.true; expect(afterProject).to.be.true; expect(beforeTask).to.be.true; expect(afterTask).to.be.false; }); }); }); }); }); }); }); describe('M:M', function() { describe('cascade', function() { beforeEach(function() { this.Projects = this.sequelize.define('Project', { title: DataTypes.STRING }); this.Tasks = this.sequelize.define('Task', { title: DataTypes.STRING }); this.Projects.belongsToMany(this.Tasks, {cascade: 'onDelete', through: 'projects_and_tasks', hooks: true}); this.Tasks.belongsToMany(this.Projects, {cascade: 'onDelete', through: 'projects_and_tasks', hooks: true}); return this.sequelize.sync({ force: true }); }); describe('#remove', function() { it('with no errors', function() { var self = this , beforeProject = sinon.spy() , afterProject = sinon.spy() , beforeTask = sinon.spy() , afterTask = sinon.spy(); this.Projects.beforeCreate(beforeProject); this.Projects.afterCreate(afterProject); this.Tasks.beforeDestroy(beforeTask); this.Tasks.afterDestroy(afterTask); return this.Projects.create({title: 'New Project'}).then(function(project) { return self.Tasks.create({title: 'New Task'}).then(function(task) { return project.addTask(task).then(function() { return project.destroy().then(function() { expect(beforeProject).to.have.been.calledOnce; expect(afterProject).to.have.been.calledOnce; // Since Sequelize does not cascade M:M, these should be false expect(beforeTask).not.to.have.been.called; expect(afterTask).not.to.have.been.called; }); }); }); }); }); it('with errors', function() { var self = this , beforeProject = false , afterProject = false , beforeTask = false , afterTask = false; this.Projects.beforeCreate(function(project, options, fn) { beforeProject = true; fn(); }); this.Projects.afterCreate(function(project, options, fn) { afterProject = true; fn(); }); this.Tasks.beforeDestroy(function(task, options, fn) { beforeTask = true; fn(new Error('Whoops!')); }); this.Tasks.afterDestroy(function(task, options, fn) { afterTask = true; fn(); }); return this.Projects.create({title: 'New Project'}).then(function(project) { return self.Tasks.create({title: 'New Task'}).then(function(task) { return project.addTask(task).then(function() { return project.destroy().then(function() { expect(beforeProject).to.be.true; expect(afterProject).to.be.true; expect(beforeTask).to.be.false; expect(afterTask).to.be.false; }); }); }); }); }); }); }); describe('no cascade', function() { beforeEach(function() { this.Projects = this.sequelize.define('Project', { title: DataTypes.STRING }); this.Tasks = this.sequelize.define('Task', { title: DataTypes.STRING }); this.Projects.belongsToMany(this.Tasks, {hooks: true, through: 'project_tasks'}); this.Tasks.belongsToMany(this.Projects, {hooks: true, through: 'project_tasks'}); return this.sequelize.sync({ force: true }); }); describe('#remove', function() { it('with no errors', function() { var self = this , beforeProject = sinon.spy() , afterProject = sinon.spy() , beforeTask = sinon.spy() , afterTask = sinon.spy(); this.Projects.beforeCreate(beforeProject); this.Projects.afterCreate(afterProject); this.Tasks.beforeUpdate(beforeTask); this.Tasks.afterUpdate(afterTask); return this.Projects.create({title: 'New Project'}).then(function(project) { return self.Tasks.create({title: 'New Task'}).then(function(task) { return project.addTask(task).then(function() { return project.removeTask(task).then(function() { expect(beforeProject).to.have.been.calledOnce; expect(afterProject).to.have.been.calledOnce; expect(beforeTask).not.to.have.been.called; expect(afterTask).not.to.have.been.called; }); }); }); }); }); it('with errors', function() { var self = this , beforeProject = false , afterProject = false , beforeTask = false , afterTask = false; this.Projects.beforeCreate(function(project, options, fn) { beforeProject = true; fn(); }); this.Projects.afterCreate(function(project, options, fn) { afterProject = true; fn(); }); this.Tasks.beforeUpdate(function(task, options, fn) { beforeTask = true; fn(new Error('Whoops!')); }); this.Tasks.afterUpdate(function(task, options, fn) { afterTask = true; fn(); }); return this.Projects.create({title: 'New Project'}).then(function(project) { return self.Tasks.create({title: 'New Task'}).then(function(task) { return project.addTask(task).then(function() { expect(beforeProject).to.be.true; expect(afterProject).to.be.true; expect(beforeTask).to.be.false; expect(afterTask).to.be.false; }); }); }); }); }); }); }); // NOTE: Reenable when FK constraints create table query is fixed when using hooks if (dialect !== 'mssql') { describe('multiple 1:M', function () { describe('cascade', function() { beforeEach(function() { this.Projects = this.sequelize.define('Project', { title: DataTypes.STRING }); this.Tasks = this.sequelize.define('Task', { title: DataTypes.STRING }); this.MiniTasks = this.sequelize.define('MiniTask', { mini_title: DataTypes.STRING }); this.Projects.hasMany(this.Tasks, {onDelete: 'cascade', hooks: true}); this.Projects.hasMany(this.MiniTasks, {onDelete: 'cascade', hooks: true}); this.Tasks.belongsTo(this.Projects, {hooks: true}); this.Tasks.hasMany(this.MiniTasks, {onDelete: 'cascade', hooks: true}); this.MiniTasks.belongsTo(this.Projects, {hooks: true}); this.MiniTasks.belongsTo(this.Tasks, {hooks: true}); return this.sequelize.sync({force: true}); }); describe('#remove', function() { it('with no errors', function() { var beforeProject = false , afterProject = false , beforeTask = false , afterTask = false , beforeMiniTask = false , afterMiniTask = false; this.Projects.beforeCreate(function(project, options, fn) { beforeProject = true; fn(); }); this.Projects.afterCreate(function(project, options, fn) { afterProject = true; fn(); }); this.Tasks.beforeDestroy(function(task, options, fn) { beforeTask = true; fn(); }); this.Tasks.afterDestroy(function(task, options, fn) { afterTask = true; fn(); }); this.MiniTasks.beforeDestroy(function(minitask, options, fn) { beforeMiniTask = true; fn(); }); this.MiniTasks.afterDestroy(function(minitask, options, fn) { afterMiniTask = true; fn(); }); return this.sequelize.Promise.all([ this.Projects.create({title: 'New Project'}), this.MiniTasks.create({mini_title: 'New MiniTask'}) ]).bind(this).spread(function(project, minitask) { return project.addMiniTask(minitask); }).then(function(project) { return project.destroy(); }).then(function() { expect(beforeProject).to.be.true; expect(afterProject).to.be.true; expect(beforeTask).to.be.false; expect(afterTask).to.be.false; expect(beforeMiniTask).to.be.true; expect(afterMiniTask).to.be.true; }); }); it('with errors', function() { var beforeProject = false , afterProject = false , beforeTask = false , afterTask = false , beforeMiniTask = false , afterMiniTask = false; this.Projects.beforeCreate(function(project, options, fn) { beforeProject = true; fn(); }); this.Projects.afterCreate(function(project, options, fn) { afterProject = true; fn(); }); this.Tasks.beforeDestroy(function(task, options, fn) { beforeTask = true; fn(); }); this.Tasks.afterDestroy(function(task, options, fn) { afterTask = true; fn(); }); this.MiniTasks.beforeDestroy(function(minitask, options, fn) { beforeMiniTask = true; fn(new Error('Whoops!')); }); this.MiniTasks.afterDestroy(function(minitask, options, fn) { afterMiniTask = true; fn(); }); return this.sequelize.Promise.all([ this.Projects.create({title: 'New Project'}), this.MiniTasks.create({mini_title: 'New MiniTask'}) ]).bind(this).spread(function(project, minitask) { return project.addMiniTask(minitask); }).then(function(project) { return project.destroy(); }).catch(function() { expect(beforeProject).to.be.true; expect(afterProject).to.be.true; expect(beforeTask).to.be.false; expect(afterTask).to.be.false; expect(beforeMiniTask).to.be.true; expect(afterMiniTask).to.be.false; }); }); }); }); }); describe('multiple 1:M sequential hooks', function () { describe('cascade', function() { beforeEach(function() { this.Projects = this.sequelize.define('Project', { title: DataTypes.STRING }); this.Tasks = this.sequelize.define('Task', { title: DataTypes.STRING }); this.MiniTasks = this.sequelize.define('MiniTask', { mini_title: DataTypes.STRING }); this.Projects.hasMany(this.Tasks, {onDelete: 'cascade', hooks: true}); this.Projects.hasMany(this.MiniTasks, {onDelete: 'cascade', hooks: true}); this.Tasks.belongsTo(this.Projects, {hooks: true}); this.Tasks.hasMany(this.MiniTasks, {onDelete: 'cascade', hooks: true}); this.MiniTasks.belongsTo(this.Projects, {hooks: true}); this.MiniTasks.belongsTo(this.Tasks, {hooks: true}); return this.sequelize.sync({force: true}); }); describe('#remove', function() { it('with no errors', function() { var beforeProject = false , afterProject = false , beforeTask = false , afterTask = false , beforeMiniTask = false , afterMiniTask = false; this.Projects.beforeCreate(function(project, options, fn) { beforeProject = true; fn(); }); this.Projects.afterCreate(function(project, options, fn) { afterProject = true; fn(); }); this.Tasks.beforeDestroy(function(task, options, fn) { beforeTask = true; fn(); }); this.Tasks.afterDestroy(function(task, options, fn) { afterTask = true; fn(); }); this.MiniTasks.beforeDestroy(function(minitask, options, fn) { beforeMiniTask = true; fn(); }); this.MiniTasks.afterDestroy(function(minitask, options, fn) { afterMiniTask = true; fn(); }); return this.sequelize.Promise.all([ this.Projects.create({title: 'New Project'}), this.Tasks.create({title: 'New Task'}), this.MiniTasks.create({mini_title: 'New MiniTask'}) ]).bind(this).spread(function(project, task, minitask) { return this.sequelize.Promise.all([ task.addMiniTask(minitask), project.addTask(task) ]).return(project); }).then(function(project) { return project.destroy(); }).then(function() { expect(beforeProject).to.be.true; expect(afterProject).to.be.true; expect(beforeTask).to.be.true; expect(afterTask).to.be.true; expect(beforeMiniTask).to.be.true; expect(afterMiniTask).to.be.true; }); }); it('with errors', function() { var beforeProject = false , afterProject = false , beforeTask = false , afterTask = false , beforeMiniTask = false , afterMiniTask = false , CustomErrorText = 'Whoops!'; this.Projects.beforeCreate(function() { beforeProject = true; }); this.Projects.afterCreate(function() { afterProject = true; }); this.Tasks.beforeDestroy(function() { beforeTask = true; throw new Error(CustomErrorText); }); this.Tasks.afterDestroy(function() { afterTask = true; }); this.MiniTasks.beforeDestroy(function() { beforeMiniTask = true; }); this.MiniTasks.afterDestroy(function() { afterMiniTask = true; }); return this.sequelize.Promise.all([ this.Projects.create({title: 'New Project'}), this.Tasks.create({title: 'New Task'}), this.MiniTasks.create({mini_title: 'New MiniTask'}) ]).bind(this).spread(function(project, task, minitask) { return this.sequelize.Promise.all([ task.addMiniTask(minitask), project.addTask(task) ]).return(project); }).then(function(project) { return expect(project.destroy()).to.eventually.be.rejectedWith(CustomErrorText).then(function () { expect(beforeProject).to.be.true; expect(afterProject).to.be.true; expect(beforeTask).to.be.true; expect(afterTask).to.be.false; expect(beforeMiniTask).to.be.false; expect(afterMiniTask).to.be.false; }); }); }); }); }); }); } }); describe('passing DAO instances', function() { describe('beforeValidate / afterValidate', function() { it('should pass a DAO instance to the hook', function() { var beforeHooked = false; var afterHooked = false; var User = this.sequelize.define('User', { username: DataTypes.STRING }, { hooks: { beforeValidate: function(user, options, fn) { expect(user).to.be.instanceof(User.Instance); beforeHooked = true; fn(); }, afterValidate: function(user, options, fn) { expect(user).to.be.instanceof(User.Instance); afterHooked = true; fn(); } } }); return User.sync({ force: true }).then(function() { return User.create({ username: 'bob' }).then(function() { expect(beforeHooked).to.be.true; expect(afterHooked).to.be.true; }); }); }); }); describe('beforeCreate / afterCreate', function() { it('should pass a DAO instance to the hook', function() { var beforeHooked = false; var afterHooked = false; var User = this.sequelize.define('User', { username: DataTypes.STRING }, { hooks: { beforeCreate: function(user, options, fn) { expect(user).to.be.instanceof(User.Instance); beforeHooked = true; fn(); }, afterCreate: function(user, options, fn) { expect(user).to.be.instanceof(User.Instance); afterHooked = true; fn(); } } }); return User.sync({ force: true }).then(function() { return User.create({ username: 'bob' }).then(function() { expect(beforeHooked).to.be.true; expect(afterHooked).to.be.true; }); }); }); }); describe('beforeDestroy / afterDestroy', function() { it('should pass a DAO instance to the hook', function() { var beforeHooked = false; var afterHooked = false; var User = this.sequelize.define('User', { username: DataTypes.STRING }, { hooks: { beforeDestroy: function(user, options, fn) { expect(user).to.be.instanceof(User.Instance); beforeHooked = true; fn(); }, afterDestroy: function(user, options, fn) { expect(user).to.be.instanceof(User.Instance); afterHooked = true; fn(); } } }); return User.sync({ force: true }).then(function() { return User.create({ username: 'bob' }).then(function(user) { return user.destroy().then(function() { expect(beforeHooked).to.be.true; expect(afterHooked).to.be.true; }); }); }); }); }); describe('beforeDelete / afterDelete', function() { it('should pass a DAO instance to the hook', function() { var beforeHooked = false; var afterHooked = false; var User = this.sequelize.define('User', { username: DataTypes.STRING }, { hooks: { beforeDelete: function(user, options, fn) { expect(user).to.be.instanceof(User.Instance); beforeHooked = true; fn(); }, afterDelete: function(user, options, fn) { expect(user).to.be.instanceof(User.Instance); afterHooked = true; fn(); } } }); return User.sync({ force: true }).then(function() { return User.create({ username: 'bob' }).then(function(user) { return user.destroy().then(function() { expect(beforeHooked).to.be.true; expect(afterHooked).to.be.true; }); }); }); }); }); describe('beforeUpdate / afterUpdate', function() { it('should pass a DAO instance to the hook', function() { var beforeHooked = false; var afterHooked = false; var User = this.sequelize.define('User', { username: DataTypes.STRING }, { hooks: { beforeUpdate: function(user, options, fn) { expect(user).to.be.instanceof(User.Instance); beforeHooked = true; fn(); }, afterUpdate: function(user, options, fn) { expect(user).to.be.instanceof(User.Instance); afterHooked = true; fn(); } } }); return User.sync({ force: true }).then(function() { return User.create({ username: 'bob' }).then(function(user) { user.username = 'bawb'; return user.save({ fields: ['username'] }).then(function() { expect(beforeHooked).to.be.true; expect(afterHooked).to.be.true; }); }); }); }); }); }); describe('Model#sync', function() { describe('on success', function() { it('should run hooks', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy(); this.User.beforeSync(beforeHook); this.User.afterSync(afterHook); return this.User.sync({ force: true }).then(function() { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).to.have.been.calledOnce; }); }); it('should not run hooks when "hooks = false" option passed', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy(); this.User.beforeSync(beforeHook); this.User.afterSync(afterHook); return this.User.sync({ hooks: false, force: true }).then(function() { expect(beforeHook).to.not.have.been.called; expect(afterHook).to.not.have.been.called; }); }); }); describe('on error', function() { it('should return an error from before', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy(); this.User.beforeSync(function(options) { beforeHook(); throw new Error('Whoops!'); }); this.User.afterSync(afterHook); return expect(this.User.sync({force: true})).to.be.rejected.then(function(err) { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).not.to.have.been.called; }); }); it('should return an error from after', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy(); this.User.beforeSync(beforeHook); this.User.afterSync(function(options) { afterHook(); throw new Error('Whoops!'); }); return expect(this.User.sync({force: true})).to.be.rejected.then(function(err) { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).to.have.been.calledOnce; }); }); }); }); describe('sequelize#sync', function() { describe('on success', function() { it('should run hooks', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy() , modelBeforeHook = sinon.spy() , modelAfterHook = sinon.spy(); this.sequelize.beforeBulkSync(beforeHook); this.User.beforeSync(modelBeforeHook); this.User.afterSync(modelAfterHook); this.sequelize.afterBulkSync(afterHook); return this.sequelize.sync({ force: true }).then(function() { expect(beforeHook).to.have.been.calledOnce; expect(modelBeforeHook).to.have.been.calledOnce; expect(modelAfterHook).to.have.been.calledOnce; expect(afterHook).to.have.been.calledOnce; }); }); it('should not run hooks if "hooks = false" option passed', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy() , modelBeforeHook = sinon.spy() , modelAfterHook = sinon.spy(); this.sequelize.beforeBulkSync(beforeHook); this.User.beforeSync(modelBeforeHook); this.User.afterSync(modelAfterHook); this.sequelize.afterBulkSync(afterHook); return this.sequelize.sync({ hooks: false, force: true }).then(function() { expect(beforeHook).to.not.have.been.called; expect(modelBeforeHook).to.not.have.been.called; expect(modelAfterHook).to.not.have.been.called; expect(afterHook).to.not.have.been.called; }); }); afterEach(function() { this.sequelize.options.hooks = {}; }); }); describe('on error', function() { it('should return an error from before', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy(); this.sequelize.beforeBulkSync(function(options) { beforeHook(); throw new Error('Whoops!'); }); this.sequelize.afterBulkSync(afterHook); return expect(this.sequelize.sync( { force: true } )).to.be.rejected.then(function(err) { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).not.to.have.been.called; }); }); it('should return an error from after', function() { var beforeHook = sinon.spy() , afterHook = sinon.spy(); this.sequelize.beforeBulkSync(beforeHook); this.sequelize.afterBulkSync(function(options) { afterHook(); throw new Error('Whoops!'); }); return expect(this.sequelize.sync({ force: true })).to.be.rejected.then(function(err) { expect(beforeHook).to.have.been.calledOnce; expect(afterHook).to.have.been.calledOnce; }); }); afterEach(function() { this.sequelize.options.hooks = {}; }); }); }); });
mit
sgpatil/NeoEloquent
src/Vinelab/NeoEloquent/Console/Migrations/MigrateMakeCommand.php
3183
<?php namespace Vinelab\NeoEloquent\Console\Migrations; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use Vinelab\NeoEloquent\Migrations\MigrationCreator; class MigrateMakeCommand extends BaseCommand { /** * {@inheritDoc} */ protected $name = 'neo4j:migrate:make'; /** * {@inheritDoc} */ protected $description = 'Create a new migration file'; /** * @var \Vinelab\NeoEloquent\Migrations\MigrationCreator */ protected $creator; /** * The path to the packages directory (vendor). * * @var string */ protected $packagePath; /** * @param \Vinelab\NeoEloquent\Migrations\MigrationCreator $creator * @param string $packagePath * @return void */ public function __construct(MigrationCreator $creator, $packagePath) { parent::__construct(); $this->creator = $creator; $this->packagePath = $packagePath; } /** * {@inheritDoc} */ public function fire() { // It's possible for the developer to specify the tables to modify in this // schema operation. The developer may also specify if this label needs // to be freshly created so we can create the appropriate migrations. $name = $this->input->getArgument('name'); $label = $this->input->getOption('label'); $modify = $this->input->getOption('create'); if ( ! $label && is_string($modify)) { $label = $modify; } // Now we are ready to write the migration out to disk. Once we've written // the migration out, we will dump-autoload for the entire framework to // make sure that the migrations are registered by the class loaders. $this->writeMigration($name, $label); $this->call('dump-autoload'); } /** * Write the migration file to disk. * * @param string $name * @param string $label * @param bool $create * @return string */ protected function writeMigration($name, $label) { $path = $this->getMigrationPath(); $file = pathinfo($this->creator->create($name, $path, $label), PATHINFO_FILENAME); $this->line("<info>Created Migration:</info> $file"); } /** * {@inheritDoc} */ protected function getArguments() { return array( array('name', InputArgument::REQUIRED, 'The name of the migration'), ); } /** * {@inheritDoc} */ protected function getOptions() { return array( array('bench', null, InputOption::VALUE_OPTIONAL, 'The workbench the migration belongs to.', null), array('create', null, InputOption::VALUE_OPTIONAL, 'The label schema to be created.'), array('package', null, InputOption::VALUE_OPTIONAL, 'The package the migration belongs to.', null), array('path', null, InputOption::VALUE_OPTIONAL, 'Where to store the migration.', null), array('label', null, InputOption::VALUE_OPTIONAL, 'The label to migrate.'), ); } }
mit
BanBart/Symfony2-Project
app/cache/dev/twig/73/61/a3743db2e60af0775bb3bc0f75e86dfe96a8ee258462c47d889f44823ab1.php
1017
<?php /* SonataDoctrineORMAdminBundle:Form:filter_admin_fields.html.twig */ class __TwigTemplate_7361a3743db2e60af0775bb3bc0f75e86dfe96a8ee258462c47d889f44823ab1 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = $this->env->loadTemplate("SonataAdminBundle:Form:filter_admin_fields.html.twig"); $this->blocks = array( ); } protected function doGetParent(array $context) { return "SonataAdminBundle:Form:filter_admin_fields.html.twig"; } protected function doDisplay(array $context, array $blocks = array()) { $this->parent->display($context, array_merge($this->blocks, $blocks)); } public function getTemplateName() { return "SonataDoctrineORMAdminBundle:Form:filter_admin_fields.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array (); } }
mit
galinski/jquery-countdown-rails
lib/jquery-countdown-rails.rb
416
require 'jquery-countdown-rails/version' # Public: Adds jquery-countdown to the asset pipeline, for rails and # standalone Sprockets module JqueryCountdownRails if defined? ::Rails if ::Rails.version.to_s < '3.1' require 'jquery-countdown-rails/railtie' else require 'jquery-countdown-rails/engine' end elsif defined? ::Sprockets require 'jquery-countdown-rails/sprockets' end end
mit
SrunSundy/NhameyWebBackEnd
application/views/pages/event.php
54333
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Event List | Dernham</title> <?php include 'imports/cssimport.php' ?> <style> p.list-shop-total{ font-size: 18px; font-weight: bold; color: #616161; } button.header-shop-btn{ border-radius: 0; font-weight: bold; } button.header-shop-btn i{ padding-right: 7px; } p.search-shop-result{ color:#9E9E9E; font-style: italic; line-height:40px; } div.advance-search-box{ border-bottom:2px solid #E0E0E0; display:none; background:#f6f7f9; } div.border-line{ margin-top:7px; height: 2px; background: #E0E0E0; } div.nham-div-line{ width: 50%; float:left; } p.text-show-style{ color: #757575; } p.text-show-style i{ padding-right:5px; } th{ color: #757575; } .shop-open-time{ color: #9E9E9E; padding-left: 1px; font-style: italic; } .active-shop{ font-size: 8px; padding-right: 5px; } img.table-shop-img{ width: 120px; height: 90px;; border-radius: 5px; top:6px; right:0; border: 2px solid #fff; box-shadow: 1px 1px 2px gray; } .shop-display-status{ transition: all 0.5s linear; } i.shop-edit{ font-size: 22px; color: #dd4b39; cursor: pointer; } @media screen and (max-width: 1198px) { #srch-order-by{ width: 100% !important; } .select2{ width: 100% !important; } } div.status-style{ position: relative; } div.appeal-status{ width:20px; height: 20px; background: #4CAF50; border-radius: 5px; position:absolute; top:-7px; left:-7px; border-radius:5px; } @media screen and (min-width: 768px) { #updateEventModal .modal-dialog, #shopFacilityModal .modal-dialog { width: 800px; /* New width for default modal */ } #updateEventModal .modal-sm , #shopFacilityModal .modal-sm { width: 350px; /* New width for small modal */ } } @media screen and (min-width: 992px) { #updateEventModal .modal-lg ,#shopFacilityModal .modal-lg { width: 950px; /* New width for large modal */ } } </style> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/plugins/Jcrop/jquery.Jcrop.css" /> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/nhamdis/csscontroller/updateshop-upload.css" /> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/nhamdis/csscontroller/addshop-validation.css" /> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/nhamdis/csscontroller/addshop-openmodal.css" /> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/nhamdis/css/nhamslider.css"> </head> <body class="hold-transition skin-red-light sidebar-mini"> <input type="hidden" id="base_url" value="<?php echo base_url() ?>" /> <input type="hidden" id="dis_img_path" value="<?php echo DIS_IMAGE_PATH ?>" /> <div class="wrapper"> <header class="main-header"> <?php include 'elements/headnavbar.php';?> </header> <!-- Left side column. contains the logo and sidebar --> <aside class="main-sidebar"> <?php include 'elements/leftnavbar.php';?> </aside> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> Event Management <small>create all the event here</small> </h1> <ol class="breadcrumb"> <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li> <li class="active">Event Management</li> </ol> </section> <!-- Main content --> <section class="content"> <div class="box box-danger" style="border-radius: 0;min-height: 500px;" > <div class="box-header"> <div class="col-lg-12"> <div class="row"> <div class="col-lg-7"> </div> <div class="col-lg-5"> <div class="row"> <div class="col-lg-12"> <div class="row"> <button type="button" class="btn btn-default pull-right header-shop-btn" id="btnAddEvent"> <i class="fa fa-plus-circle" aria-hidden="true"></i> Add Event </button> </div> </div> <div class="col-lg-12" style="padding-top:10px;" id="normal-search-box"> <div class="row"> <div class="col-lg-5"></div> <div class="col-lg-7"> <div class="row"> <div class="input-group "> <input type="text" name="table_search" id="whole-search" class="form-control input-sm pull-right" placeholder="Search shop name,content ,creator..."> <div class="input-group-btn"> <button id="btn-whole-search" class="btn btn-sm btn-default"><i class="fa fa-search"></i></button> </div> </div> </div> </div> </div> </div> </div> </div> <!-- add data --> <div class="col-lg-12"> </div> <!-- end add data --> </div> </div> <div class="col-lg-12" style="padding-top:-5px;"> <div class="row"> <div class="nham-div-line"> <div class="form-group"> <select class="form-control " id="shop-row-num" style="width: 70px;"> <option value="5">5</option> <option value="10" selected="selected" >10</option> <option value="15" >15</option> <option value="30">30</option> <option value="50" >50</option> </select> </div><!-- /.form-group --> </div> <div class="nham-div-line"> <p class="search-shop-result pull-right">searching results: <span id="total-record">0</span></p> </div> <div style="clear:both"></div> </div> </div> </div><!-- /.box-header --> <!-- table and pagination --> <div class="box-body table-responsive no-padding" style="margin-top:-10px;" > <table class="table table-hover" > <thead> <tr> <th style="width:15%">Photo</th> <th style="width:28%">Content</th> <th style="width:15%">Shop</th> <th style="width:15%">Created Date</th> <th style="width:10%">Creator</th> <th style="width:10%">Status</th> <th style="width:7%">Action</th> </tr> </thead> <tbody id="display-eve-result"> </tbody> </table> </div><!-- /.box-body --> <div class="" > <div id="pagi-display" class="pagination-display " style="padding-left:20px;"> </div> </div> <!-- end table and pagination --> </div><!-- /.box --> </section><!-- /.content --> </div><!-- /.content-wrapper --> <footer class="main-footer"> <?php include 'elements/footnavbar.php';?> </footer> <!-- Control Sidebar --> </div><!-- ./wrapper --> <!-- update event popup --> <div class="modal fade" id="updateEventModal" role="dialog"> <div class="modal-dialog" > <div class="modal-content"> <div class="modal-header"> <button type="button" id="shopfacilityclose" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title pop-title" style="font-weight:bold;"><i class="fa fa-th-large" aria-hidden="true" style="padding-right: 10px;"></i>Update Event</h4> </div> <div class="modal-body"> <input type="hidden" value="" id="evt_id_update"/> <div class="col-lg-6"> <div class="row"> <div class="form-group"> <label>Shop Name</label> <div id="u_shop_name_to_put" style="width: 100%; height: 40px; border: 1px solid #e4e4e4; cursor:pointer"> </div> </div> <div class="form-group"> <label>Event's Image</label> <div class="col-lg-12 photo-browsing-wrapper" align="center"> <div class="row"> <div class="col-lg-12" align="center" style="position:relative;"> <div class="photo-display-wrapper" style="width:67%;min-height:180px;" id="u_cover-display-wrapper"> <!-- <label class="gray-image-plus"><i class="fa fa-plus"></i></label> <p style="font-weight:bold;color:#9E9E9E;margin-top:-10px;"> Add image </p> --> </div> <!-- fake on --> <div class="photo-open-modal" id="u_cover-open-modal"></div> <div class="photo-upload-remove-fake" id="u_cover-upload-remove-fake"></div> <div class="photo-upload-remove" id="u_cover-upload-remove"> <i id="u_cover-upload-remove-icon" class="fa fa-trash" aria-hidden="true"></i> </div> <div class="photo-remove-loading" id="u_cover-remove-loading" align="center"> <img class="loading-inside-box" src="<?php echo base_url() ?>/assets/nhamdis/img/ringsmall.svg" /> </div> <!-- end fake on --> </div> <!-- <textarea rows="" placeholder="have your word about this..." id="cover_description" class="nham_description" cols=""></textarea> --> </div> </div> </div> </div> </div> <div class="col-lg-6"> <div class="row" style="padding-left: 10px"> <div class="form-group"> <label>Event's Description</label> <textarea id="u_event_cntt" class="form-control" rows="3" placeholder="describe what the event is all about" style="resize:none;height: 272px;"></textarea> </div> </div> </div> <div style="clear:both;"></div> </div> <div class="modal-footer"> <button type="button" id="belowcloseshopfacility" class="btn btn-default pull-left" style="display:none;" data-dismiss="modal">Close</button> <button type="button" id="updateEvent" class="btn nham-btn btn-danger">Update</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --><!-- Modal --> <button type="button" id="u_btnShowPopUp" style="display:none;" data-toggle="modal" style="display:none;" data-backdrop="static" data-keyboard="false" data-target="#updateEventModal">Open Modal</button> <!-- end update event popup --> <!--add event popup --> <div class="modal fade" id="shopFacilityModal" role="dialog"> <div class="modal-dialog" > <div class="modal-content"> <div class="modal-header"> <button type="button" id="shopfacilityclose" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title pop-title" style="font-weight:bold;"><i class="fa fa-th-large" aria-hidden="true" style="padding-right: 10px;"></i>Add Event</h4> </div> <div class="modal-body"> <div class="col-lg-6"> <div class="row"> <div class="form-group"> <label>Shop Name</label> <div id="shop_name_to_put" style="width: 100%; height: 40px; border: 1px solid #e4e4e4; cursor:pointer"> </div> </div> <div class="form-group"> <label>Event's Image</label> <div class="col-lg-12 photo-browsing-wrapper" align="center"> <div class="row"> <div class="col-lg-12" align="center" style="position:relative;"> <div class="photo-display-wrapper" style="width:67%;min-height:180px;" id="cover-display-wrapper"> <label class="gray-image-plus"><i class="fa fa-plus"></i></label> <p style="font-weight:bold;color:#9E9E9E;margin-top:-10px;"> Add image </p> </div> <!-- fake on --> <div class="photo-open-modal" id="cover-open-modal"></div> <div class="photo-upload-remove-fake" id="cover-upload-remove-fake"></div> <div class="photo-upload-remove" id="cover-upload-remove"> <i id="cover-upload-remove-icon" class="fa fa-trash" aria-hidden="true"></i> </div> <div class="photo-remove-loading" id="cover-remove-loading" align="center"> <img class="loading-inside-box" src="<?php echo base_url() ?>/assets/nhamdis/img/ringsmall.svg" /> </div> <!-- end fake on --> </div> <!-- <textarea rows="" placeholder="have your word about this..." id="cover_description" class="nham_description" cols=""></textarea> --> </div> </div> </div> </div> </div> <div class="col-lg-6"> <div class="row" style="padding-left: 10px"> <div class="form-group"> <label>Event's Description</label> <textarea id="event_cntt" class="form-control" rows="3" placeholder="describe what the event is all about" style="resize:none;height: 272px;"></textarea> </div> </div> </div> <div style="clear:both;"></div> </div> <div class="modal-footer"> <button type="button" id="belowcloseshopfacility" class="btn btn-default pull-left" style="display:none;" data-dismiss="modal">Close</button> <button type="button" id="saveEvent" class="btn nham-btn btn-danger">Save</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --><!-- Modal --> <button type="button" id="btnShowPopUp" style="display:none;" data-toggle="modal" style="display:none;" data-backdrop="static" data-keyboard="false" data-target="#shopFacilityModal">Open Modal</button> <!-- end add event popup --> <!-- list of shop --> <div class="modal fade" id="listShopModal" role="dialog"> <div class="modal-dialog" > <div class="modal-content"> <div class="modal-header"> <button type="button" id="shopfacilityclose" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title pop-title" style="font-weight:bold;"><i class="fa fa-th-large" aria-hidden="true" style="padding-right: 10px;"></i>Shop List</h4> </div> <div class="modal-body" style="height: 600px;"> <div class="col-lg-6"></div> <div class="input-group col-lg-6"> <input type="text" name="table_search" id="shop_search" class="form-control input-sm pull-right" placeholder="Search shop name,type ,address..."> <div class="input-group-btn"> <button id="btn_shop_srch" class="btn btn-sm btn-default"><i class="fa fa-search"></i></button> </div> </div> <!-- table and pagination --> <div class="box-body table-responsive no-padding" style="" > <table class="table table-hover" > <thead> <tr> <th style="width:20%">Logo</th> <th style="width:30%">Name</th> <th style="width:50%">Address</th> </tr> </thead> </table> </div><!-- /.box-body --> <div class="box-body table-responsive no-padding" id="shop-content" style="height:500px;overflow-y: auto;" > <table class="table table-hover" > <tbody id="display-listshop-result"> </tbody> </table> </div><!-- /.box-body --> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --><!-- Modal --> <button type="button" id="btnListShop" style="display:none;" data-toggle="modal" style="display:none;" data-backdrop="static" data-keyboard="false" data-target="#listShopModal">Open Modal</button> <!--end list of shop --> <!-- cover upload modal --> <div class="modal fade" id="coverModal" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="nham-modal-header"> <button type="button" id="coverformclose" class="close btn-close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <p class="nham-modal-title"> <i class="fa fa-picture-o" aria-hidden="true"></i><span>Upload Image</span> </p> </div> <div class="nham-modal-body"> <div class="photo-browse-box" align="center"> <div class="photo-upload-info" > <p class="text-upload-info"> <span>Browse Photo </span> </p> </div> <!-- fake on --> <div class="trigger-photo-browse" id="trigger-cover-browse"></div> <!-- end fake on --> </div> <input type='file' id="uploadcover" style="display:none" accept="image/*"/> <div class="upload-photo-box" id="cover-upload-box"> <div class="photo-upload-wrapper" align="center" id="display-cover-upload" > <div class="photo-upload-info-2" > <i class="fa fa-picture-o" aria-hidden="true"></i> </div> </div> <!-- fake on --> <div class="photo-upload-loading" id="cover-upload-loading" align="center"> <div class="photo-upload-progress-box"> <div id="cover-upload-progress" class="progress-bar progress-bar-danger progress-bar-striped" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="height:10px;"> </div> </div> <div style="width: 100%;"> <p id="cover-upload-percentage" class="photo-upload-percentage">0%</p> <img src="<?php echo base_url(); ?>assets/nhamdis/img/ring.svg" /> </div> </div> <div class="photo-fail-remove" id="cover-fail-remove"> <i class="fa fa-times" id="cover-fail-event" aria-hidden="true"></i> </div> <!-- end fake on --> </div> <!-- <div class="photo-description-box" id="cover-description-box"> <textarea rows="" id="cover_description" placeholder="have your word about this..." class="photo-description" cols=""></textarea> </div> --> <div class="photo-btncrop-box" id="cover-btncrop-box"> <button type="button" id="cover-crop-btn" class="btn btn-crop">Crop image</button> <button type="button" id="cover-save-btn" class="btn photo-save-btn btn-danger">Save</button> </div> </div> <div class="nham-modal-footer"> </div> </div> <!-- /.modal-content --> </div> <!-- /.modal-dialog --> </div> <button type="button" id="openCoverModel" style="display:none;" data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#coverModal">Open Modal</button> <!-- cover upload modal --> <!-- event update upload modal --> <div class="modal fade" id="u_coverModal" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="nham-modal-header"> <button type="button" id="u_coverformclose" class="close btn-close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <p class="nham-modal-title"> <i class="fa fa-picture-o" aria-hidden="true"></i><span>Upload Image</span> </p> </div> <div class="nham-modal-body"> <div class="photo-browse-box" align="center"> <div class="photo-upload-info" > <p class="text-upload-info"> <span>Browse Photo </span> </p> </div> <!-- fake on --> <div class="trigger-photo-browse" id="u_trigger-cover-browse"></div> <!-- end fake on --> </div> <input type='file' id="u_uploadcover" style="display:none" accept="image/*"/> <div class="upload-photo-box" id="u_cover-upload-box"> <div class="photo-upload-wrapper" align="center" id="u_display-cover-upload" > <div class="photo-upload-info-2" > <i class="fa fa-picture-o" aria-hidden="true"></i> </div> </div> <!-- fake on --> <div class="photo-upload-loading" id="u_cover-upload-loading" align="center"> <div class="photo-upload-progress-box"> <div id="u_cover-upload-progress" class="progress-bar progress-bar-danger progress-bar-striped" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="height:10px;"> </div> </div> <div style="width: 100%;"> <p id="u_cover-upload-percentage" class="photo-upload-percentage">0%</p> <img src="<?php echo base_url(); ?>assets/nhamdis/img/ring.svg" /> </div> </div> <div class="photo-fail-remove" id="u_cover-fail-remove"> <i class="fa fa-times" id="u_cover-fail-event" aria-hidden="true"></i> </div> <!-- end fake on --> </div> <!-- <div class="photo-description-box" id="cover-description-box"> <textarea rows="" id="cover_description" placeholder="have your word about this..." class="photo-description" cols=""></textarea> </div> --> <div class="photo-btncrop-box" id="u_cover-btncrop-box"> <button type="button" id="u_cover-crop-btn" class="btn btn-crop">Crop image</button> <button type="button" id="u_cover-save-btn" class="btn photo-save-btn btn-danger">Save</button> </div> </div> <div class="nham-modal-footer"> </div> </div> <!-- /.modal-content --> </div> <!-- /.modal-dialog --> </div> <button type="button" id="u_openCoverModel" style="display:none;" data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#u_coverModal">Open Modal</button> <!-- event update upload modal --> <?php include 'imports/scriptimport.php'; ?> </body> <script type="text/javascript"> jQuery.browser = {}; (function () { jQuery.browser.msie = false; jQuery.browser.version = 0; if (navigator.userAgent.match(/MSIE ([0-9]+)\./)) { jQuery.browser.msie = true; jQuery.browser.version = RegExp.$1; } })(); </script> <script src="<?php echo base_url(); ?>assets/plugins/Jcrop/jquery.Jcrop.js"></script> <script id="display-eve-table" type="text/x-jQuery-tmpl"> <tr> <td class="evt_img"> <input id="evt_id" type="hidden" value="{{= evt_id}}"/> <div class="img-logo-wrapper" > <img class="table-shop-img" src="{{= domainImageSrc('event/small/'+evt_img) }}" /> </div> </td> <td class="evt_cntt"> <input id="evt_cntt" type="hidden" value="{{= evt_cntt}}"/> <div> {{= subText( evt_cntt, 150) }} </div> </td> <td class="shop_data"> <input id="shop_logo" type="hidden" value="{{= shop_logo }}" /> <div data-shop_id="{{= shop_id }}"> {{= shop_name_en }} ( {{= shop_name_kh }} ) </div> </td> <td> <div> {{= created_date }} </div> </td> <td> <div> {{= admin_name }} </div> </td> <td> <div class="status-style"> <div class="appeal-status" id="{{= generateIdWithShopId('toggleEve',evt_id)}}" style="background: {{= backgroundStatus(status) }}"></div> <select class="form-control evtstatus" > <option value="0" {{= checkStatus(0 , status) }}> Disabled </option> <option value="1" {{= checkStatus(1 , status) }}> Active </option> </select> </div> </td> <td> <div> <i class="shop-edit fa fa-pencil-square" aria-hidden="true"></i> </div> </td> </tr> </script> <script id="display-listshop-table" type="text/x-jQuery-tmpl"> <tr style="cursor:pointer" class="shop_item"> <td style="width:20%" class="store_data"> <input id="shop_id" type="hidden" value="{{= shop_id }}"/> <input id="shop_name" type="hidden" value="{{= shop_name_en }}"/> <img src="{{= domainImageSrc('place/logo/small/'+shop_logo) }}" style="width:30px;height:30px;border-radius: 100%;"/> </td> <td style="width:30%"> <span>{{= shop_name_en }}</span> </td> <td style="width:40%">{{= shop_address }}</td> </tr> </script> <script> var pageNum = 1; var totalPage = 1; var srchKey = ""; var pageRow = 10; var pageShNum = 1; var totalShPage = 1 var srchShKey = ""; var shopIdIn = ""; var shopNameIn = ""; var shopLogoIn = ""; var shopIdUp = ""; var shopNameUp = ""; var shopLogoUp = ""; var clickPopUplistShop = 0; $(document).ready(function(){ listEvent(); }); $("#btn-whole-search").on("click", function(){ srchKey = $("#whole-search").val(); listEvent(); }); $("#shop-row-num").on("change", function(){ pageNum = 1; pageRow = $(this).val(); listEvent(); }); $('#whole-search').keypress(function (e) { if (e.which == 13) { $("#btn-whole-search").click(); return false; //<---- Add this line } }); $("#btnAddEvent").on("click", function(){ $('#btnShowPopUp').click(); }); $("#shop_name_to_put").on("click", function(){ clickPopUplistShop = 1; pageShNum = 1; listShop(false); $('#btnListShop').click(); }); $("#btn_shop_srch").on("click", function(){ srchShKey = $("#shop_search").val(); pageShNum = 1; listShop(false); }); $('#shop_search').keypress(function (e) { if (e.which == 13) { $("#btn_shop_srch").click(); return false; //<---- Add this line } }); $(document).on("dblclick","tr.shop_item", function(){ var item = $(this).find("td.store_data"); if(clickPopUplistShop == 1){ shopIdIn = item.find("input#shop_id").val(); shopNameIn = item.find("input#shop_name").val(); shopLogoIn = item.find("img").attr("src"); var html = "<div style='float:left;margin: 4px 5px 0 5px'>"; html += "<img src='"+shopLogoIn+"' style='width:30px;height:30px;border-radius: 100%;'>"; html += "</div>"; html += "<div style='float:left;margin-left: 10px;'>"; html += "<p style='margin-top: 8px;'>"+shopNameIn+"</p>"; html += "</div>"; html += "<div style='clear:both;'></div>"; $("#shop_name_to_put").html(html); }else if(clickPopUplistShop == 2){ shopIdUp = item.find("input#shop_id").val(); shopNameUp = item.find("input#shop_name").val(); shopLogoUp = item.find("img").attr("src"); var html = "<div style='float:left;margin: 4px 5px 0 5px'>"; html += "<img src='"+shopLogoUp+"' style='width:30px;height:30px;border-radius: 100%;'>"; html += "</div>"; html += "<div style='float:left;margin-left: 10px;'>"; html += "<p style='margin-top: 8px;'>"+shopNameUp+"</p>"; html += "</div>"; html += "<div style='clear:both;'></div>"; $("#u_shop_name_to_put").html(html); } $('#listShopModal').modal('hide'); }); $(document).on("change", ".evtstatus" ,function(){ var evtid = $(this).parents("tr").children("td").eq(0).find("input").val(); var first_status_val = $(this).val(); var my_obj = this; $(this).prop("disabled", "disabled"); toggleEvent( first_status_val ,evtid , function(data){ console.log(data); $(my_obj).removeAttr("disabled"); if(data.response_code == "200"){ $("#toggleEve"+evtid).css({ "background" : backgroundStatus(first_status_val) }); }else{ var goback = (first_status_val == 0) ? 1 : 0; $(my_obj).val(goback); swal("Update Error!", data.message, "error"); } //swal("Shop is updated!", "This shop will be visible for clients", "success"); }); }); $(document).ready(function() { $("#shop-content").endlessScroll({ callback: function() { if( pageShNum <= totalShPage){ srchShKey = $("#shop_search").val(); listShop(true); } } }); }); $("#saveEvent").on("click", function(){ saveEvent(); }); /*update event*/ var evt_img_glo; var shop_id_glo; $(document).on("click",".shop-edit", function(){ var obj = $(this).parents("tr"); shop_id_glo = obj.find("td.shop_data div").attr("data-shop_id"); var shop_logo = obj.find("td.shop_data input#shop_logo").val(); var shop_name = obj.find("td.shop_data div").text(); evt_img_glo = obj.find("td.evt_img img.table-shop-img").attr("src"); var evt_cntt = obj.find("td.evt_cntt input#evt_cntt").val(); var evt_id = obj.find("td.evt_img input#evt_id").val(); //console.log(shop_logo, shop_name, evt_img, evt_cntt, evt_id); var html = "<div style='float:left;margin: 4px 5px 0 5px'>"; html += "<img src='"+domainImageSrc('place/logo/small/'+shop_logo)+"' style='width:30px;height:30px;border-radius: 100%;'>"; html += "</div>"; html += "<div style='float:left;margin-left: 10px;'>"; html += "<p style='margin-top: 8px;'>"+shop_name+"</p>"; html += "</div>"; html += "<div style='clear:both;'></div>"; var myimg ='<img class="upload-shop-img"'; myimg +='src="'+evt_img_glo+'" alt="your image" />'; $("#u_shop_name_to_put").html(html); $("#u_event_cntt").val(evt_cntt); $("#evt_id_update").val(evt_id); $("#u_cover-display-wrapper").html(myimg); $("#u_btnShowPopUp").click(); }); $("#u_shop_name_to_put").on("click", function(){ clickPopUplistShop = 2; pageShNum = 1; listShop(false); $('#btnListShop').click(); }); $("#updateEvent").on("click", function(){ updateEvent(); }); function updateEvent(){ var evt_cntt = $("#u_event_cntt").val(); var evt_id = $("#evt_id_update").val(); var evt_img = evt_img_glo.substr(evt_img_glo.lastIndexOf('/') + 1); if(u_coverimagename) evt_img = u_coverimagename; var shop_id = shop_id_glo; if(shopIdUp) shop_id = shopIdUp; $.ajax({ type : "POST", url : $("#base_url").val()+"API/EventRestController/updateevent", contentType : "application/json", data : JSON.stringify({ "request_data" : { "evt_id" : evt_id, "shop_id" : shop_id, "evt_img" : evt_img, "evt_cntt" : evt_cntt } }), success : function(data){ shopIdUp = ""; u_coverimagename = ""; evt_img_glo = ""; $('#updateEventModal').modal('hide'); pageNum = 1; listEvent(); } }); } /*end update event*/ function saveEvent(){ $.ajax({ type : "POST", url : $("#base_url").val()+"API/EventRestController/addevent", contentType : "application/json", data : JSON.stringify({ "request_data" : { "shop_id" : shopIdIn, "evt_img" : coverimagename, "evt_cntt" : $("#event_cntt").val() } }), success : function(data){ $('#shopFacilityModal').modal('hide'); pageShNum = 1; listEvent(); } }); } function toggleEvent(status , evtId, callback){ $.ajax({ type : "POST", url : $("#base_url").val()+"API/EventRestController/toggleevent", contentType : "application/json", data : JSON.stringify({ "request_data" : { "evt_id" : evtId, "status" : status } }), success : function(data){ data = JSON.parse(data); if( typeof callback === "function"){ callback(data); } } }); } function listEvent(){ progressbar.start(); $.ajax({ type : "POST", url : $("#base_url").val()+"API/EventRestController/listevent", contentType : "application/json", data : JSON.stringify({ "request_data" : { "page" : pageNum, "row" : pageRow, "srch_key" : srchKey } }), success : function(data){ data = JSON.parse(data); console.log(data.response_data); $("#display-eve-result").children().remove(); $("#display-eve-table").tmpl(data.response_data).appendTo("#display-eve-result"); $("#total-record").html(data.total_record); totalPage = data.total_page; $('#pagi-display').bootpag({ total : totalPage, maxVisible: 5, leaps: true, firstLastUse: true, first: '&#8592;', last: '&#8594;', wrapClass: 'pagination', activeClass: 'active', disabledClass: 'disabled', nextClass: 'next', prevClass: 'prev', lastClass: 'last', firstClass: 'first' }); progressbar.stop(); }, xhr: function() { var xhr = new XMLHttpRequest(); xhr.upload.addEventListener("progress", function(event) { if (event.lengthComputable) { var percentComplete = Math.round( (event.loaded / event.total) * 100 ); //console.log(percentComplete); $("#start_progress_bar").css({width: percentComplete+"%"}); }; }, false); return xhr; } }); } var process = false; function listShop(scroll){ if(!process){ process = true; $.ajax({ type: "GET", url: $("#base_url").val()+"API/ShopRestController/getShopByChoice", data : { "srch_key" : srchShKey, "row" : 10, "page" : pageShNum }, success: function(data){ data = JSON.parse(data); console.log(data); totalShPage = data.total_page; if(!scroll){ $("#display-listshop-result").children().remove(); } $("#display-listshop-table").tmpl(data.response_data).appendTo("#display-listshop-result"); process = false; pageShNum++ } }); } } function subText(str, cutvalue){ if(!str) return ""; if(str.length > cutvalue){ return str.substring(0,cutvalue)+"..."; }else{ return str; } } function checkStatus( status , compare ){ if(status == compare){ return "selected"; }else{ return ""; } } function generateIdWithShopId(text,shopid){ return text+shopid; } function backgroundStatus( status ){ if(status == "1" || status == 1){ return "#4CAF50"; }else{ return "#F44336"; } } function domainImageSrc(img){ return $("#dis_img_path").val()+"/uploadimages/real/"+img; } /*===================== upload event update =============================*/ var u_coverimagename = ""; var u_backuprealcoverimage; var u_img_x = 0; var u_img_y = 0; var u_img_w = 0; var u_img_h = 0; $("#u_cover-open-modal").on("click", function(){ $("#u_openCoverModel").click(); }); $("#u_trigger-cover-browse").on("click",function(){ $("#u_uploadcover").click(); }); $("#u_uploadcover").on("change", function(){ u_uploadCover(this); }); $("#u_cover-fail-event").on("click" , function(){ u_coverimagename = ""; $("#u_uploadcover").val(null); $(this).parent().hide(); var txt = '<div class="photo-upload-info-2" >'; txt += ' <i class="fa fa-picture-o" aria-hidden="true"></i>'; txt += '</div>'; $('#u_display-cover-upload').html(txt); }); $("#u_coverformclose").on("click", function(){ if(u_coverimagename) { var txt = '<div class="photo-upload-info-2" >'; txt += ' <i class="fa fa-picture-o" aria-hidden="true"></i>'; txt += '</div>'; //$("#cover-description").val(""); $('#u_display-cover-upload').html(txt); //$("#cover-description-box").hide(); $("#u_cover-btncrop-box").hide(); u_removeCoverImageFromServer().success(function(data){ u_coverimagename = ""; $("#u_uploadcover").val(null); }); } }); $("#u_cover-crop-btn").on("click", function(){ u_upoloadCoverToServer(); $(this).hide(); }); $("#u_cover-save-btn").on("click", function(){ $('#u_coverModal').modal('hide'); $("#u_cover_description").show(); $("#u_cover-upload-remove-fake").show(); $("#u_cover-upload-remove").show(); var myimg ='<img class="upload-shop-img"'; myimg +='src="'+$("#dis_img_path").val()+'/uploadimages/real/event/medium/'+u_coverimagename+'" alt="your image" />'; $('#u_cover-display-wrapper').html(myimg); var txt = '<div class="photo-upload-info-2" >'; txt += ' <i class="fa fa-picture-o" aria-hidden="true"></i>'; txt += '</div>'; $('#u_display-cover-upload').html(txt); $("#u_cover-btncrop-box").hide(); // coverimagename = ""; //$("#uploadcover").val(null); }); $("#u_cover-upload-remove-icon").on("click", function(){ $(this).parent().hide(); var txt = '<label class="gray-image-plus">'; txt += '<i class="fa fa-plus"></i>'; txt += '</label>'; txt += '<p style="font-weight:bold;color:#9E9E9E;margin-top:-10px;"> 960 x 500 </p>'; txt += '<p style="font-weight:bold;color:#9E9E9E;margin-top:-10px;"> Add cover image </p>'; $(this).parent().siblings(".photo-display-wrapper").html(txt); $(this).parent().siblings(".photo-remove-loading").show(); $("#u_cover-upload-remove-fake").hide(); $("#u_cover-remove-loading").hide(); $("#u_cover_description").hide(); u_removeCoverImageFromServer().success(function(data){ u_coverimagename = ""; $("#u_uploadcover").val(null); }); }); function u_uploadCover(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { if(u_coverimagename) { u_removeCoverImageFromServer().success(function(data){ u_coverimagename = ""; }); } $("#u_cover-crop-btn").show(); $("#u_cover-save-btn").hide(); //$("#cover-description-box").hide(); var image = new Image(); image.src = e.target.result; image.onload = function () { var height = this.height; var width = this.width; $("#u_cover-btncrop-box").show(); var myimg ='<img class="photo-upload-output" src="'+e.target.result+'" id="u_cropcover" alt="your image" />'; $('#u_display-cover-upload').html(myimg); $('#u_cropcover').Jcrop({ aspectRatio: 16 / 10, onSelect: updateCoords, onChange: updateCoords, setSelect: [0,0,110,110], trueSize: [width,height] }); u_backuprealcoverimage = $("#u_uploadcover")[0].files[0]; } } reader.readAsDataURL(input.files[0]); } } function u_updateCoords(c){ img_x = c.x; img_y = c.y; img_w = c.w; img_h = c.h; } function u_getCropImgData(){ var crop_img_data = { "img_x" : img_x, "img_y" : img_y, "img_w" : img_w, "img_h" : img_h }; return crop_img_data; } function u_removeCoverImageFromServer(){ return $.ajax({ url : $("#u_base_url").val()+"API/UploadRestController/removeEvent", type: "POST", data : { "IMG_NAME": u_coverimagename } }); } function u_upoloadCoverToServer(){ //var inputFile = $("#uploadcover"); $("#u_cover-upload-progress").css({width:"0%"}); $("#u_cover-upload-percentage").html(0); $("#u_cover-upload-loading").show(); var fileToUpload = u_backuprealcoverimage; if(fileToUpload != 'undefined'){ var formData = new FormData(); formData.append("file", fileToUpload); formData.append("json", JSON.stringify(u_getCropImgData())); $.ajax({ url: $("#base_url").val()+"API/UploadRestController/uploadEventImage", type: "POST", data : formData, processData : false, contentType : false, success: function(data){ data = JSON.parse(data); if(data.is_upload == false){ swal({ title: "Upload Error!", text: data.message, html: true, type: "error", }); u_coverimagename = ""; $("#u_cover-fail-remove").show(); //$("#cover-description-box").hide(); $("#u_cover-btncrop-box").hide(); }else{ $("#u_cover-save-btn").show(); //$("#cover-description-box").show(); u_coverimagename = data.filename; var uploadedimg ='<img class="photo-upload-output" ' +'src="'+$("#dis_img_path").val()+'/uploadimages/real/event/big/'+u_coverimagename+'" ' +'alt="your image" />'; $('#u_display-cover-upload').html(uploadedimg); } $("#u_cover-upload-loading").hide(); }, xhr: function() { var xhr = new XMLHttpRequest(); xhr.upload.addEventListener("progress", function(event) { if (event.lengthComputable) { var percentComplete = Math.round( (event.loaded / event.total) * 100 ); $("#u_cover-upload-progress").css({width: percentComplete+"%"}); $("#u_cover-upload-percentage").html(percentComplete+"%"); }; }, false); return xhr; } }); } } /*===================== end upload update event =========================*/ /*===================== upload cover event =============================*/ var coverimagename = ""; var backuprealcoverimage; var img_x = 0; var img_y = 0; var img_w = 0; var img_h = 0; $("#cover-open-modal").on("click", function(){ $("#openCoverModel").click(); }); $("#trigger-cover-browse").on("click",function(){ $("#uploadcover").click(); }); $("#uploadcover").on("change", function(){ uploadCover(this); }); $("#cover-fail-event").on("click" , function(){ coverimagename = ""; $("#uploadcover").val(null); $(this).parent().hide(); var txt = '<div class="photo-upload-info-2" >'; txt += ' <i class="fa fa-picture-o" aria-hidden="true"></i>'; txt += '</div>'; $('#display-cover-upload').html(txt); }); $("#coverformclose").on("click", function(){ if(coverimagename) { var txt = '<div class="photo-upload-info-2" >'; txt += ' <i class="fa fa-picture-o" aria-hidden="true"></i>'; txt += '</div>'; //$("#cover-description").val(""); $('#display-cover-upload').html(txt); //$("#cover-description-box").hide(); $("#cover-btncrop-box").hide(); removeCoverImageFromServer().success(function(data){ coverimagename = ""; $("#uploadcover").val(null); }); } }); $("#cover-crop-btn").on("click", function(){ upoloadCoverToServer(); $(this).hide(); }); $("#cover-save-btn").on("click", function(){ $('#coverModal').modal('hide'); $("#cover_description").show(); $("#cover-upload-remove-fake").show(); $("#cover-upload-remove").show(); var myimg ='<img class="upload-shop-img"'; myimg +='src="'+$("#dis_img_path").val()+'/uploadimages/real/event/medium/'+coverimagename+'" alt="your image" />'; $('#cover-display-wrapper').html(myimg); var txt = '<div class="photo-upload-info-2" >'; txt += ' <i class="fa fa-picture-o" aria-hidden="true"></i>'; txt += '</div>'; $('#display-cover-upload').html(txt); $("#cover-btncrop-box").hide(); // coverimagename = ""; //$("#uploadcover").val(null); }); $("#cover-upload-remove-icon").on("click", function(){ $(this).parent().hide(); var txt = '<label class="gray-image-plus">'; txt += '<i class="fa fa-plus"></i>'; txt += '</label>'; txt += '<p style="font-weight:bold;color:#9E9E9E;margin-top:-10px;"> 960 x 500 </p>'; txt += '<p style="font-weight:bold;color:#9E9E9E;margin-top:-10px;"> Add cover image </p>'; $(this).parent().siblings(".photo-display-wrapper").html(txt); $(this).parent().siblings(".photo-remove-loading").show(); $("#cover-upload-remove-fake").hide(); $("#cover-remove-loading").hide(); $("#cover_description").hide(); removeCoverImageFromServer().success(function(data){ coverimagename = ""; $("#uploadcover").val(null); }); }); function uploadCover(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { if(coverimagename) { removeCoverImageFromServer().success(function(data){ coverimagename = ""; }); } $("#cover-crop-btn").show(); $("#cover-save-btn").hide(); //$("#cover-description-box").hide(); var image = new Image(); image.src = e.target.result; image.onload = function () { var height = this.height; var width = this.width; $("#cover-btncrop-box").show(); var myimg ='<img class="photo-upload-output" src="'+e.target.result+'" id="cropcover" alt="your image" />'; $('#display-cover-upload').html(myimg); $('#cropcover').Jcrop({ aspectRatio: 16 / 10, onSelect: updateCoords, onChange: updateCoords, setSelect: [0,0,110,110], trueSize: [width,height] }); backuprealcoverimage = $("#uploadcover")[0].files[0]; } } reader.readAsDataURL(input.files[0]); } } function updateCoords(c){ img_x = c.x; img_y = c.y; img_w = c.w; img_h = c.h; } function getCropImgData(){ var crop_img_data = { "img_x" : img_x, "img_y" : img_y, "img_w" : img_w, "img_h" : img_h }; return crop_img_data; } function removeCoverImageFromServer(){ return $.ajax({ url : $("#base_url").val()+"API/UploadRestController/removeEvent", type: "POST", data : { "IMG_NAME": coverimagename } }); } function upoloadCoverToServer(){ //var inputFile = $("#uploadcover"); $("#cover-upload-progress").css({width:"0%"}); $("#cover-upload-percentage").html(0); $("#cover-upload-loading").show(); var fileToUpload = backuprealcoverimage; if(fileToUpload != 'undefined'){ var formData = new FormData(); formData.append("file", fileToUpload); formData.append("json", JSON.stringify(getCropImgData())); $.ajax({ url: $("#base_url").val()+"API/UploadRestController/uploadEventImage", type: "POST", data : formData, processData : false, contentType : false, success: function(data){ data = JSON.parse(data); if(data.is_upload == false){ swal({ title: "Upload Error!", text: data.message, html: true, type: "error", }); coverimagename = ""; $("#cover-fail-remove").show(); //$("#cover-description-box").hide(); $("#cover-btncrop-box").hide(); }else{ $("#cover-save-btn").show(); //$("#cover-description-box").show(); coverimagename = data.filename; var uploadedimg ='<img class="photo-upload-output" ' +'src="'+$("#dis_img_path").val()+'/uploadimages/real/event/big/'+coverimagename+'" ' +'alt="your image" />'; $('#display-cover-upload').html(uploadedimg); } $("#cover-upload-loading").hide(); }, xhr: function() { var xhr = new XMLHttpRequest(); xhr.upload.addEventListener("progress", function(event) { if (event.lengthComputable) { var percentComplete = Math.round( (event.loaded / event.total) * 100 ); $("#cover-upload-progress").css({width: percentComplete+"%"}); $("#cover-upload-percentage").html(percentComplete+"%"); }; }, false); return xhr; } }); } } /*===================== end upload cover event =========================*/ (function($){ $.fn.endlessScroll = function(options) { var defaults = { bottomPixels: 50, fireOnce: true, fireDelay: 150, loader: "<br />Loading...<br />", data: "", insertAfter: "div:last", resetCounter: function() { return false; }, callback: function() { return true; }, ceaseFire: function() { return false; } }; var options = $.extend({}, defaults, options); var firing = true; var fired = false; var fireSequence = 0; if (options.ceaseFire.apply(this) === true) { firing = false; } if (firing === true) { $(this).scroll(function() { if (options.ceaseFire.apply(this) === true) { firing = false; return; // Scroll will still get called, but nothing will happen } if (this == document || this == window) { var is_scrollable = $(document).height() - $(window).height() <= $(window).scrollTop() + options.bottomPixels; } else { // calculates the actual height of the scrolling container var inner_wrap = $(".endless_scroll_inner_wrap", this); if (inner_wrap.length == 0) { inner_wrap = $(this).wrapInner("<div class=\"endless_scroll_inner_wrap\" />").find(".endless_scroll_inner_wrap"); } var is_scrollable = inner_wrap.length > 0 && (inner_wrap.height() - $(this).height() <= $(this).scrollTop() + options.bottomPixels); } if (is_scrollable && (options.fireOnce == false || (options.fireOnce == true && fired != true))) { if (options.resetCounter.apply(this) === true) fireSequence = 0; fired = true; fireSequence++; $(options.insertAfter).after("<div id=\"endless_scroll_loader\">" + options.loader + "</div>"); data = typeof options.data == 'function' ? options.data.apply(this, [fireSequence]) : options.data; if (data !== false) { $(options.insertAfter).after("<div id=\"endless_scroll_data\">" + data + "</div>"); $("div#endless_scroll_data").hide().fadeIn(); $("div#endless_scroll_data").removeAttr("id"); options.callback.apply(this, [fireSequence]); if (options.fireDelay !== false || options.fireDelay !== 0) { $("body").after("<div id=\"endless_scroll_marker\"></div>"); // slight delay for preventing event firing twice $("div#endless_scroll_marker").fadeTo(options.fireDelay, 1, function() { $(this).remove(); fired = false; }); } else { fired = false; } } $("div#endless_scroll_loader").remove(); } }); } }; })(jQuery); </script> </html>
mit
dmitry-merzlyakov/the-cat-lang
OriginCode/cat-1-0-b4/CatVarRenamer.cs
6611
/// Dedicated to the public domain by Christopher Diggins /// http://creativecommons.org/licenses/publicdomain/ using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; namespace Cat { /// <summary> /// The renamer assigns new names to a set of variables either from a supplied /// dictionary or by generating unique names. /// </summary> public class CatVarRenamer { int mnId = 0; CatTypeVarList mNames; #region constructors public CatVarRenamer() { mNames = new CatTypeVarList(); } #endregion #region static functions public static bool IsStackVarName(string s) { Trace.Assert(s.Length > 0); Trace.Assert(s[0] == '\''); char c = s[1]; if (char.IsLower(c)) return false; else return true; } public CatKind GenerateNewVar(string s) { if (IsStackVarName(s)) return new CatStackVar("S" + (mnId++).ToString()); else return new CatTypeVar("t" + (mnId++).ToString()); } #endregion /// <summary> /// This forgets previously generated names, but assures that new names generated will be unique. /// </summary> public void ResetNames() { mNames.Clear(); } public static CatFxnType RenameVars(CatFxnType ft) { return (new CatVarRenamer()).Rename(ft); } public CatKind Rename(CatKind k) { if (k is CatFxnType) return Rename(k as CatFxnType); else if (k is CatTypeKind) return Rename(k as CatTypeKind); else if (k is CatStackVar) return Rename(k as CatStackVar); else if (k is CatTypeVector) return Rename(k as CatTypeVector); else if (k is CatCustomKind) return k; else if (k is CatRecursiveType) return k; else throw new Exception(k.ToString() + " is an unrecognized kind"); } public CatFxnType Rename(CatFxnType f) { if (f == null) throw new Exception("Invalid null parameter to rename function"); return new CatFxnType(Rename(f.GetCons()), Rename(f.GetProd()), f.HasSideEffects()); } public CatTypeVector Rename(CatTypeVector s) { CatTypeVector ret = new CatTypeVector(); foreach (CatKind k in s.GetKinds()) ret.Add(Rename(k)); return ret; } public CatStackKind Rename(CatStackVar s) { string sName = s.ToString(); if (mNames.ContainsKey(sName)) { CatKind tmp = mNames[sName]; if (!(tmp is CatStackKind)) throw new Exception(sName + " is not a stack kind"); return tmp as CatStackKind; } CatStackVar var = GenerateNewVar(sName) as CatStackVar; mNames.Add(sName, var); return var; } public CatTypeKind Rename(CatTypeKind t) { if (t == null) throw new Exception("Invalid null parameter to rename function"); if (t is CatFxnType) { return Rename(t as CatFxnType); } else if (t is CatTypeVar) { string sName = t.ToString(); if (mNames.ContainsKey(sName)) { CatTypeKind ret = mNames[sName] as CatTypeKind; if (ret == null) throw new Exception(sName + " is not a type kind"); return ret; } CatTypeVar var = GenerateNewVar(sName) as CatTypeVar; mNames.Add(sName, var); return var; } else { return t; } } public static bool DoesVarOccurIn(CatKind k, CatTypeVector vec, CatFxnType except) { foreach (CatKind tmp in vec.GetKinds()) { if (tmp.IsKindVar() && tmp.Equals(k)) return true; if (tmp is CatFxnType) if (DoesVarOccurIn(k, tmp as CatFxnType, except)) return true; } return false; } public static bool DoesVarOccurIn(CatKind k, CatFxnType ft, CatFxnType except) { if (!k.IsKindVar()) return false; if (k == except) return false; return DoesVarOccurIn(k, ft.GetCons(), except) || DoesVarOccurIn(k, ft.GetProd(), except); } public static bool IsFreeVar(CatKind k, CatFxnType left, CatFxnType right, CatFxnType except) { return !DoesVarOccurIn(k, left, except) && !DoesVarOccurIn(k, right, except); } public static CatFxnType RenameFreeVars(CatFxnType left, CatFxnType right, CatFxnType ft) { CatTypeVarList vars = ft.GetAllVars(); foreach (string s in vars.Keys) { CatKind k = vars[s]; if (IsFreeVar(k, left, right, ft)) { if (k is CatTypeVar) vars[s] = CatTypeVar.CreateUnique(); else vars[s] = CatStackVar.CreateUnique(); } } return RenameVars(ft, vars); } static CatTypeVector RenameVars(CatTypeVector vec, CatTypeVarList vars) { CatTypeVector ret = new CatTypeVector(); foreach (CatKind k in vec.GetKinds()) { if (k.IsKindVar() && vars.ContainsKey(k.ToString())) ret.Add(vars[k.ToString()]); else if (k is CatFxnType) ret.Add(RenameVars(ret, vars)); else if (k is CatTypeVector) throw new Exception("unexpected type vector in function during renaming"); else ret.Add(k); } return ret; } static CatFxnType RenameVars(CatFxnType ft, CatTypeVarList vars) { return new CatFxnType(RenameVars(ft.GetCons(), vars), RenameVars(ft.GetProd(), vars), ft.HasSideEffects()); } } }
mit
TelerikAcademy-Cloning/Databases
Sample-Exams/2015/Author/Problem 3 - Sample Data/PetStore.Importer/Importers/CategoryImporter.cs
1344
namespace PetStore.Importer.Importers { using System; using System.Collections.Generic; using System.IO; using PetStore.Data; public class CategoryImporter : IImporter { private const int NumberOfCountries = 50; public string Message { get { return "Importing categories"; } } public int Order { get { return 4; } } public Action<PetStoreEntities, TextWriter> Import { get { return (db, tr) => { for (int i = 0; i < NumberOfCountries; i++) { db.Categories.Add(new Category { Name = RandomGenerator.RandomString(5, 20) }); if (i % 10 == 0) { tr.Write("."); } if (i % 100 == 0) { db.SaveChanges(); db = new PetStoreEntities(); } } db.SaveChanges(); }; } } } }
mit
johnsonlin/portfolio
src/main.ts
391
import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import 'hammerjs'; import { AppModule } from './app/app.module'; import { environment } from './environments/environment'; if (environment.production) { enableProdMode(); } platformBrowserDynamic().bootstrapModule(AppModule) .catch(err => console.error(err));
mit
kittehcoin/kittehcoin
src/qt/addressbookpage.cpp
12783
#include "addressbookpage.h" #include "ui_addressbookpage.h" #include "addresstablemodel.h" #include "optionsmodel.h" #include "bitcoingui.h" #include "editaddressdialog.h" #include "csvmodelwriter.h" #include "guiutil.h" #ifdef USE_QRCODE #include "qrcodedialog.h" #endif #include <QSortFilterProxyModel> #include <QClipboard> #include <QMessageBox> #include <QMenu> AddressBookPage::AddressBookPage(Mode mode, Tabs tab, QWidget *parent) : QDialog(parent), ui(new Ui::AddressBookPage), model(0), optionsModel(0), mode(mode), tab(tab) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->newAddress->setIcon(QIcon()); ui->copyAddress->setIcon(QIcon()); ui->deleteAddress->setIcon(QIcon()); ui->verifyMessage->setIcon(QIcon()); ui->signMessage->setIcon(QIcon()); ui->exportButton->setIcon(QIcon()); #endif #ifndef USE_QRCODE ui->showQRCode->setVisible(false); #endif switch(mode) { case ForSending: connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept())); ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableView->setFocus(); ui->exportButton->hide(); break; case ForEditing: ui->buttonBox->setVisible(false); break; } switch(tab) { case SendingTab: ui->labelExplanation->setText(tr("These are your KittehCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.")); ui->deleteAddress->setVisible(true); ui->signMessage->setVisible(false); break; case ReceivingTab: ui->labelExplanation->setText(tr("These are your KittehCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.")); ui->deleteAddress->setVisible(false); ui->signMessage->setVisible(true); break; } // Context menu actions QAction *copyAddressAction = new QAction(ui->copyAddress->text(), this); QAction *copyLabelAction = new QAction(tr("Copy &Label"), this); QAction *editAction = new QAction(tr("&Edit"), this); QAction *sendCoinsAction = new QAction(tr("Send &Coins"), this); QAction *showQRCodeAction = new QAction(ui->showQRCode->text(), this); QAction *signMessageAction = new QAction(ui->signMessage->text(), this); QAction *verifyMessageAction = new QAction(ui->verifyMessage->text(), this); deleteAction = new QAction(ui->deleteAddress->text(), this); // Build context menu contextMenu = new QMenu(); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(editAction); if(tab == SendingTab) contextMenu->addAction(deleteAction); contextMenu->addSeparator(); if(tab == SendingTab) contextMenu->addAction(sendCoinsAction); #ifdef USE_QRCODE contextMenu->addAction(showQRCodeAction); #endif if(tab == ReceivingTab) contextMenu->addAction(signMessageAction); else if(tab == SendingTab) contextMenu->addAction(verifyMessageAction); // Connect signals for context menu actions connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyAddress_clicked())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction())); connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction())); connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteAddress_clicked())); connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(onSendCoinsAction())); connect(showQRCodeAction, SIGNAL(triggered()), this, SLOT(on_showQRCode_clicked())); connect(signMessageAction, SIGNAL(triggered()), this, SLOT(on_signMessage_clicked())); connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(on_verifyMessage_clicked())); connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); // Pass through accept action from button box connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept())); } AddressBookPage::~AddressBookPage() { delete ui; } void AddressBookPage::setModel(AddressTableModel *model) { this->model = model; if(!model) return; proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(model); proxyModel->setDynamicSortFilter(true); proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); switch(tab) { case ReceivingTab: // Receive filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Receive); break; case SendingTab: // Send filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Send); break; } ui->tableView->setModel(proxyModel); ui->tableView->sortByColumn(0, Qt::AscendingOrder); // Set column widths #if QT_VERSION < 0x050000 ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #else ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #endif connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged())); // Select row for newly created address connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewAddress(QModelIndex,int,int))); selectionChanged(); } void AddressBookPage::setOptionsModel(OptionsModel *optionsModel) { this->optionsModel = optionsModel; } void AddressBookPage::on_copyAddress_clicked() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address); } void AddressBookPage::onCopyLabelAction() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label); } void AddressBookPage::onEditAction() { if(!ui->tableView->selectionModel()) return; QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows(); if(indexes.isEmpty()) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::EditSendingAddress : EditAddressDialog::EditReceivingAddress); dlg.setModel(model); QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0)); dlg.loadRow(origIndex.row()); dlg.exec(); } void AddressBookPage::on_signMessage_clicked() { QTableView *table = ui->tableView; QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); foreach (QModelIndex index, indexes) { QString address = index.data().toString(); emit signMessage(address); } } void AddressBookPage::on_verifyMessage_clicked() { QTableView *table = ui->tableView; QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); foreach (QModelIndex index, indexes) { QString address = index.data().toString(); emit verifyMessage(address); } } void AddressBookPage::onSendCoinsAction() { QTableView *table = ui->tableView; QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); foreach (QModelIndex index, indexes) { QString address = index.data().toString(); emit sendCoins(address); } } void AddressBookPage::on_newAddress_clicked() { if(!model) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::NewSendingAddress : EditAddressDialog::NewReceivingAddress, this); dlg.setModel(model); if(dlg.exec()) { newAddressToSelect = dlg.getAddress(); } } void AddressBookPage::on_deleteAddress_clicked() { QTableView *table = ui->tableView; if(!table->selectionModel()) return; QModelIndexList indexes = table->selectionModel()->selectedRows(); if(!indexes.isEmpty()) { table->model()->removeRow(indexes.at(0).row()); } } void AddressBookPage::selectionChanged() { // Set button states based on selected tab and selection QTableView *table = ui->tableView; if(!table->selectionModel()) return; if(table->selectionModel()->hasSelection()) { switch(tab) { case SendingTab: // In sending tab, allow deletion of selection ui->deleteAddress->setEnabled(true); ui->deleteAddress->setVisible(true); deleteAction->setEnabled(true); ui->signMessage->setEnabled(false); ui->signMessage->setVisible(false); ui->verifyMessage->setEnabled(true); ui->verifyMessage->setVisible(true); break; case ReceivingTab: // Deleting receiving addresses, however, is not allowed ui->deleteAddress->setEnabled(false); ui->deleteAddress->setVisible(false); deleteAction->setEnabled(false); ui->signMessage->setEnabled(true); ui->signMessage->setVisible(true); ui->verifyMessage->setEnabled(false); ui->verifyMessage->setVisible(false); break; } ui->copyAddress->setEnabled(true); ui->showQRCode->setEnabled(true); } else { ui->deleteAddress->setEnabled(false); ui->showQRCode->setEnabled(false); ui->copyAddress->setEnabled(false); ui->signMessage->setEnabled(false); ui->verifyMessage->setEnabled(false); } } void AddressBookPage::done(int retval) { QTableView *table = ui->tableView; if(!table->selectionModel() || !table->model()) return; // When this is a tab/widget and not a model dialog, ignore "done" if(mode == ForEditing) return; // Figure out which address was selected, and return it QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); foreach (QModelIndex index, indexes) { QVariant address = table->model()->data(index); returnValue = address.toString(); } if(returnValue.isEmpty()) { // If no address entry selected, return rejected retval = Rejected; } QDialog::done(retval); } void AddressBookPage::on_exportButton_clicked() { // CSV is currently the only supported format QString filename = GUIUtil::getSaveFileName( this, tr("Export Address Book Data"), QString(), tr("Comma separated file (*.csv)")); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(proxyModel); writer.addColumn("Label", AddressTableModel::Label, Qt::EditRole); writer.addColumn("Address", AddressTableModel::Address, Qt::EditRole); if(!writer.write()) { QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename), QMessageBox::Abort, QMessageBox::Abort); } } void AddressBookPage::on_showQRCode_clicked() { #ifdef USE_QRCODE QTableView *table = ui->tableView; QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); foreach (QModelIndex index, indexes) { QString address = index.data().toString(); QString label = index.sibling(index.row(), 0).data(Qt::EditRole).toString(); QRCodeDialog *dialog = new QRCodeDialog(address, label, tab == ReceivingTab, this); dialog->setModel(optionsModel); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->show(); } #endif } void AddressBookPage::contextualMenu(const QPoint &point) { QModelIndex index = ui->tableView->indexAt(point); if(index.isValid()) { contextMenu->exec(QCursor::pos()); } } void AddressBookPage::selectNewAddress(const QModelIndex &parent, int begin, int /*end*/) { QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent)); if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect)) { // Select row of newly created address, once ui->tableView->setFocus(); ui->tableView->selectRow(idx.row()); newAddressToSelect.clear(); } }
mit
minime283/draft
app/config/view.php
922
<?php return array( /* |-------------------------------------------------------------------------- | View Storage Paths |-------------------------------------------------------------------------- | | Most templating systems load templates from disk. Here you may specify | an array of paths that should be checked for your views. Of course | the usual Laravel view path has already been registered for you. | */ 'paths' => array(__DIR__.'/../views'), /* |-------------------------------------------------------------------------- | Pagination View |-------------------------------------------------------------------------- | | This view will be used to render the pagination link output, and can | be easily customized here to show any view you like. A clean view | compatible with Twitter's Bootstrap is given to you by default. | */ 'pagination' => 'foundationpagination::slider-center', );
mit
devatwork/Premotion-Mansion
src/Premotion.Mansion.Core/ScriptTags/Stack/SetPropertiesTag.cs
1682
using System; using System.Collections.Generic; using Premotion.Mansion.Core.Collections; using Premotion.Mansion.Core.Scripting.TagScript; namespace Premotion.Mansion.Core.ScriptTags.Stack { /// <summary> /// Opens a template. /// </summary> [ScriptTag(Constants.NamespaceUri, "setProperties")] public class SetPropertiesTag : ScriptTag { /// <summary> /// </summary> /// <param name="context"></param> protected override void DoExecute(IMansionContext context) { // get the attribute var attributes = GetAttributes(context); string dataspaceName; if (!attributes.TryGetAndRemove(context, "dataspaceName", out dataspaceName) || string.IsNullOrEmpty(dataspaceName)) throw new InvalidOperationException("The attribute dataspaceName must be non null and non empty"); bool global; if (!attributes.TryGetAndRemove(context, "global", out global)) global = false; // get the value from the stack IPropertyBag dataspace; if (!context.Stack.TryPeek(dataspaceName, out dataspace)) { dataspace = new PropertyBag(); using (context.Stack.Push(dataspaceName, dataspace, global)) SetProperties(context, dataspace, attributes); } else SetProperties(context, dataspace, attributes); } /// <summary> /// Sets the properties. /// </summary> /// <param name="context"></param> /// <param name="dataspace"></param> /// <param name="attributes"></param> private void SetProperties(IMansionContext context, IPropertyBag dataspace, IEnumerable<KeyValuePair<string, object>> attributes) { // copy the attributes dataspace.Merge(attributes); // execute children ExecuteChildTags(context); } } }
mit
axilleas/gitlabhq
spec/javascripts/environments/environments_app_spec.js
7320
import Vue from 'vue'; import MockAdapter from 'axios-mock-adapter'; import axios from '~/lib/utils/axios_utils'; import environmentsComponent from '~/environments/components/environments_app.vue'; import mountComponent from 'spec/helpers/vue_mount_component_helper'; import { environment, folder } from './mock_data'; describe('Environment', () => { const mockData = { endpoint: 'environments.json', canCreateEnvironment: true, canCreateDeployment: true, canReadEnvironment: true, cssContainerClass: 'container', newEnvironmentPath: 'environments/new', helpPagePath: 'help', }; let EnvironmentsComponent; let component; let mock; beforeEach(() => { mock = new MockAdapter(axios); EnvironmentsComponent = Vue.extend(environmentsComponent); }); afterEach(() => { component.$destroy(); mock.restore(); }); describe('successful request', () => { describe('without environments', () => { beforeEach(done => { mock.onGet(mockData.endpoint).reply(200, { environments: [] }); component = mountComponent(EnvironmentsComponent, mockData); setTimeout(() => { done(); }, 0); }); it('should render the empty state', () => { expect(component.$el.querySelector('.js-new-environment-button').textContent).toContain( 'New environment', ); expect(component.$el.querySelector('.js-blank-state-title').textContent).toContain( "You don't have any environments right now", ); }); }); describe('with paginated environments', () => { beforeEach(done => { mock.onGet(mockData.endpoint).reply( 200, { environments: [environment], stopped_count: 1, available_count: 0, }, { 'X-nExt-pAge': '2', 'x-page': '1', 'X-Per-Page': '1', 'X-Prev-Page': '', 'X-TOTAL': '37', 'X-Total-Pages': '2', }, ); component = mountComponent(EnvironmentsComponent, mockData); setTimeout(() => { done(); }, 0); }); it('should render a table with environments', () => { expect(component.$el.querySelectorAll('table')).not.toBeNull(); expect(component.$el.querySelector('.environment-name').textContent.trim()).toEqual( environment.name, ); }); describe('pagination', () => { it('should render pagination', () => { expect(component.$el.querySelectorAll('.gl-pagination li').length).toEqual(5); }); it('should make an API request when page is clicked', done => { spyOn(component, 'updateContent'); setTimeout(() => { component.$el.querySelector('.gl-pagination li:nth-child(5) a').click(); expect(component.updateContent).toHaveBeenCalledWith({ scope: 'available', page: '2' }); done(); }, 0); }); it('should make an API request when using tabs', done => { setTimeout(() => { spyOn(component, 'updateContent'); component.$el.querySelector('.js-environments-tab-stopped').click(); expect(component.updateContent).toHaveBeenCalledWith({ scope: 'stopped', page: '1' }); done(); }, 0); }); }); }); }); describe('unsuccessfull request', () => { beforeEach(done => { mock.onGet(mockData.endpoint).reply(500, {}); component = mountComponent(EnvironmentsComponent, mockData); setTimeout(() => { done(); }, 0); }); it('should render empty state', () => { expect(component.$el.querySelector('.js-blank-state-title').textContent).toContain( "You don't have any environments right now", ); }); }); describe('expandable folders', () => { beforeEach(() => { mock.onGet(mockData.endpoint).reply( 200, { environments: [folder], stopped_count: 0, available_count: 1, }, { 'X-nExt-pAge': '2', 'x-page': '1', 'X-Per-Page': '1', 'X-Prev-Page': '', 'X-TOTAL': '37', 'X-Total-Pages': '2', }, ); mock.onGet(environment.folder_path).reply(200, { environments: [environment] }); component = mountComponent(EnvironmentsComponent, mockData); }); it('should open a closed folder', done => { setTimeout(() => { component.$el.querySelector('.folder-name').click(); Vue.nextTick(() => { expect(component.$el.querySelector('.folder-icon.ic-chevron-right')).toBe(null); done(); }); }, 0); }); it('should close an opened folder', done => { setTimeout(() => { // open folder component.$el.querySelector('.folder-name').click(); Vue.nextTick(() => { // close folder component.$el.querySelector('.folder-name').click(); Vue.nextTick(() => { expect(component.$el.querySelector('.folder-icon.ic-chevron-down')).toBe(null); done(); }); }); }, 0); }); it('should show children environments and a button to show all environments', done => { setTimeout(() => { // open folder component.$el.querySelector('.folder-name').click(); Vue.nextTick(() => { // wait for next async request setTimeout(() => { expect(component.$el.querySelectorAll('.js-child-row').length).toEqual(1); expect(component.$el.querySelector('.text-center > a.btn').textContent).toContain( 'Show all', ); done(); }); }); }, 0); }); }); describe('methods', () => { beforeEach(() => { mock.onGet(mockData.endpoint).reply( 200, { environments: [], stopped_count: 0, available_count: 1, }, {}, ); component = mountComponent(EnvironmentsComponent, mockData); spyOn(window.history, 'pushState').and.stub(); }); describe('updateContent', () => { it('should set given parameters', done => { component .updateContent({ scope: 'stopped', page: '3' }) .then(() => { expect(component.page).toEqual('3'); expect(component.scope).toEqual('stopped'); expect(component.requestData.scope).toEqual('stopped'); expect(component.requestData.page).toEqual('3'); done(); }) .catch(done.fail); }); }); describe('onChangeTab', () => { it('should set page to 1', () => { spyOn(component, 'updateContent'); component.onChangeTab('stopped'); expect(component.updateContent).toHaveBeenCalledWith({ scope: 'stopped', page: '1' }); }); }); describe('onChangePage', () => { it('should update page and keep scope', () => { spyOn(component, 'updateContent'); component.onChangePage(4); expect(component.updateContent).toHaveBeenCalledWith({ scope: component.scope, page: '4' }); }); }); }); });
mit
abulrim/ember.js
packages/ember/tests/helpers/link_to_test.js
64949
import "ember"; import { objectControllerDeprecation } from "ember-runtime/controllers/object_controller"; import EmberHandlebars from "ember-htmlbars/compat"; var compile = EmberHandlebars.compile; var Router, App, AppView, router, registry, container; var set = Ember.set; function bootApplication() { router = container.lookup('router:main'); Ember.run(App, 'advanceReadiness'); } // IE includes the host name function normalizeUrl(url) { return url.replace(/https?:\/\/[^\/]+/, ''); } function shouldNotBeActive(selector) { checkActive(selector, false); } function shouldBeActive(selector) { checkActive(selector, true); } function checkActive(selector, active) { var classList = Ember.$(selector, '#qunit-fixture')[0].className; equal(classList.indexOf('active') > -1, active, selector + " active should be " + active.toString()); } var updateCount, replaceCount; function sharedSetup() { App = Ember.Application.create({ name: "App", rootElement: '#qunit-fixture' }); App.deferReadiness(); updateCount = replaceCount = 0; App.Router.reopen({ location: Ember.NoneLocation.createWithMixins({ setURL(path) { updateCount++; set(this, 'path', path); }, replaceURL(path) { replaceCount++; set(this, 'path', path); } }) }); Router = App.Router; registry = App.registry; container = App.__container__; } function sharedTeardown() { Ember.run(function() { App.destroy(); }); Ember.TEMPLATES = {}; } QUnit.module("The {{link-to}} helper", { setup() { Ember.run(function() { sharedSetup(); Ember.TEMPLATES.app = compile("{{outlet}}"); Ember.TEMPLATES.index = compile("<h3>Home</h3>{{#link-to 'about' id='about-link'}}About{{/link-to}}{{#link-to 'index' id='self-link'}}Self{{/link-to}}"); Ember.TEMPLATES.about = compile("<h3>About</h3>{{#link-to 'index' id='home-link'}}Home{{/link-to}}{{#link-to 'about' id='self-link'}}Self{{/link-to}}"); Ember.TEMPLATES.item = compile("<h3>Item</h3><p>{{model.name}}</p>{{#link-to 'index' id='home-link'}}Home{{/link-to}}"); AppView = Ember.View.extend({ templateName: 'app' }); registry.register('view:app', AppView); registry.unregister('router:main'); registry.register('router:main', Router); }); }, teardown: sharedTeardown }); QUnit.test("The {{link-to}} helper moves into the named route", function() { Router.map(function(match) { this.route("about"); }); bootApplication(); Ember.run(function() { router.handleURL("/"); }); equal(Ember.$('h3:contains(Home)', '#qunit-fixture').length, 1, "The home template was rendered"); equal(Ember.$('#self-link.active', '#qunit-fixture').length, 1, "The self-link was rendered with active class"); equal(Ember.$('#about-link:not(.active)', '#qunit-fixture').length, 1, "The other link was rendered without active class"); Ember.run(function() { Ember.$('#about-link', '#qunit-fixture').click(); }); equal(Ember.$('h3:contains(About)', '#qunit-fixture').length, 1, "The about template was rendered"); equal(Ember.$('#self-link.active', '#qunit-fixture').length, 1, "The self-link was rendered with active class"); equal(Ember.$('#home-link:not(.active)', '#qunit-fixture').length, 1, "The other link was rendered without active class"); }); QUnit.test("The {{link-to}} helper supports URL replacement", function() { Ember.TEMPLATES.index = compile("<h3>Home</h3>{{#link-to 'about' id='about-link' replace=true}}About{{/link-to}}"); Router.map(function() { this.route("about"); }); bootApplication(); Ember.run(function() { router.handleURL("/"); }); equal(updateCount, 0, 'precond: setURL has not been called'); equal(replaceCount, 0, 'precond: replaceURL has not been called'); Ember.run(function() { Ember.$('#about-link', '#qunit-fixture').click(); }); equal(updateCount, 0, 'setURL should not be called'); equal(replaceCount, 1, 'replaceURL should be called once'); }); QUnit.test("the {{link-to}} helper doesn't add an href when the tagName isn't 'a'", function() { Ember.TEMPLATES.index = compile("{{#link-to 'about' id='about-link' tagName='div'}}About{{/link-to}}"); Router.map(function() { this.route("about"); }); bootApplication(); Ember.run(function() { router.handleURL("/"); }); equal(Ember.$('#about-link').attr('href'), undefined, "there is no href attribute"); }); QUnit.test("the {{link-to}} applies a 'disabled' class when disabled", function () { Ember.TEMPLATES.index = compile('{{#link-to "about" id="about-link" disabledWhen="shouldDisable"}}About{{/link-to}}'); App.IndexController = Ember.Controller.extend({ shouldDisable: true }); Router.map(function() { this.route("about"); }); bootApplication(); Ember.run(function() { router.handleURL("/"); }); equal(Ember.$('#about-link.disabled', '#qunit-fixture').length, 1, "The link is disabled when its disabledWhen is true"); }); QUnit.test("the {{link-to}} doesn't apply a 'disabled' class if disabledWhen is not provided", function () { Ember.TEMPLATES.index = compile('{{#link-to "about" id="about-link"}}About{{/link-to}}'); Router.map(function() { this.route("about"); }); bootApplication(); Ember.run(function() { router.handleURL("/"); }); ok(!Ember.$('#about-link', '#qunit-fixture').hasClass("disabled"), "The link is not disabled if disabledWhen not provided"); }); QUnit.test("the {{link-to}} helper supports a custom disabledClass", function () { Ember.TEMPLATES.index = compile('{{#link-to "about" id="about-link" disabledWhen="shouldDisable" disabledClass="do-not-want"}}About{{/link-to}}'); App.IndexController = Ember.Controller.extend({ shouldDisable: true }); Router.map(function() { this.route("about"); }); bootApplication(); Ember.run(function() { router.handleURL("/"); }); equal(Ember.$('#about-link.do-not-want', '#qunit-fixture').length, 1, "The link can apply a custom disabled class"); }); QUnit.test("the {{link-to}} helper does not respond to clicks when disabled", function () { Ember.TEMPLATES.index = compile('{{#link-to "about" id="about-link" disabledWhen="shouldDisable"}}About{{/link-to}}'); App.IndexController = Ember.Controller.extend({ shouldDisable: true }); Router.map(function() { this.route("about"); }); bootApplication(); Ember.run(function() { router.handleURL("/"); }); Ember.run(function() { Ember.$('#about-link', '#qunit-fixture').click(); }); equal(Ember.$('h3:contains(About)', '#qunit-fixture').length, 0, "Transitioning did not occur"); }); QUnit.test("The {{link-to}} helper supports a custom activeClass", function() { Ember.TEMPLATES.index = compile("<h3>Home</h3>{{#link-to 'about' id='about-link'}}About{{/link-to}}{{#link-to 'index' id='self-link' activeClass='zomg-active'}}Self{{/link-to}}"); Router.map(function() { this.route("about"); }); bootApplication(); Ember.run(function() { router.handleURL("/"); }); equal(Ember.$('h3:contains(Home)', '#qunit-fixture').length, 1, "The home template was rendered"); equal(Ember.$('#self-link.zomg-active', '#qunit-fixture').length, 1, "The self-link was rendered with active class"); equal(Ember.$('#about-link:not(.active)', '#qunit-fixture').length, 1, "The other link was rendered without active class"); }); QUnit.test("The {{link-to}} helper supports leaving off .index for nested routes", function() { Router.map(function() { this.resource("about", function() { this.route("item"); }); }); Ember.TEMPLATES.about = compile("<h1>About</h1>{{outlet}}"); Ember.TEMPLATES['about/index'] = compile("<div id='index'>Index</div>"); Ember.TEMPLATES['about/item'] = compile("<div id='item'>{{#link-to 'about'}}About{{/link-to}}</div>"); bootApplication(); Ember.run(router, 'handleURL', '/about/item'); equal(normalizeUrl(Ember.$('#item a', '#qunit-fixture').attr('href')), '/about'); }); QUnit.test("The {{link-to}} helper supports currentWhen (DEPRECATED)", function() { expectDeprecation('Using currentWhen with {{link-to}} is deprecated in favor of `current-when`.'); Router.map(function(match) { this.resource("index", { path: "/" }, function() { this.route("about"); }); this.route("item"); }); Ember.TEMPLATES.index = compile("<h3>Home</h3>{{outlet}}"); Ember.TEMPLATES['index/about'] = compile("{{#link-to 'item' id='other-link' currentWhen='index'}}ITEM{{/link-to}}"); bootApplication(); Ember.run(function() { router.handleURL("/about"); }); equal(Ember.$('#other-link.active', '#qunit-fixture').length, 1, "The link is active since current-when is a parent route"); }); QUnit.test("The {{link-to}} helper supports custom, nested, current-when", function() { Router.map(function(match) { this.resource("index", { path: "/" }, function() { this.route("about"); }); this.route("item"); }); Ember.TEMPLATES.index = compile("<h3>Home</h3>{{outlet}}"); Ember.TEMPLATES['index/about'] = compile("{{#link-to 'item' id='other-link' current-when='index'}}ITEM{{/link-to}}"); bootApplication(); Ember.run(function() { router.handleURL("/about"); }); equal(Ember.$('#other-link.active', '#qunit-fixture').length, 1, "The link is active since current-when is a parent route"); }); QUnit.test("The {{link-to}} helper does not disregard current-when when it is given explicitly for a resource", function() { Router.map(function(match) { this.resource("index", { path: "/" }, function() { this.route("about"); }); this.resource("items", function() { this.route('item'); }); }); Ember.TEMPLATES.index = compile("<h3>Home</h3>{{outlet}}"); Ember.TEMPLATES['index/about'] = compile("{{#link-to 'items' id='other-link' current-when='index'}}ITEM{{/link-to}}"); bootApplication(); Ember.run(function() { router.handleURL("/about"); }); equal(Ember.$('#other-link.active', '#qunit-fixture').length, 1, "The link is active when current-when is given for explicitly for a resource"); }); QUnit.test("The {{link-to}} helper supports multiple current-when routes", function() { Router.map(function(match) { this.resource("index", { path: "/" }, function() { this.route("about"); }); this.route("item"); this.route("foo"); }); Ember.TEMPLATES.index = compile("<h3>Home</h3>{{outlet}}"); Ember.TEMPLATES['index/about'] = compile("{{#link-to 'item' id='link1' current-when='item index'}}ITEM{{/link-to}}"); Ember.TEMPLATES['item'] = compile("{{#link-to 'item' id='link2' current-when='item index'}}ITEM{{/link-to}}"); Ember.TEMPLATES['foo'] = compile("{{#link-to 'item' id='link3' current-when='item index'}}ITEM{{/link-to}}"); bootApplication(); Ember.run(function() { router.handleURL("/about"); }); equal(Ember.$('#link1.active', '#qunit-fixture').length, 1, "The link is active since current-when contains the parent route"); Ember.run(function() { router.handleURL("/item"); }); equal(Ember.$('#link2.active', '#qunit-fixture').length, 1, "The link is active since you are on the active route"); Ember.run(function() { router.handleURL("/foo"); }); equal(Ember.$('#link3.active', '#qunit-fixture').length, 0, "The link is not active since current-when does not contain the active route"); }); QUnit.test("The {{link-to}} helper defaults to bubbling", function() { Ember.TEMPLATES.about = compile("<div {{action 'hide'}}>{{#link-to 'about.contact' id='about-contact'}}About{{/link-to}}</div>{{outlet}}"); Ember.TEMPLATES['about/contact'] = compile("<h1 id='contact'>Contact</h1>"); Router.map(function() { this.resource("about", function() { this.route("contact"); }); }); var hidden = 0; App.AboutRoute = Ember.Route.extend({ actions: { hide() { hidden++; } } }); bootApplication(); Ember.run(function() { router.handleURL("/about"); }); Ember.run(function() { Ember.$('#about-contact', '#qunit-fixture').click(); }); equal(Ember.$("#contact", "#qunit-fixture").text(), "Contact", "precond - the link worked"); equal(hidden, 1, "The link bubbles"); }); QUnit.test("The {{link-to}} helper supports bubbles=false", function() { Ember.TEMPLATES.about = compile("<div {{action 'hide'}}>{{#link-to 'about.contact' id='about-contact' bubbles=false}}About{{/link-to}}</div>{{outlet}}"); Ember.TEMPLATES['about/contact'] = compile("<h1 id='contact'>Contact</h1>"); Router.map(function() { this.resource("about", function() { this.route("contact"); }); }); var hidden = 0; App.AboutRoute = Ember.Route.extend({ actions: { hide() { hidden++; } } }); bootApplication(); Ember.run(function() { router.handleURL("/about"); }); Ember.run(function() { Ember.$('#about-contact', '#qunit-fixture').click(); }); equal(Ember.$("#contact", "#qunit-fixture").text(), "Contact", "precond - the link worked"); equal(hidden, 0, "The link didn't bubble"); }); QUnit.test("The {{link-to}} helper moves into the named route with context", function() { Router.map(function(match) { this.route("about"); this.resource("item", { path: "/item/:id" }); }); Ember.TEMPLATES.about = compile("<h3>List</h3><ul>{{#each person in model}}<li>{{#link-to 'item' person}}{{person.name}}{{/link-to}}</li>{{/each}}</ul>{{#link-to 'index' id='home-link'}}Home{{/link-to}}"); App.AboutRoute = Ember.Route.extend({ model() { return Ember.A([ { id: "yehuda", name: "Yehuda Katz" }, { id: "tom", name: "Tom Dale" }, { id: "erik", name: "Erik Brynroflsson" } ]); } }); App.ItemRoute = Ember.Route.extend({ serialize(object) { return { id: object.id }; } }); bootApplication(); Ember.run(function() { router.handleURL("/about"); }); equal(Ember.$('h3:contains(List)', '#qunit-fixture').length, 1, "The home template was rendered"); equal(normalizeUrl(Ember.$('#home-link').attr('href')), '/', "The home link points back at /"); Ember.run(function() { Ember.$('li a:contains(Yehuda)', '#qunit-fixture').click(); }); equal(Ember.$('h3:contains(Item)', '#qunit-fixture').length, 1, "The item template was rendered"); equal(Ember.$('p', '#qunit-fixture').text(), "Yehuda Katz", "The name is correct"); Ember.run(function() { Ember.$('#home-link').click(); }); Ember.run(function() { Ember.$('#about-link').click(); }); equal(normalizeUrl(Ember.$('li a:contains(Yehuda)').attr('href')), "/item/yehuda"); equal(normalizeUrl(Ember.$('li a:contains(Tom)').attr('href')), "/item/tom"); equal(normalizeUrl(Ember.$('li a:contains(Erik)').attr('href')), "/item/erik"); Ember.run(function() { Ember.$('li a:contains(Erik)', '#qunit-fixture').click(); }); equal(Ember.$('h3:contains(Item)', '#qunit-fixture').length, 1, "The item template was rendered"); equal(Ember.$('p', '#qunit-fixture').text(), "Erik Brynroflsson", "The name is correct"); }); QUnit.test("The {{link-to}} helper binds some anchor html tag common attributes", function() { Ember.TEMPLATES.index = compile("<h3>Home</h3>{{#link-to 'index' id='self-link' title='title-attr' rel='rel-attr' tabindex='-1'}}Self{{/link-to}}"); bootApplication(); Ember.run(function() { router.handleURL("/"); }); var link = Ember.$('#self-link', '#qunit-fixture'); equal(link.attr('title'), 'title-attr', "The self-link contains title attribute"); equal(link.attr('rel'), 'rel-attr', "The self-link contains rel attribute"); equal(link.attr('tabindex'), '-1', "The self-link contains tabindex attribute"); }); QUnit.test("The {{link-to}} helper supports `target` attribute", function() { Ember.TEMPLATES.index = compile("<h3>Home</h3>{{#link-to 'index' id='self-link' target='_blank'}}Self{{/link-to}}"); bootApplication(); Ember.run(function() { router.handleURL("/"); }); var link = Ember.$('#self-link', '#qunit-fixture'); equal(link.attr('target'), '_blank', "The self-link contains `target` attribute"); }); QUnit.test("The {{link-to}} helper does not call preventDefault if `target` attribute is provided", function() { Ember.TEMPLATES.index = compile("<h3>Home</h3>{{#link-to 'index' id='self-link' target='_blank'}}Self{{/link-to}}"); bootApplication(); Ember.run(function() { router.handleURL("/"); }); var event = Ember.$.Event("click"); Ember.$('#self-link', '#qunit-fixture').trigger(event); equal(event.isDefaultPrevented(), false, "should not preventDefault when target attribute is specified"); }); QUnit.test("The {{link-to}} helper should preventDefault when `target = _self`", function() { Ember.TEMPLATES.index = compile("<h3>Home</h3>{{#link-to 'index' id='self-link' target='_self'}}Self{{/link-to}}"); bootApplication(); Ember.run(function() { router.handleURL("/"); }); var event = Ember.$.Event("click"); Ember.$('#self-link', '#qunit-fixture').trigger(event); equal(event.isDefaultPrevented(), true, "should preventDefault when target attribute is `_self`"); }); QUnit.test("The {{link-to}} helper should not transition if target is not equal to _self or empty", function() { Ember.TEMPLATES.index = compile("{{#link-to 'about' id='about-link' replace=true target='_blank'}}About{{/link-to}}"); Router.map(function() { this.route("about"); }); bootApplication(); Ember.run(function() { router.handleURL("/"); }); Ember.run(function() { Ember.$('#about-link', '#qunit-fixture').click(); }); notEqual(container.lookup('controller:application').get('currentRouteName'), 'about', 'link-to should not transition if target is not equal to _self or empty'); }); QUnit.test("The {{link-to}} helper accepts string/numeric arguments", function() { Router.map(function() { this.route('filter', { path: '/filters/:filter' }); this.route('post', { path: '/post/:post_id' }); this.route('repo', { path: '/repo/:owner/:name' }); }); App.FilterController = Ember.Controller.extend({ filter: "unpopular", repo: Ember.Object.create({ owner: 'ember', name: 'ember.js' }), post_id: 123 }); Ember.TEMPLATES.filter = compile('<p>{{filter}}</p>{{#link-to "filter" "unpopular" id="link"}}Unpopular{{/link-to}}{{#link-to "filter" filter id="path-link"}}Unpopular{{/link-to}}{{#link-to "post" post_id id="post-path-link"}}Post{{/link-to}}{{#link-to "post" 123 id="post-number-link"}}Post{{/link-to}}{{#link-to "repo" repo id="repo-object-link"}}Repo{{/link-to}}'); Ember.TEMPLATES.index = compile(' '); bootApplication(); Ember.run(function() { router.handleURL("/filters/popular"); }); equal(normalizeUrl(Ember.$('#link', '#qunit-fixture').attr('href')), "/filters/unpopular"); equal(normalizeUrl(Ember.$('#path-link', '#qunit-fixture').attr('href')), "/filters/unpopular"); equal(normalizeUrl(Ember.$('#post-path-link', '#qunit-fixture').attr('href')), "/post/123"); equal(normalizeUrl(Ember.$('#post-number-link', '#qunit-fixture').attr('href')), "/post/123"); equal(normalizeUrl(Ember.$('#repo-object-link', '#qunit-fixture').attr('href')), "/repo/ember/ember.js"); }); QUnit.test("Issue 4201 - Shorthand for route.index shouldn't throw errors about context arguments", function() { expect(2); Router.map(function() { this.resource('lobby', function() { this.route('index', { path: ':lobby_id' }); this.route('list'); }); }); App.LobbyIndexRoute = Ember.Route.extend({ model(params) { equal(params.lobby_id, 'foobar'); return params.lobby_id; } }); Ember.TEMPLATES['lobby/index'] = compile("{{#link-to 'lobby' 'foobar' id='lobby-link'}}Lobby{{/link-to}}"); Ember.TEMPLATES.index = compile(""); Ember.TEMPLATES['lobby/list'] = compile("{{#link-to 'lobby' 'foobar' id='lobby-link'}}Lobby{{/link-to}}"); bootApplication(); Ember.run(router, 'handleURL', '/lobby/list'); Ember.run(Ember.$('#lobby-link'), 'click'); shouldBeActive('#lobby-link'); }); QUnit.test("The {{link-to}} helper unwraps controllers", function() { if (Ember.FEATURES.isEnabled('ember-routing-transitioning-classes')) { expect(5); } else { expect(6); } Router.map(function() { this.route('filter', { path: '/filters/:filter' }); }); var indexObject = { filter: 'popular' }; App.FilterRoute = Ember.Route.extend({ model(params) { return indexObject; }, serialize(passedObject) { equal(passedObject, indexObject, "The unwrapped object is passed"); return { filter: 'popular' }; } }); App.IndexRoute = Ember.Route.extend({ model() { return indexObject; } }); Ember.TEMPLATES.filter = compile('<p>{{model.filter}}</p>'); Ember.TEMPLATES.index = compile('{{#link-to "filter" this id="link"}}Filter{{/link-to}}'); expectDeprecation(function() { bootApplication(); }, /Providing `{{link-to}}` with a param that is wrapped in a controller is deprecated./); Ember.run(function() { router.handleURL("/"); }); Ember.$('#link', '#qunit-fixture').trigger('click'); }); QUnit.test("The {{link-to}} helper doesn't change view context", function() { App.IndexView = Ember.View.extend({ elementId: 'index', name: 'test', isTrue: true }); Ember.TEMPLATES.index = compile("{{view.name}}-{{#link-to 'index' id='self-link'}}Link: {{view.name}}-{{#if view.isTrue}}{{view.name}}{{/if}}{{/link-to}}"); bootApplication(); Ember.run(function() { router.handleURL("/"); }); equal(Ember.$('#index', '#qunit-fixture').text(), 'test-Link: test-test', "accesses correct view"); }); QUnit.test("Quoteless route param performs property lookup", function() { Ember.TEMPLATES.index = compile("{{#link-to 'index' id='string-link'}}string{{/link-to}}{{#link-to foo id='path-link'}}path{{/link-to}}{{#link-to view.foo id='view-link'}}{{view.foo}}{{/link-to}}"); function assertEquality(href) { equal(normalizeUrl(Ember.$('#string-link', '#qunit-fixture').attr('href')), '/'); equal(normalizeUrl(Ember.$('#path-link', '#qunit-fixture').attr('href')), href); equal(normalizeUrl(Ember.$('#view-link', '#qunit-fixture').attr('href')), href); } App.IndexView = Ember.View.extend({ foo: 'index', elementId: 'index-view' }); App.IndexController = Ember.Controller.extend({ foo: 'index' }); App.Router.map(function() { this.route('about'); }); bootApplication(); Ember.run(router, 'handleURL', '/'); assertEquality('/'); var controller = container.lookup('controller:index'); var view = Ember.View.views['index-view']; Ember.run(function() { controller.set('foo', 'about'); view.set('foo', 'about'); }); assertEquality('/about'); }); QUnit.test("link-to with null/undefined dynamic parameters are put in a loading state", function() { expect(19); var oldWarn = Ember.Logger.warn; var warnCalled = false; Ember.Logger.warn = function() { warnCalled = true; }; Ember.TEMPLATES.index = compile("{{#link-to destinationRoute routeContext loadingClass='i-am-loading' id='context-link'}}string{{/link-to}}{{#link-to secondRoute loadingClass='i-am-loading' id='static-link'}}string{{/link-to}}"); var thing = Ember.Object.create({ id: 123 }); App.IndexController = Ember.Controller.extend({ destinationRoute: null, routeContext: null }); App.AboutRoute = Ember.Route.extend({ activate() { ok(true, "About was entered"); } }); App.Router.map(function() { this.route('thing', { path: '/thing/:thing_id' }); this.route('about'); }); bootApplication(); Ember.run(router, 'handleURL', '/'); function assertLinkStatus($link, url) { if (url) { equal(normalizeUrl($link.attr('href')), url, "loaded link-to has expected href"); ok(!$link.hasClass('i-am-loading'), "loaded linkView has no loadingClass"); } else { equal(normalizeUrl($link.attr('href')), '#', "unloaded link-to has href='#'"); ok($link.hasClass('i-am-loading'), "loading linkView has loadingClass"); } } var $contextLink = Ember.$('#context-link', '#qunit-fixture'); var $staticLink = Ember.$('#static-link', '#qunit-fixture'); var controller = container.lookup('controller:index'); assertLinkStatus($contextLink); assertLinkStatus($staticLink); Ember.run(function() { warnCalled = false; $contextLink.click(); ok(warnCalled, "Logger.warn was called from clicking loading link"); }); // Set the destinationRoute (context is still null). Ember.run(controller, 'set', 'destinationRoute', 'thing'); assertLinkStatus($contextLink); // Set the routeContext to an id Ember.run(controller, 'set', 'routeContext', '456'); assertLinkStatus($contextLink, '/thing/456'); // Test that 0 isn't interpreted as falsy. Ember.run(controller, 'set', 'routeContext', 0); assertLinkStatus($contextLink, '/thing/0'); // Set the routeContext to an object Ember.run(controller, 'set', 'routeContext', thing); assertLinkStatus($contextLink, '/thing/123'); // Set the destinationRoute back to null. Ember.run(controller, 'set', 'destinationRoute', null); assertLinkStatus($contextLink); Ember.run(function() { warnCalled = false; $staticLink.click(); ok(warnCalled, "Logger.warn was called from clicking loading link"); }); Ember.run(controller, 'set', 'secondRoute', 'about'); assertLinkStatus($staticLink, '/about'); // Click the now-active link Ember.run($staticLink, 'click'); Ember.Logger.warn = oldWarn; }); QUnit.test("The {{link-to}} helper refreshes href element when one of params changes", function() { Router.map(function() { this.route('post', { path: '/posts/:post_id' }); }); var post = Ember.Object.create({ id: '1' }); var secondPost = Ember.Object.create({ id: '2' }); Ember.TEMPLATES.index = compile('{{#link-to "post" post id="post"}}post{{/link-to}}'); App.IndexController = Ember.Controller.extend(); var indexController = container.lookup('controller:index'); Ember.run(function() { indexController.set('post', post); }); bootApplication(); Ember.run(function() { router.handleURL("/"); }); equal(normalizeUrl(Ember.$('#post', '#qunit-fixture').attr('href')), '/posts/1', 'precond - Link has rendered href attr properly'); Ember.run(function() { indexController.set('post', secondPost); }); equal(Ember.$('#post', '#qunit-fixture').attr('href'), '/posts/2', 'href attr was updated after one of the params had been changed'); Ember.run(function() { indexController.set('post', null); }); equal(Ember.$('#post', '#qunit-fixture').attr('href'), '#', 'href attr becomes # when one of the arguments in nullified'); }); QUnit.test("The {{link-to}} helper's bound parameter functionality works as expected in conjunction with an ObjectProxy/Controller", function() { expectDeprecation(objectControllerDeprecation); Router.map(function() { this.route('post', { path: '/posts/:post_id' }); }); var post = Ember.Object.create({ id: '1' }); var secondPost = Ember.Object.create({ id: '2' }); Ember.TEMPLATES = { index: compile(' '), post: compile('{{#link-to "post" this id="self-link"}}selflink{{/link-to}}') }; App.PostController = Ember.ObjectController.extend(); var postController = container.lookup('controller:post'); bootApplication(); Ember.run(router, 'transitionTo', 'post', post); var $link = Ember.$('#self-link', '#qunit-fixture'); equal(normalizeUrl($link.attr('href')), '/posts/1', 'self link renders post 1'); Ember.run(postController, 'set', 'model', secondPost); equal(normalizeUrl($link.attr('href')), '/posts/2', 'self link updated to post 2'); }); QUnit.test("{{linkTo}} is aliased", function() { Ember.TEMPLATES.index = compile("<h3>Home</h3>{{#linkTo 'about' id='about-link' replace=true}}About{{/linkTo}}"); Router.map(function() { this.route("about"); }); expectDeprecation(function() { bootApplication(); }, "The 'linkTo' view helper is deprecated in favor of 'link-to'"); Ember.run(function() { router.handleURL("/"); }); Ember.run(function() { Ember.$('#about-link', '#qunit-fixture').click(); }); equal(container.lookup('controller:application').get('currentRouteName'), 'about', 'linkTo worked properly'); }); QUnit.test("The {{link-to}} helper is active when a resource is active", function() { Router.map(function() { this.resource("about", function() { this.route("item"); }); }); Ember.TEMPLATES.about = compile("<div id='about'>{{#link-to 'about' id='about-link'}}About{{/link-to}} {{#link-to 'about.item' id='item-link'}}Item{{/link-to}} {{outlet}}</div>"); Ember.TEMPLATES['about/item'] = compile(" "); Ember.TEMPLATES['about/index'] = compile(" "); bootApplication(); Ember.run(router, 'handleURL', '/about'); equal(Ember.$('#about-link.active', '#qunit-fixture').length, 1, "The about resource link is active"); equal(Ember.$('#item-link.active', '#qunit-fixture').length, 0, "The item route link is inactive"); Ember.run(router, 'handleURL', '/about/item'); equal(Ember.$('#about-link.active', '#qunit-fixture').length, 1, "The about resource link is active"); equal(Ember.$('#item-link.active', '#qunit-fixture').length, 1, "The item route link is active"); }); QUnit.test("The {{link-to}} helper works in an #each'd array of string route names", function() { Router.map(function() { this.route('foo'); this.route('bar'); this.route('rar'); }); App.IndexController = Ember.Controller.extend({ routeNames: Ember.A(['foo', 'bar', 'rar']), route1: 'bar', route2: 'foo' }); Ember.TEMPLATES = { index: compile('{{#each routeName in routeNames}}{{#link-to routeName}}{{routeName}}{{/link-to}}{{/each}}{{#each routeNames}}{{#link-to this}}{{this}}{{/link-to}}{{/each}}{{#link-to route1}}a{{/link-to}}{{#link-to route2}}b{{/link-to}}') }; expectDeprecation(function() { bootApplication(); }, 'Using the context switching form of {{each}} is deprecated. Please use the block param form (`{{#each bar as |foo|}}`) instead.'); function linksEqual($links, expected) { equal($links.length, expected.length, "Has correct number of links"); var idx; for (idx = 0; idx < $links.length; idx++) { var href = Ember.$($links[idx]).attr('href'); // Old IE includes the whole hostname as well equal(href.slice(-expected[idx].length), expected[idx], "Expected link to be '"+expected[idx]+"', but was '"+href+"'"); } } linksEqual(Ember.$('a', '#qunit-fixture'), ["/foo", "/bar", "/rar", "/foo", "/bar", "/rar", "/bar", "/foo"]); var indexController = container.lookup('controller:index'); Ember.run(indexController, 'set', 'route1', 'rar'); linksEqual(Ember.$('a', '#qunit-fixture'), ["/foo", "/bar", "/rar", "/foo", "/bar", "/rar", "/rar", "/foo"]); Ember.run(indexController.routeNames, 'shiftObject'); linksEqual(Ember.$('a', '#qunit-fixture'), ["/bar", "/rar", "/bar", "/rar", "/rar", "/foo"]); }); QUnit.test("The non-block form {{link-to}} helper moves into the named route", function() { expect(3); Router.map(function(match) { this.route("contact"); }); Ember.TEMPLATES.index = compile("<h3>Home</h3>{{link-to 'Contact us' 'contact' id='contact-link'}}{{#link-to 'index' id='self-link'}}Self{{/link-to}}"); Ember.TEMPLATES.contact = compile("<h3>Contact</h3>{{link-to 'Home' 'index' id='home-link'}}{{link-to 'Self' 'contact' id='self-link'}}"); bootApplication(); Ember.run(function() { Ember.$('#contact-link', '#qunit-fixture').click(); }); equal(Ember.$('h3:contains(Contact)', '#qunit-fixture').length, 1, "The contact template was rendered"); equal(Ember.$('#self-link.active', '#qunit-fixture').length, 1, "The self-link was rendered with active class"); equal(Ember.$('#home-link:not(.active)', '#qunit-fixture').length, 1, "The other link was rendered without active class"); }); QUnit.test("The non-block form {{link-to}} helper updates the link text when it is a binding", function() { expect(8); Router.map(function(match) { this.route("contact"); }); App.IndexController = Ember.Controller.extend({ contactName: 'Jane' }); Ember.TEMPLATES.index = compile("<h3>Home</h3>{{link-to contactName 'contact' id='contact-link'}}{{#link-to 'index' id='self-link'}}Self{{/link-to}}"); Ember.TEMPLATES.contact = compile("<h3>Contact</h3>{{link-to 'Home' 'index' id='home-link'}}{{link-to 'Self' 'contact' id='self-link'}}"); bootApplication(); Ember.run(function() { router.handleURL("/"); }); var controller = container.lookup('controller:index'); equal(Ember.$('#contact-link:contains(Jane)', '#qunit-fixture').length, 1, "The link title is correctly resolved"); Ember.run(function() { controller.set('contactName', 'Joe'); }); equal(Ember.$('#contact-link:contains(Joe)', '#qunit-fixture').length, 1, "The link title is correctly updated when the bound property changes"); Ember.run(function() { controller.set('contactName', 'Robert'); }); equal(Ember.$('#contact-link:contains(Robert)', '#qunit-fixture').length, 1, "The link title is correctly updated when the bound property changes a second time"); Ember.run(function() { Ember.$('#contact-link', '#qunit-fixture').click(); }); equal(Ember.$('h3:contains(Contact)', '#qunit-fixture').length, 1, "The contact template was rendered"); equal(Ember.$('#self-link.active', '#qunit-fixture').length, 1, "The self-link was rendered with active class"); equal(Ember.$('#home-link:not(.active)', '#qunit-fixture').length, 1, "The other link was rendered without active class"); Ember.run(function() { Ember.$('#home-link', '#qunit-fixture').click(); }); equal(Ember.$('h3:contains(Home)', '#qunit-fixture').length, 1, "The index template was rendered"); equal(Ember.$('#contact-link:contains(Robert)', '#qunit-fixture').length, 1, "The link title is correctly updated when the route changes"); }); QUnit.test("The non-block form {{link-to}} helper moves into the named route with context", function() { expect(5); Router.map(function(match) { this.route("item", { path: "/item/:id" }); }); App.IndexRoute = Ember.Route.extend({ model() { return Ember.A([ { id: "yehuda", name: "Yehuda Katz" }, { id: "tom", name: "Tom Dale" }, { id: "erik", name: "Erik Brynroflsson" } ]); } }); App.ItemRoute = Ember.Route.extend({ serialize(object) { return { id: object.id }; } }); Ember.TEMPLATES.index = compile("<h3>Home</h3><ul>{{#each person in controller}}<li>{{link-to person.name 'item' person}}</li>{{/each}}</ul>"); Ember.TEMPLATES.item = compile("<h3>Item</h3><p>{{model.name}}</p>{{#link-to 'index' id='home-link'}}Home{{/link-to}}"); bootApplication(); Ember.run(function() { Ember.$('li a:contains(Yehuda)', '#qunit-fixture').click(); }); equal(Ember.$('h3:contains(Item)', '#qunit-fixture').length, 1, "The item template was rendered"); equal(Ember.$('p', '#qunit-fixture').text(), "Yehuda Katz", "The name is correct"); Ember.run(function() { Ember.$('#home-link').click(); }); equal(normalizeUrl(Ember.$('li a:contains(Yehuda)').attr('href')), "/item/yehuda"); equal(normalizeUrl(Ember.$('li a:contains(Tom)').attr('href')), "/item/tom"); equal(normalizeUrl(Ember.$('li a:contains(Erik)').attr('href')), "/item/erik"); }); QUnit.test("The non-block form {{link-to}} performs property lookup", function() { Ember.TEMPLATES.index = compile("{{link-to 'string' 'index' id='string-link'}}{{link-to path foo id='path-link'}}{{link-to view.foo view.foo id='view-link'}}"); function assertEquality(href) { equal(normalizeUrl(Ember.$('#string-link', '#qunit-fixture').attr('href')), '/'); equal(normalizeUrl(Ember.$('#path-link', '#qunit-fixture').attr('href')), href); equal(normalizeUrl(Ember.$('#view-link', '#qunit-fixture').attr('href')), href); } App.IndexView = Ember.View.extend({ foo: 'index', elementId: 'index-view' }); App.IndexController = Ember.Controller.extend({ foo: 'index' }); App.Router.map(function() { this.route('about'); }); bootApplication(); Ember.run(router, 'handleURL', '/'); assertEquality('/'); var controller = container.lookup('controller:index'); var view = Ember.View.views['index-view']; Ember.run(function() { controller.set('foo', 'about'); view.set('foo', 'about'); }); assertEquality('/about'); }); QUnit.test("The non-block form {{link-to}} protects against XSS", function() { Ember.TEMPLATES.application = compile("{{link-to display 'index' id='link'}}"); App.ApplicationController = Ember.Controller.extend({ display: 'blahzorz' }); bootApplication(); Ember.run(router, 'handleURL', '/'); var controller = container.lookup('controller:application'); equal(Ember.$('#link', '#qunit-fixture').text(), 'blahzorz'); Ember.run(function() { controller.set('display', '<b>BLAMMO</b>'); }); equal(Ember.$('#link', '#qunit-fixture').text(), '<b>BLAMMO</b>'); equal(Ember.$('b', '#qunit-fixture').length, 0); }); QUnit.test("the {{link-to}} helper calls preventDefault", function() { Router.map(function() { this.route("about"); }); bootApplication(); Ember.run(router, 'handleURL', '/'); var event = Ember.$.Event("click"); Ember.$('#about-link', '#qunit-fixture').trigger(event); equal(event.isDefaultPrevented(), true, "should preventDefault"); }); QUnit.test("the {{link-to}} helper does not call preventDefault if `preventDefault=false` is passed as an option", function() { Ember.TEMPLATES.index = compile("{{#link-to 'about' id='about-link' preventDefault=false}}About{{/link-to}}"); Router.map(function() { this.route("about"); }); bootApplication(); Ember.run(router, 'handleURL', '/'); var event = Ember.$.Event("click"); Ember.$('#about-link', '#qunit-fixture').trigger(event); equal(event.isDefaultPrevented(), false, "should not preventDefault"); }); QUnit.test("the {{link-to}} helper does not throw an error if its route has exited", function() { expect(0); Ember.TEMPLATES.application = compile("{{#link-to 'index' id='home-link'}}Home{{/link-to}}{{#link-to 'post' defaultPost id='default-post-link'}}Default Post{{/link-to}}{{#if currentPost}}{{#link-to 'post' id='post-link'}}Post{{/link-to}}{{/if}}"); App.ApplicationController = Ember.Controller.extend({ needs: ['post'], currentPost: Ember.computed.alias('controllers.post.model') }); App.PostController = Ember.Controller.extend({ model: { id: 1 } }); Router.map(function() { this.route("post", { path: 'post/:post_id' }); }); bootApplication(); Ember.run(router, 'handleURL', '/'); Ember.run(function() { Ember.$('#default-post-link', '#qunit-fixture').click(); }); Ember.run(function() { Ember.$('#home-link', '#qunit-fixture').click(); }); }); QUnit.test("{{link-to}} active property respects changing parent route context", function() { Ember.TEMPLATES.application = compile( "{{link-to 'OMG' 'things' 'omg' id='omg-link'}} " + "{{link-to 'LOL' 'things' 'lol' id='lol-link'}} "); Router.map(function() { this.resource('things', { path: '/things/:name' }, function() { this.route('other'); }); }); bootApplication(); Ember.run(router, 'handleURL', '/things/omg'); shouldBeActive('#omg-link'); shouldNotBeActive('#lol-link'); Ember.run(router, 'handleURL', '/things/omg/other'); shouldBeActive('#omg-link'); shouldNotBeActive('#lol-link'); }); QUnit.test("{{link-to}} populates href with default query param values even without query-params object", function() { App.IndexController = Ember.Controller.extend({ queryParams: ['foo'], foo: '123' }); Ember.TEMPLATES.index = compile("{{#link-to 'index' id='the-link'}}Index{{/link-to}}"); bootApplication(); equal(Ember.$('#the-link').attr('href'), "/", "link has right href"); }); QUnit.test("{{link-to}} populates href with default query param values with empty query-params object", function() { App.IndexController = Ember.Controller.extend({ queryParams: ['foo'], foo: '123' }); Ember.TEMPLATES.index = compile("{{#link-to 'index' (query-params) id='the-link'}}Index{{/link-to}}"); bootApplication(); equal(Ember.$('#the-link').attr('href'), "/", "link has right href"); }); QUnit.test("{{link-to}} populates href with supplied query param values", function() { App.IndexController = Ember.Controller.extend({ queryParams: ['foo'], foo: '123' }); Ember.TEMPLATES.index = compile("{{#link-to 'index' (query-params foo='456') id='the-link'}}Index{{/link-to}}"); bootApplication(); equal(Ember.$('#the-link').attr('href'), "/?foo=456", "link has right href"); }); QUnit.test("{{link-to}} populates href with partially supplied query param values", function() { App.IndexController = Ember.Controller.extend({ queryParams: ['foo', 'bar'], foo: '123', bar: 'yes' }); Ember.TEMPLATES.index = compile("{{#link-to 'index' (query-params foo='456') id='the-link'}}Index{{/link-to}}"); bootApplication(); equal(Ember.$('#the-link').attr('href'), "/?foo=456", "link has right href"); }); QUnit.test("{{link-to}} populates href with partially supplied query param values, but omits if value is default value", function() { App.IndexController = Ember.Controller.extend({ queryParams: ['foo', 'bar'], foo: '123', bar: 'yes' }); Ember.TEMPLATES.index = compile("{{#link-to 'index' (query-params foo='123') id='the-link'}}Index{{/link-to}}"); bootApplication(); equal(Ember.$('#the-link').attr('href'), "/", "link has right href"); }); QUnit.test("{{link-to}} populates href with fully supplied query param values", function() { App.IndexController = Ember.Controller.extend({ queryParams: ['foo', 'bar'], foo: '123', bar: 'yes' }); Ember.TEMPLATES.index = compile("{{#link-to 'index' (query-params foo='456' bar='NAW') id='the-link'}}Index{{/link-to}}"); bootApplication(); equal(Ember.$('#the-link').attr('href'), "/?bar=NAW&foo=456", "link has right href"); }); QUnit.module("The {{link-to}} helper: invoking with query params", { setup() { Ember.run(function() { sharedSetup(); App.IndexController = Ember.Controller.extend({ queryParams: ['foo', 'bar', 'abool'], foo: '123', bar: 'abc', boundThing: "OMG", abool: true }); App.AboutController = Ember.Controller.extend({ queryParams: ['baz', 'bat'], baz: 'alex', bat: 'borf' }); registry.unregister('router:main'); registry.register('router:main', Router); }); }, teardown: sharedTeardown }); QUnit.test("doesn't update controller QP properties on current route when invoked", function() { Ember.TEMPLATES.index = compile("{{#link-to 'index' id='the-link'}}Index{{/link-to}}"); bootApplication(); Ember.run(Ember.$('#the-link'), 'click'); var indexController = container.lookup('controller:index'); deepEqual(indexController.getProperties('foo', 'bar'), { foo: '123', bar: 'abc' }, "controller QP properties not"); }); QUnit.test("doesn't update controller QP properties on current route when invoked (empty query-params obj)", function() { Ember.TEMPLATES.index = compile("{{#link-to 'index' (query-params) id='the-link'}}Index{{/link-to}}"); bootApplication(); Ember.run(Ember.$('#the-link'), 'click'); var indexController = container.lookup('controller:index'); deepEqual(indexController.getProperties('foo', 'bar'), { foo: '123', bar: 'abc' }, "controller QP properties not"); }); QUnit.test("link-to with no params throws", function() { Ember.TEMPLATES.index = compile("{{#link-to id='the-link'}}Index{{/link-to}}"); expectAssertion(function() { bootApplication(); }, /one or more/); }); QUnit.test("doesn't update controller QP properties on current route when invoked (empty query-params obj, inferred route)", function() { Ember.TEMPLATES.index = compile("{{#link-to (query-params) id='the-link'}}Index{{/link-to}}"); bootApplication(); Ember.run(Ember.$('#the-link'), 'click'); var indexController = container.lookup('controller:index'); deepEqual(indexController.getProperties('foo', 'bar'), { foo: '123', bar: 'abc' }, "controller QP properties not"); }); QUnit.test("updates controller QP properties on current route when invoked", function() { Ember.TEMPLATES.index = compile("{{#link-to 'index' (query-params foo='456') id='the-link'}}Index{{/link-to}}"); bootApplication(); Ember.run(Ember.$('#the-link'), 'click'); var indexController = container.lookup('controller:index'); deepEqual(indexController.getProperties('foo', 'bar'), { foo: '456', bar: 'abc' }, "controller QP properties updated"); }); QUnit.test("updates controller QP properties on current route when invoked (inferred route)", function() { Ember.TEMPLATES.index = compile("{{#link-to (query-params foo='456') id='the-link'}}Index{{/link-to}}"); bootApplication(); Ember.run(Ember.$('#the-link'), 'click'); var indexController = container.lookup('controller:index'); deepEqual(indexController.getProperties('foo', 'bar'), { foo: '456', bar: 'abc' }, "controller QP properties updated"); }); QUnit.test("updates controller QP properties on other route after transitioning to that route", function() { Router.map(function() { this.route('about'); }); Ember.TEMPLATES.index = compile("{{#link-to 'about' (query-params baz='lol') id='the-link'}}About{{/link-to}}"); bootApplication(); equal(Ember.$('#the-link').attr('href'), '/about?baz=lol'); Ember.run(Ember.$('#the-link'), 'click'); var aboutController = container.lookup('controller:about'); deepEqual(aboutController.getProperties('baz', 'bat'), { baz: 'lol', bat: 'borf' }, "about controller QP properties updated"); equal(container.lookup('controller:application').get('currentPath'), "about"); }); QUnit.test("supplied QP properties can be bound", function() { var indexController = container.lookup('controller:index'); Ember.TEMPLATES.index = compile("{{#link-to (query-params foo=boundThing) id='the-link'}}Index{{/link-to}}"); bootApplication(); equal(Ember.$('#the-link').attr('href'), '/?foo=OMG'); Ember.run(indexController, 'set', 'boundThing', "ASL"); equal(Ember.$('#the-link').attr('href'), '/?foo=ASL'); }); QUnit.test("supplied QP properties can be bound (booleans)", function() { var indexController = container.lookup('controller:index'); Ember.TEMPLATES.index = compile("{{#link-to (query-params abool=boundThing) id='the-link'}}Index{{/link-to}}"); bootApplication(); equal(Ember.$('#the-link').attr('href'), '/?abool=OMG'); Ember.run(indexController, 'set', 'boundThing', false); equal(Ember.$('#the-link').attr('href'), '/?abool=false'); Ember.run(Ember.$('#the-link'), 'click'); deepEqual(indexController.getProperties('foo', 'bar', 'abool'), { foo: '123', bar: 'abc', abool: false }); }); QUnit.test("href updates when unsupplied controller QP props change", function() { var indexController = container.lookup('controller:index'); Ember.TEMPLATES.index = compile("{{#link-to (query-params foo='lol') id='the-link'}}Index{{/link-to}}"); bootApplication(); equal(Ember.$('#the-link').attr('href'), '/?foo=lol'); Ember.run(indexController, 'set', 'bar', 'BORF'); equal(Ember.$('#the-link').attr('href'), '/?bar=BORF&foo=lol'); Ember.run(indexController, 'set', 'foo', 'YEAH'); equal(Ember.$('#the-link').attr('href'), '/?bar=BORF&foo=lol'); }); QUnit.test("The {{link-to}} applies activeClass when query params are not changed", function() { Ember.TEMPLATES.index = compile( "{{#link-to (query-params foo='cat') id='cat-link'}}Index{{/link-to}} " + "{{#link-to (query-params foo='dog') id='dog-link'}}Index{{/link-to}} " + "{{#link-to 'index' id='change-nothing'}}Index{{/link-to}}" ); Ember.TEMPLATES.search = compile( "{{#link-to (query-params search='same') id='same-search'}}Index{{/link-to}} " + "{{#link-to (query-params search='change') id='change-search'}}Index{{/link-to}} " + "{{#link-to (query-params search='same' archive=true) id='same-search-add-archive'}}Index{{/link-to}} " + "{{#link-to (query-params archive=true) id='only-add-archive'}}Index{{/link-to}} " + "{{#link-to (query-params search='same' archive=true) id='both-same'}}Index{{/link-to}} " + "{{#link-to (query-params search='different' archive=true) id='change-one'}}Index{{/link-to}} " + "{{#link-to (query-params search='different' archive=false) id='remove-one'}}Index{{/link-to}} " + "{{outlet}}" ); Ember.TEMPLATES['search/results'] = compile( "{{#link-to (query-params sort='title') id='same-sort-child-only'}}Index{{/link-to}} " + "{{#link-to (query-params search='same') id='same-search-parent-only'}}Index{{/link-to}} " + "{{#link-to (query-params search='change') id='change-search-parent-only'}}Index{{/link-to}} " + "{{#link-to (query-params search='same' sort='title') id='same-search-same-sort-child-and-parent'}}Index{{/link-to}} " + "{{#link-to (query-params search='same' sort='author') id='same-search-different-sort-child-and-parent'}}Index{{/link-to}} " + "{{#link-to (query-params search='change' sort='title') id='change-search-same-sort-child-and-parent'}}Index{{/link-to}} " + "{{#link-to (query-params foo='dog') id='dog-link'}}Index{{/link-to}} " ); Router.map(function() { this.resource("search", function() { this.route("results"); }); }); App.SearchController = Ember.Controller.extend({ queryParams: ['search', 'archive'], search: '', archive: false }); App.SearchResultsController = Ember.Controller.extend({ queryParams: ['sort', 'showDetails'], sort: 'title', showDetails: true }); bootApplication(); //Basic tests shouldNotBeActive('#cat-link'); shouldNotBeActive('#dog-link'); Ember.run(router, 'handleURL', '/?foo=cat'); shouldBeActive('#cat-link'); shouldNotBeActive('#dog-link'); Ember.run(router, 'handleURL', '/?foo=dog'); shouldBeActive('#dog-link'); shouldNotBeActive('#cat-link'); shouldBeActive('#change-nothing'); //Multiple params Ember.run(function() { router.handleURL("/search?search=same"); }); shouldBeActive('#same-search'); shouldNotBeActive('#change-search'); shouldNotBeActive('#same-search-add-archive'); shouldNotBeActive('#only-add-archive'); shouldNotBeActive('#remove-one'); Ember.run(function() { router.handleURL("/search?search=same&archive=true"); }); shouldBeActive('#both-same'); shouldNotBeActive('#change-one'); //Nested Controllers Ember.run(function() { // Note: this is kind of a strange case; sort's default value is 'title', // so this URL shouldn't have been generated in the first place, but // we should also be able to gracefully handle these cases. router.handleURL("/search/results?search=same&sort=title&showDetails=true"); }); //shouldBeActive('#same-sort-child-only'); shouldBeActive('#same-search-parent-only'); shouldNotBeActive('#change-search-parent-only'); shouldBeActive('#same-search-same-sort-child-and-parent'); shouldNotBeActive('#same-search-different-sort-child-and-parent'); shouldNotBeActive('#change-search-same-sort-child-and-parent'); }); QUnit.test("The {{link-to}} applies active class when query-param is number", function() { Ember.TEMPLATES.index = compile( "{{#link-to (query-params page=pageNumber) id='page-link'}}Index{{/link-to}} "); App.IndexController = Ember.Controller.extend({ queryParams: ['page'], page: 1, pageNumber: 5 }); bootApplication(); shouldNotBeActive('#page-link'); Ember.run(router, 'handleURL', '/?page=5'); shouldBeActive('#page-link'); }); QUnit.test("The {{link-to}} applies active class when query-param is array", function() { Ember.TEMPLATES.index = compile( "{{#link-to (query-params pages=pagesArray) id='array-link'}}Index{{/link-to}} " + "{{#link-to (query-params pages=biggerArray) id='bigger-link'}}Index{{/link-to}} " + "{{#link-to (query-params pages=emptyArray) id='empty-link'}}Index{{/link-to}} " ); App.IndexController = Ember.Controller.extend({ queryParams: ['pages'], pages: [], pagesArray: [1,2], biggerArray: [1,2,3], emptyArray: [] }); bootApplication(); shouldNotBeActive('#array-link'); Ember.run(router, 'handleURL', '/?pages=%5B1%2C2%5D'); shouldBeActive('#array-link'); shouldNotBeActive('#bigger-link'); shouldNotBeActive('#empty-link'); Ember.run(router, 'handleURL', '/?pages=%5B2%2C1%5D'); shouldNotBeActive('#array-link'); shouldNotBeActive('#bigger-link'); shouldNotBeActive('#empty-link'); Ember.run(router, 'handleURL', '/?pages=%5B1%2C2%2C3%5D'); shouldBeActive('#bigger-link'); shouldNotBeActive('#array-link'); shouldNotBeActive('#empty-link'); }); QUnit.test("The {{link-to}} helper applies active class to parent route", function() { App.Router.map(function() { this.resource('parent', function() { this.route('child'); }); }); Ember.TEMPLATES.application = compile( "{{#link-to 'parent' id='parent-link'}}Parent{{/link-to}} " + "{{#link-to 'parent.child' id='parent-child-link'}}Child{{/link-to}} " + "{{#link-to 'parent' (query-params foo=cat) id='parent-link-qp'}}Parent{{/link-to}} " + "{{outlet}}" ); App.ParentChildController = Ember.Controller.extend({ queryParams: ['foo'], foo: 'bar' }); bootApplication(); shouldNotBeActive('#parent-link'); shouldNotBeActive('#parent-child-link'); shouldNotBeActive('#parent-link-qp'); Ember.run(router, 'handleURL', '/parent/child?foo=dog'); shouldBeActive('#parent-link'); shouldNotBeActive('#parent-link-qp'); }); QUnit.test("The {{link-to}} helper disregards query-params in activeness computation when current-when specified", function() { App.Router.map(function() { this.route('parent'); }); Ember.TEMPLATES.application = compile( "{{#link-to 'parent' (query-params page=1) current-when='parent' id='app-link'}}Parent{{/link-to}} {{outlet}}"); Ember.TEMPLATES.parent = compile( "{{#link-to 'parent' (query-params page=1) current-when='parent' id='parent-link'}}Parent{{/link-to}} {{outlet}}"); App.ParentController = Ember.Controller.extend({ queryParams: ['page'], page: 1 }); bootApplication(); equal(Ember.$('#app-link').attr('href'), '/parent'); shouldNotBeActive('#app-link'); Ember.run(router, 'handleURL', '/parent?page=2'); equal(Ember.$('#app-link').attr('href'), '/parent'); shouldBeActive('#app-link'); equal(Ember.$('#parent-link').attr('href'), '/parent'); shouldBeActive('#parent-link'); var parentController = container.lookup('controller:parent'); equal(parentController.get('page'), 2); Ember.run(parentController, 'set', 'page', 3); equal(router.get('location.path'), '/parent?page=3'); shouldBeActive('#app-link'); shouldBeActive('#parent-link'); Ember.$('#app-link').click(); equal(router.get('location.path'), '/parent'); }); function basicEagerURLUpdateTest(setTagName) { expect(6); if (setTagName) { Ember.TEMPLATES.application = compile("{{outlet}}{{link-to 'Index' 'index' id='index-link'}}{{link-to 'About' 'about' id='about-link' tagName='span'}}"); } bootApplication(); equal(updateCount, 0); Ember.run(Ember.$('#about-link'), 'click'); // URL should be eagerly updated now equal(updateCount, 1); equal(router.get('location.path'), '/about'); // Resolve the promise. Ember.run(aboutDefer, 'resolve'); equal(router.get('location.path'), '/about'); // Shouldn't have called update url again. equal(updateCount, 1); equal(router.get('location.path'), '/about'); } var aboutDefer, otherDefer; if (!Ember.FEATURES.isEnabled('ember-routing-transitioning-classes')) { QUnit.module("The {{link-to}} helper: eager URL updating", { setup() { Ember.run(function() { sharedSetup(); registry.unregister('router:main'); registry.register('router:main', Router); Router.map(function() { this.route('about'); }); App.AboutRoute = Ember.Route.extend({ model() { aboutDefer = Ember.RSVP.defer(); return aboutDefer.promise; } }); Ember.TEMPLATES.application = compile("{{outlet}}{{link-to 'Index' 'index' id='index-link'}}{{link-to 'About' 'about' id='about-link'}}"); }); }, teardown() { sharedTeardown(); aboutDefer = null; } }); QUnit.test("invoking a link-to with a slow promise eager updates url", function() { basicEagerURLUpdateTest(false); }); QUnit.test("when link-to eagerly updates url, the path it provides does NOT include the rootURL", function() { expect(2); // HistoryLocation is the only Location class that will cause rootURL to be // prepended to link-to href's right now var HistoryTestLocation = Ember.HistoryLocation.extend({ location: { hash: '', hostname: 'emberjs.com', href: 'http://emberjs.com/app/', pathname: '/app/', protocol: 'http:', port: '', search: '' }, // Don't actually touch the URL replaceState(path) {}, pushState(path) {}, setURL(path) { set(this, 'path', path); }, replaceURL(path) { set(this, 'path', path); } }); registry.register('location:historyTest', HistoryTestLocation); Router.reopen({ location: 'historyTest', rootURL: '/app/' }); bootApplication(); // href should have rootURL prepended equal(Ember.$('#about-link').attr('href'), '/app/about'); Ember.run(Ember.$('#about-link'), 'click'); // Actual path provided to Location class should NOT have rootURL equal(router.get('location.path'), '/about'); }); QUnit.test("non `a` tags also eagerly update URL", function() { basicEagerURLUpdateTest(true); }); QUnit.test("invoking a link-to with a promise that rejects on the run loop doesn't update url", function() { App.AboutRoute = Ember.Route.extend({ model() { return Ember.RSVP.reject(); } }); bootApplication(); Ember.run(Ember.$('#about-link'), 'click'); // Shouldn't have called update url. equal(updateCount, 0); equal(router.get('location.path'), '', 'url was not updated'); }); QUnit.test("invoking a link-to whose transition gets aborted in will transition doesn't update the url", function() { App.IndexRoute = Ember.Route.extend({ actions: { willTransition(transition) { ok(true, "aborting transition"); transition.abort(); } } }); bootApplication(); Ember.run(Ember.$('#about-link'), 'click'); // Shouldn't have called update url. equal(updateCount, 0); equal(router.get('location.path'), '', 'url was not updated'); }); } if (Ember.FEATURES.isEnabled('ember-routing-transitioning-classes')) { QUnit.module("The {{link-to}} helper: .transitioning-in .transitioning-out CSS classes", { setup() { Ember.run(function() { sharedSetup(); registry.unregister('router:main'); registry.register('router:main', Router); Router.map(function() { this.route('about'); this.route('other'); }); App.AboutRoute = Ember.Route.extend({ model() { aboutDefer = Ember.RSVP.defer(); return aboutDefer.promise; } }); App.OtherRoute = Ember.Route.extend({ model() { otherDefer = Ember.RSVP.defer(); return otherDefer.promise; } }); Ember.TEMPLATES.application = compile("{{outlet}}{{link-to 'Index' 'index' id='index-link'}}{{link-to 'About' 'about' id='about-link'}}{{link-to 'Other' 'other' id='other-link'}}"); }); }, teardown() { sharedTeardown(); aboutDefer = null; } }); QUnit.test("while a transition is underway", function() { expect(18); bootApplication(); function assertHasClass(className) { var i = 1; while (i < arguments.length) { var $a = arguments[i]; var shouldHaveClass = arguments[i+1]; equal($a.hasClass(className), shouldHaveClass, $a.attr('id') + " should " + (shouldHaveClass ? '' : "not ") + "have class " + className); i +=2; } } var $index = Ember.$('#index-link'); var $about = Ember.$('#about-link'); var $other = Ember.$('#other-link'); Ember.run($about, 'click'); assertHasClass('active', $index, true, $about, false, $other, false); assertHasClass('ember-transitioning-in', $index, false, $about, true, $other, false); assertHasClass('ember-transitioning-out', $index, true, $about, false, $other, false); Ember.run(aboutDefer, 'resolve'); assertHasClass('active', $index, false, $about, true, $other, false); assertHasClass('ember-transitioning-in', $index, false, $about, false, $other, false); assertHasClass('ember-transitioning-out', $index, false, $about, false, $other, false); }); QUnit.test("while a transition is underway with nested link-to's", function() { expect(54); Router.map(function() { this.route('parent-route', function() { this.route('about'); this.route('other'); }); }); App.ParentRouteAboutRoute = Ember.Route.extend({ model() { aboutDefer = Ember.RSVP.defer(); return aboutDefer.promise; } }); App.ParentRouteOtherRoute = Ember.Route.extend({ model() { otherDefer = Ember.RSVP.defer(); return otherDefer.promise; } }); Ember.TEMPLATES.application = compile(` {{outlet}} {{#link-to 'index' tagName='li'}} {{link-to 'Index' 'index' id='index-link'}} {{/link-to}} {{#link-to 'parent-route.about' tagName='li'}} {{link-to 'About' 'parent-route.about' id='about-link'}} {{/link-to}} {{#link-to 'parent-route.other' tagName='li'}} {{link-to 'Other' 'parent-route.other' id='other-link'}} {{/link-to}} `); bootApplication(); function assertHasClass(className) { var i = 1; while (i < arguments.length) { var $a = arguments[i]; var shouldHaveClass = arguments[i+1]; equal($a.hasClass(className), shouldHaveClass, $a.attr('id') + " should " + (shouldHaveClass ? '' : "not ") + "have class " + className); i +=2; } } var $index = Ember.$('#index-link'); var $about = Ember.$('#about-link'); var $other = Ember.$('#other-link'); Ember.run($about, 'click'); assertHasClass('active', $index, true, $about, false, $other, false); assertHasClass('ember-transitioning-in', $index, false, $about, true, $other, false); assertHasClass('ember-transitioning-out', $index, true, $about, false, $other, false); Ember.run(aboutDefer, 'resolve'); assertHasClass('active', $index, false, $about, true, $other, false); assertHasClass('ember-transitioning-in', $index, false, $about, false, $other, false); assertHasClass('ember-transitioning-out', $index, false, $about, false, $other, false); Ember.run($other, 'click'); assertHasClass('active', $index, false, $about, true, $other, false); assertHasClass('ember-transitioning-in', $index, false, $about, false, $other, true); assertHasClass('ember-transitioning-out', $index, false, $about, true, $other, false); Ember.run(otherDefer, 'resolve'); assertHasClass('active', $index, false, $about, false, $other, true); assertHasClass('ember-transitioning-in', $index, false, $about, false, $other, false); assertHasClass('ember-transitioning-out', $index, false, $about, false, $other, false); Ember.run($about, 'click'); assertHasClass('active', $index, false, $about, false, $other, true); assertHasClass('ember-transitioning-in', $index, false, $about, true, $other, false); assertHasClass('ember-transitioning-out', $index, false, $about, false, $other, true); Ember.run(aboutDefer, 'resolve'); assertHasClass('active', $index, false, $about, true, $other, false); assertHasClass('ember-transitioning-in', $index, false, $about, false, $other, false); assertHasClass('ember-transitioning-out', $index, false, $about, false, $other, false); }); }
mit
cosnics/cosnics
src/Chamilo/Core/Repository/ContentObject/File/Common/Rendition/Html/Extension/HtmlInlineHtmlRenditionImplementation.php
1994
<?php namespace Chamilo\Core\Repository\ContentObject\File\Common\Rendition\Html\Extension; use Chamilo\Core\Repository\ContentObject\File\Common\Rendition\Html\HtmlInlineRenditionImplementation; use Chamilo\Core\Repository\ContentObject\File\Storage\DataClass\File; use Chamilo\Libraries\Format\Theme; /** * * @package Chamilo\Core\Repository\ContentObject\File\Common\Rendition\Html\Extension * @author Hans De Bisschop <hans.de.bisschop@ehb.be> * @author Magali Gillard <magali.gillard@ehb.be> */ class HtmlInlineHtmlRenditionImplementation extends HtmlInlineRenditionImplementation { /** * @param array $parameters * * @return string * @throws \Chamilo\Libraries\Architecture\Exceptions\ObjectNotExistException * @throws \Twig\Error\LoaderError * @throws \Twig\Error\RuntimeError * @throws \Twig\Error\SyntaxError */ public function render($parameters) { /** @var File $object */ $object = $this->get_content_object(); $url = \Chamilo\Core\Repository\Manager::get_document_downloader_url( $object->get_id(), $object->calculate_security_code()) . '&display=1'; $html = array(); // if(!$this->isIframeAllowed($object)) // { // return $this->renderThumbnail($object); // } $html[] = '<div class="text-container">'; $html[] = '<iframe class="text-frame" src="' . $url . '" sandbox="allow-forms allow-pointer-lock allow-same-origin allow-scripts">'; $html[] = '</iframe>'; $html[] = $this->renderActions(); $html[] = '</div>'; return implode(PHP_EOL, $html); } /** * @param File $contentObject * * @return bool */ protected function isIframeAllowed(File $contentObject) { $owner = $contentObject->get_owner(); if(!$owner->is_teacher()) { return false; } return true; } }
mit
amplitude/analytics-android
analytics/src/main/java/com/segment/analytics/Properties.java
11963
/* * The MIT License (MIT) * * Copyright (c) 2014 Segment, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.segment.analytics; import java.util.List; import java.util.Map; /** * Properties are a dictionary of free-form information to attach to specific events. * <p/> * Just like traits, we also accept some properties with semantic meaning, and you should only ever * use these property names for that purpose. */ public class Properties extends ValueMap { // Common Properties private static final String REVENUE_KEY = "revenue"; private static final String CURRENCY_KEY = "currency"; private static final String VALUE_KEY = "value"; // Screen Properties private static final String PATH_KEY = "path"; private static final String REFERRER_KEY = "referrer"; private static final String TITLE_KEY = "title"; private static final String URL_KEY = "url"; // Ecommerce API private static final String NAME_KEY = "name"; // used by product too private static final String CATEGORY_KEY = "category"; private static final String SKU_KEY = "sku"; private static final String PRICE_KEY = "price"; private static final String ID_KEY = "id"; private static final String ORDER_ID_KEY = "orderId"; private static final String TOTAL_KEY = "total"; private static final String SUBTOTAL_KEY = "subtotal"; private static final String SHIPPING_KEY = "shipping"; private static final String TAX_KEY = "tax"; private static final String DISCOUNT_KEY = "discount"; private static final String COUPON_KEY = "coupon"; private static final String PRODUCTS_KEY = "products"; private static final String REPEAT_KEY = "repeat"; public Properties() { } public Properties(int initialCapacity) { super(initialCapacity); } // For deserialization Properties(Map<String, Object> delegate) { super(delegate); } @Override public Properties putValue(String key, Object value) { super.putValue(key, value); return this; } /** * Set the amount of revenue an event resulted in. This should be a decimal value in dollars, so * a shirt worth $19.99 would result in a revenue of 19.99. */ public Properties putRevenue(double revenue) { return putValue(REVENUE_KEY, revenue); } public double revenue() { return getDouble(REVENUE_KEY, 0); } /** * Set an abstract value to associate with an event. This is typically used in situations where * the event doesn’t generate real-dollar revenue, but has an intrinsic value to a marketing * team, like newsletter signups. */ public Properties putValue(double value) { return putValue(VALUE_KEY, value); } public double value() { double value = getDouble(VALUE_KEY, 0); if (value != 0) { return value; } return revenue(); } /** The currency for the value set in {@link #putRevenue(double)}. */ public Properties putCurrency(String currency) { return putValue(CURRENCY_KEY, currency); } public String currency() { return getString(CURRENCY_KEY); } /** * Set a path (usually the path of the URL) for the screen. * * @see <a href="https://segment.com/docs/api/tracking/page/#properties">Page Properties</a> */ public Properties putPath(String path) { return putValue(PATH_KEY, path); } public String path() { return getString(PATH_KEY); } /** * Set the referrer that led the user to the screen. In the browser it is the document.referrer * property. * * @see <a href="https://segment.com/docs/api/tracking/page/#properties">Page Properties</a> */ public Properties putReferrer(String referrer) { return putValue(REFERRER_KEY, referrer); } public String referrer() { return getString(REFERRER_KEY); } /** * Set the title of the screen. * * @see <a href="https://segment.com/docs/api/tracking/page/#properties">Page Properties</a> */ public Properties putTitle(String title) { return putValue(TITLE_KEY, title); } public String title() { return getString(TITLE_KEY); } /** * Set a url for the screen. * * @see <a href="https://segment.com/docs/api/tracking/page/#properties">Page Properties</a> */ public Properties putUrl(String url) { return putValue(URL_KEY, url); } public String url() { return getString(URL_KEY); } /** * Set the name of the product associated with an event. * * @see <a href="https://segment.com/docs/api/tracking/ecommerce/">Ecommerce API</a> */ public Properties putName(String name) { return putValue(NAME_KEY, name); } public String name() { return getString(NAME_KEY); } /** * Set a category for this action. You’ll want to track all of your product category pages so * you can quickly see which categories are most popular. * * @see <a href="https://segment.com/docs/api/tracking/ecommerce/">Ecommerce API</a> */ public Properties putCategory(String category) { return putValue(CATEGORY_KEY, category); } public String category() { return getString(CATEGORY_KEY); } /** * Set a sku for the product associated with an event. * * @see <a href="https://segment.com/docs/api/tracking/ecommerce/">Ecommerce API</a> */ public Properties putSku(String sku) { return putValue(SKU_KEY, sku); } public String sku() { return getString(SKU_KEY); } /** * Set a price (in dollars) for the product associated with an event. * * @see <a href="https://segment.com/docs/api/tracking/ecommerce/">Ecommerce API</a> */ public Properties putPrice(double price) { return putValue(PRICE_KEY, price); } public double price() { return getDouble(PRICE_KEY, 0); } /** * Set an ID for the product associated with an event. * * @see <a href="https://segment.com/docs/api/tracking/ecommerce/">Ecommerce API</a> */ public Properties putProductId(String id) { return putValue(ID_KEY, id); } public String productId() { return getString(ID_KEY); } /** * Set the order ID associated with an event. * * @see <a href="https://segment.com/docs/api/tracking/ecommerce/">Ecommerce API</a> */ public Properties putOrderId(String orderId) { return putValue(ORDER_ID_KEY, orderId); } public String orderId() { return getString(ORDER_ID_KEY); } /** * Set the total amount (in dollars) for an order associated with an event. * * @see <a href="https://segment.com/docs/api/tracking/ecommerce/">Ecommerce API</a> */ public Properties putTotal(double total) { return putValue(TOTAL_KEY, total); } public double total() { double total = getDouble(TOTAL_KEY, 0); if (total != 0) { return total; } double revenue = revenue(); if (revenue != 0) { return revenue; } return value(); } /** * Set the subtotal (in dollars) for an order associated with an event (excluding tax and * shipping). * * @see <a href="https://segment.com/docs/api/tracking/ecommerce/">Ecommerce API</a> */ public Properties putSubtotal(double subtotal) { return putValue(SUBTOTAL_KEY, subtotal); } public double putSubtotal() { return getDouble(SUBTOTAL_KEY, 0); } /** * Set the shipping amount (in dollars) for an order associated with an event. * * @see <a href="https://segment.com/docs/api/tracking/ecommerce/">Ecommerce API</a> */ public Properties putShipping(double shipping) { return putValue(SHIPPING_KEY, shipping); } public double shipping() { return getDouble(SHIPPING_KEY, 0); } /** * Set the tax amount (in dollars) for an order associated with an event. * * @see <a href="https://segment.com/docs/api/tracking/ecommerce/">Ecommerce API</a> */ public Properties putTax(double tax) { return putValue(TAX_KEY, tax); } public double tax() { return getDouble(TAX_KEY, 0); } /** * Set the discount amount (in dollars) for an order associated with an event. * * @see <a href="https://segment.com/docs/api/tracking/ecommerce/">Ecommerce API</a> */ public Properties putDiscount(double discount) { return putValue(DISCOUNT_KEY, discount); } public double discount() { return getDouble(DISCOUNT_KEY, 0); } /** * Set a coupon name for an order associated with an event. * * @see <a href="https://segment.com/docs/api/tracking/ecommerce/">Ecommerce API</a> */ public Properties putCoupon(String coupon) { return putValue(COUPON_KEY, coupon); } /** * Set the individual products for an order associated with an event. * * @see <a href="https://segment.com/docs/api/tracking/ecommerce/">Ecommerce API</a> */ public Properties putProducts(Product... products) { return putValue(PRODUCTS_KEY, products); } public List<Product> products(Product... products) { return getList(PRODUCTS_KEY, Product.class); } /** * Set whether an order associated with an event is from a repeating customer. * * @see <a href="https://segment.com/docs/api/tracking/ecommerce/">Ecommerce API</a> */ public Properties putRepeatCustomer(boolean repeat) { return putValue(REPEAT_KEY, repeat); } public boolean isRepeatCustomer() { return getBoolean(REPEAT_KEY, false); } /** * A representation of an e-commerce product. * <p/> * Use this only when you have multiple products, usually for the "Completed Order" event. If you * have only one product, {@link Properties} has methods on it directly to attach this * information. */ public static class Product extends ValueMap { private static final String ID_KEY = "id"; private static final String SKU_KEY = "sku"; private static final String NAME_KEY = "name"; private static final String PRICE_KEY = "price"; /** * Create an e-commerce product with the given id, sku and price (in dollars). All parameters * are required for our ecommerce API. * * @param id The product ID in your database * @param sku The product SKU * @param price The price of the product (in dollars) */ public Product(String id, String sku, double price) { put(ID_KEY, id); put(SKU_KEY, sku); put(PRICE_KEY, price); } // For deserialization private Product(Map<String, Object> map) { super(map); } /** Set an optional name for this product. */ public Product putName(String name) { return putValue(NAME_KEY, name); } public String name() { return getString(NAME_KEY); } public String id() { return getString(ID_KEY); } public String sku() { return getString(SKU_KEY); } public double price() { return getDouble(PRICE_KEY, 0); } @Override public Product putValue(String key, Object value) { super.putValue(key, value); return this; } } }
mit
gregwym/joos-compiler-java
testcases/a2/Je_4_ExtendFinal.java
342
// JOOS1:HIERARCHY,EXTENDS_FINAL_CLASS // JOOS2:HIERARCHY,EXTENDS_FINAL_CLASS // JAVAC:UNKNOWN // /** * Hierarchy: * - A class must not extend a final class (8.1.1.2, 8.1.3, simple * constraint 4). */ public class Je_4_ExtendFinal extends Integer { public Je_4_ExtendFinal() {} public static int test() { return 123; } }
mit
OndraM/php-webdriver
lib/Exception/InvalidElementStateException.php
284
<?php namespace Facebook\WebDriver\Exception; /** * A command could not be completed because the element is in an invalid state, e.g. attempting to clear an element * that isn’t both editable and resettable. */ class InvalidElementStateException extends WebDriverException { }
mit
valentin-biig/sentry-demo
tests/AppBundle/Controller/Admin/BlogControllerTest.php
5972
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tests\AppBundle\Controller\Admin; use AppBundle\DataFixtures\FixturesTrait; use AppBundle\Entity\Post; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use Symfony\Component\HttpFoundation\Response; /** * Functional test for the controllers defined inside the BlogController used * for managing the blog in the backend. * * See https://symfony.com/doc/current/book/testing.html#functional-tests * * Whenever you test resources protected by a firewall, consider using the * technique explained in: * https://symfony.com/doc/current/cookbook/testing/http_authentication.html * * Execute the application tests using this command (requires PHPUnit to be installed): * * $ cd your-symfony-project/ * $ ./vendor/bin/phpunit */ class BlogControllerTest extends WebTestCase { use FixturesTrait; /** * @dataProvider getUrlsForRegularUsers */ public function testAccessDeniedForRegularUsers($httpMethod, $url) { $client = static::createClient([], [ 'PHP_AUTH_USER' => 'john_user', 'PHP_AUTH_PW' => 'kitten', ]); $client->request($httpMethod, $url); $this->assertSame(Response::HTTP_FORBIDDEN, $client->getResponse()->getStatusCode()); } public function getUrlsForRegularUsers() { yield ['GET', '/en/admin/post/']; yield ['GET', '/en/admin/post/1']; yield ['GET', '/en/admin/post/1/edit']; yield ['POST', '/en/admin/post/1/delete']; } public function testAdminBackendHomePage() { $client = static::createClient([], [ 'PHP_AUTH_USER' => 'jane_admin', 'PHP_AUTH_PW' => 'kitten', ]); $crawler = $client->request('GET', '/en/admin/post/'); $this->assertSame(Response::HTTP_OK, $client->getResponse()->getStatusCode()); $this->assertCount( 30, $crawler->filter('body#admin_post_index #main tbody tr'), 'The backend homepage displays all the available posts.' ); } /** * This test changes the database contents by creating a new blog post. However, * thanks to the DAMADoctrineTestBundle and its PHPUnit listener, all changes * to the database are rolled back when this test completes. This means that * all the application tests begin with the same database contents. */ public function testAdminNewPost() { $postTitle = 'Blog Post Title '.mt_rand(); $postSummary = $this->getRandomPostSummary(); $postContent = $this->getPostContent(); $client = static::createClient([], [ 'PHP_AUTH_USER' => 'jane_admin', 'PHP_AUTH_PW' => 'kitten', ]); $crawler = $client->request('GET', '/en/admin/post/new'); $form = $crawler->selectButton('Create post')->form([ 'post[title]' => $postTitle, 'post[summary]' => $postSummary, 'post[content]' => $postContent, ]); $client->submit($form); $this->assertSame(Response::HTTP_FOUND, $client->getResponse()->getStatusCode()); $post = $client->getContainer()->get('doctrine')->getRepository(Post::class)->findOneBy([ 'title' => $postTitle, ]); $this->assertNotNull($post); $this->assertSame($postSummary, $post->getSummary()); $this->assertSame($postContent, $post->getContent()); } public function testAdminShowPost() { $client = static::createClient([], [ 'PHP_AUTH_USER' => 'jane_admin', 'PHP_AUTH_PW' => 'kitten', ]); $client->request('GET', '/en/admin/post/1'); $this->assertSame(Response::HTTP_OK, $client->getResponse()->getStatusCode()); } /** * This test changes the database contents by editing a blog post. However, * thanks to the DAMADoctrineTestBundle and its PHPUnit listener, all changes * to the database are rolled back when this test completes. This means that * all the application tests begin with the same database contents. */ public function testAdminEditPost() { $newBlogPostTitle = 'Blog Post Title '.mt_rand(); $client = static::createClient([], [ 'PHP_AUTH_USER' => 'jane_admin', 'PHP_AUTH_PW' => 'kitten', ]); $crawler = $client->request('GET', '/en/admin/post/1/edit'); $form = $crawler->selectButton('Save changes')->form([ 'post[title]' => $newBlogPostTitle, ]); $client->submit($form); $this->assertSame(Response::HTTP_FOUND, $client->getResponse()->getStatusCode()); /** @var Post $post */ $post = $client->getContainer()->get('doctrine')->getRepository(Post::class)->find(1); $this->assertSame($newBlogPostTitle, $post->getTitle()); } /** * This test changes the database contents by deleting a blog post. However, * thanks to the DAMADoctrineTestBundle and its PHPUnit listener, all changes * to the database are rolled back when this test completes. This means that * all the application tests begin with the same database contents. */ public function testAdminDeletePost() { $client = static::createClient([], [ 'PHP_AUTH_USER' => 'jane_admin', 'PHP_AUTH_PW' => 'kitten', ]); $crawler = $client->request('GET', '/en/admin/post/1'); $client->submit($crawler->filter('#delete-form')->form()); $this->assertSame(Response::HTTP_FOUND, $client->getResponse()->getStatusCode()); $post = $client->getContainer()->get('doctrine')->getRepository(Post::class)->find(1); $this->assertNull($post); } }
mit
navalev/azure-sdk-for-java
sdk/mediaservices/mgmt-v2018_06_01_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2018_06_01_preview/Codec.java
1790
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.mediaservices.v2018_06_01_preview; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonSubTypes; /** * Describes the basic properties of all codecs. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@odata\\.type", defaultImpl = Codec.class) @JsonTypeName("Codec") @JsonSubTypes({ @JsonSubTypes.Type(name = "#Microsoft.Media.Audio", value = Audio.class), @JsonSubTypes.Type(name = "#Microsoft.Media.CopyVideo", value = CopyVideo.class), @JsonSubTypes.Type(name = "#Microsoft.Media.Video", value = Video.class), @JsonSubTypes.Type(name = "#Microsoft.Media.CopyAudio", value = CopyAudio.class) }) public class Codec { /** * An optional label for the codec. The label can be used to control muxing * behavior. */ @JsonProperty(value = "label") private String label; /** * Get an optional label for the codec. The label can be used to control muxing behavior. * * @return the label value */ public String label() { return this.label; } /** * Set an optional label for the codec. The label can be used to control muxing behavior. * * @param label the label value to set * @return the Codec object itself. */ public Codec withLabel(String label) { this.label = label; return this; } }
mit
redknightlois/arrayslice
Corvalius.ArraySlice.Portable328/IHideObjectMembers.cs
337
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; namespace Corvalius.ArraySlice { [EditorBrowsable(EditorBrowsableState.Never)] public interface IHideObjectMembers { [EditorBrowsable(EditorBrowsableState.Never)] string ToString(); } }
mit
mattdbridges/validates_formatting_of
spec/validates_formatting_of/model_additions_spec.rb
12755
require 'spec_helper' RSpec.describe ValidatesFormattingOf::ModelAdditions do describe "email" do class Email < TestActiveRecord attr_accessor :email validates_formatting_of :email end it "validates that the email provided is valid" do expect(Email.new(:email => "example@example.com")).to be_valid expect(Email.new(:email => "badexample.com")).not_to be_valid expect(Email.new(:email => "mbridges.91@gmail.com")).to be_valid expect(Email.new(:email => "some-random%%%strangely-formatted-email@lots.of.subdomains.com")).to be_valid expect(Email.new(:email => "this__???{}|__should@be-valid.com")).to be_valid expect(Email.new(:email => "visitorservices@vmfa.museum")).to be_valid expect(Email.new(:email => "info@samoa.travel")).to be_valid expect(Email.new(:email => "info@-samoa.travel")).not_to be_valid expect(Email.new(:email => "info@samoa-.travel")).not_to be_valid expect(Email.new(:email => "info@123-samoa.travel")).to be_valid expect(Email.new(:email => "info@123-samoa.travel\n")).not_to be_valid end end describe "simple email for 1.8.7 and javascript validations (such as with client_side_validations)" do class SimpleEmail < TestActiveRecord attr_accessor :email validates_formatting_of :email, :using => :simple_email end it "validates that the email provided is valid" do expect(SimpleEmail.new(:email => "example@example.com")).to be_valid expect(SimpleEmail.new(:email => "badexample.com")).not_to be_valid expect(SimpleEmail.new(:email => "mbridges.91@gmail.com")).to be_valid expect(SimpleEmail.new(:email => "some-random%%%strangely-formatted-email@lots.of.subdomains.com")).to be_valid expect(SimpleEmail.new(:email => "this__???{}|__should@be-valid.com")).to be_valid expect(SimpleEmail.new(:email => "visitorservices@vmfa.museum")).to be_valid expect(SimpleEmail.new(:email => "info@samoa.travel")).to be_valid expect(SimpleEmail.new(:email => "info@-samoa.travel")).to be_valid expect(SimpleEmail.new(:email => "info@samoa-.travel")).to be_valid expect(SimpleEmail.new(:email => "info@123-samoa.travel")).to be_valid expect(SimpleEmail.new(:email => "info@123-samoa.travel\n")).not_to be_valid end end describe "url" do class Webpage < TestActiveRecord attr_accessor :url validates_formatting_of :url end it "validates that the url provided is valid" do expect(Webpage.new(:url => 'http://something.com')).to be_valid expect(Webpage.new(:url => 'http://something-else.com')).to be_valid expect(Webpage.new(:url => 'http://sub.domains.something-else.com')).to be_valid expect(Webpage.new(:url => 'http://username:password@something-else.com')).to be_valid expect(Webpage.new(:url => "http://username:password@something-else.com\n")).not_to be_valid expect(Webpage.new(:url => "something else")).not_to be_valid end end describe "us_zip" do class USZip < TestActiveRecord attr_accessor :zipcode validates_formatting_of :zipcode, :using => :us_zip end it "validates that the zipcode provided is valid" do expect(USZip.new(:zipcode => '92348')).to be_valid expect(USZip.new(:zipcode => '23434-2348')).to be_valid expect(USZip.new(:zipcode => "23434-2348\n")).not_to be_valid expect(USZip.new(:zipcode => '234')).not_to be_valid expect(USZip.new(:zipcode => '23408234')).not_to be_valid expect(USZip.new(:zipcode => 'invalid')).not_to be_valid end end describe "alpha" do class Alpha < TestActiveRecord attr_accessor :alpha validates_formatting_of :alpha end it "validates that the letters provided is valid" do expect(Alpha.new(:alpha => 'abscdsofjsdpfahdsofkajlsdfaspdhjfads')).to be_valid expect(Alpha.new(:alpha => 'asdfalskdfjhas-dlfhasdksdfaldhfadsfasdfa')).to be_valid expect(Alpha.new(:alpha => 'adsufasodfksadjfskjdfha98')).not_to be_valid expect(Alpha.new(:alpha => 'asdf ausdpf98hasdfo alsdf ja8 sd')).not_to be_valid end end describe "alphanum" do class Alphanum < TestActiveRecord attr_accessor :letters_and_numbers validates_formatting_of :letters_and_numbers, :using => :alphanum end it "validates that the letters provided is valid" do expect(Alphanum.new(:letters_and_numbers => 'numbersandlettersarevalid1234567890')).to be_valid expect(Alphanum.new(:letters_and_numbers => 'justletters')).to be_valid expect(Alphanum.new(:letters_and_numbers => 'letters and numbers 123 with spaces')).to be_valid expect(Alphanum.new(:letters_and_numbers => 'adding ; some special ** chars')).not_to be_valid end end describe "us_phone" do class USPhone < TestActiveRecord attr_accessor :phone_number validates_formatting_of :phone_number, :using => :us_phone end it "validates that the phone number provided is valid" do expect(USPhone.new(:phone_number => '(234) 234-3456')).to be_valid expect(USPhone.new(:phone_number => '123 123 3456')).to be_valid expect(USPhone.new(:phone_number => '1231233456')).to be_valid expect(USPhone.new(:phone_number => '123.123.3456')).to be_valid expect(USPhone.new(:phone_number => '(223)123-2347')).to be_valid expect(USPhone.new(:phone_number => "(223)123-2347\n")).not_to be_valid expect(USPhone.new(:phone_number => '(223 123-2347')).not_to be_valid expect(USPhone.new(:phone_number => '12349870238')).not_to be_valid end end describe "ip_address_v4" do class IPAddress < TestActiveRecord attr_accessor :ipv4 validates_formatting_of :ipv4, :using => :ip_address_v4 end it "validates that the IP address provided is valid" do expect(IPAddress.new(:ipv4 => '10.10.10')).not_to be_valid expect(IPAddress.new(:ipv4 => '999.10.10.20')).not_to be_valid expect(IPAddress.new(:ipv4 => '2222.22.22.22')).not_to be_valid expect(IPAddress.new(:ipv4 => '22.2222.22.2')).not_to be_valid expect(IPAddress.new(:ipv4 => '127.0.0.1')).to be_valid expect(IPAddress.new(:ipv4 => '132.254.111.10')).to be_valid expect(IPAddress.new(:ipv4 => "132.254.111.10\n")).not_to be_valid end end # For clarification, NONE of the following numbers are real credit card numbers. # They only match the pattern. These were randomly made for testing. describe "credit_card" do class Client < TestActiveRecord attr_accessor :cc validates_formatting_of :cc, :using => :credit_card end it "validates that the credit card number provided is valid" do expect(Client.new(:cc => '4264-2879-1230-0000')).to be_valid # Visa style expect(Client.new(:cc => '6011-1111-0000-2391')).to be_valid # Discover style expect(Client.new(:cc => '5422434400828888')).to be_valid # Mastercard style expect(Client.new(:cc => "5422434400828889\n")).not_to be_valid # Mastercard style expect(Client.new(:cc => '1233444444444444')).not_to be_valid # fake end end describe "ssn" do class AnotherPerson < TestActiveRecord attr_accessor :ssn validates_formatting_of :ssn end it "validates that the social security number provided is valid" do expect(AnotherPerson.new(:ssn => "145.47.0191")).to be_valid expect(AnotherPerson.new(:ssn => "223-43-2343")).to be_valid expect(AnotherPerson.new(:ssn => "999.55.8888")).to be_valid expect(AnotherPerson.new(:ssn => "999.55.8888\n")).not_to be_valid expect(AnotherPerson.new(:ssn => "28934")).not_to be_valid expect(AnotherPerson.new(:ssn => "228934828934934")).not_to be_valid expect(AnotherPerson.new(:ssn => "23498.7234")).not_to be_valid end end describe "hex_color" do class Color < TestActiveRecord attr_accessor :color validates_formatting_of :color, :using => :hex_color end it "validates that the hex color value provided is valid" do expect(Color.new(:color => "efefef")).to be_valid expect(Color.new(:color => "98de89")).to be_valid expect(Color.new(:color => "000011")).to be_valid expect(Color.new(:color => "132")).to be_valid expect(Color.new(:color => "eef")).to be_valid expect(Color.new(:color => "eef\n")).not_to be_valid expect(Color.new(:color => "efefe")).not_to be_valid expect(Color.new(:color => "zsdfsd")).not_to be_valid expect(Color.new(:color => "p98hul;")).not_to be_valid expect(Color.new(:color => "sdfsdfsf")).not_to be_valid end end describe "validation options" do class Phony < TestActiveRecord attr_accessor :phone, :phone2 validates_formatting_of :phone, :using => :us_phone, :on => :create validates_formatting_of :phone2, :using => :us_phone, :on => :update end it "validates the phone formatting only on creation" do option = Phony.new(:phone => "(123) 234-4567") expect(option).to be_valid option.phone = "123123123" expect(option).to be_valid end class Iffy < TestActiveRecord attr_accessor :name, :phone validates_presence_of :name validates_formatting_of :phone, :using => :us_phone, :if => lambda { |iffy| iffy.name == "Matthew" } end it "validates the phone formatting only if a name is specified" do expect(Iffy.new(:phone => "(123 345-4567", :name => "Bill")).to be_valid expect(Iffy.new(:phone => "(123 345-4567", :name => "Matthew")).not_to be_valid end class Unlessy < TestActiveRecord attr_accessor :name, :phone validates_presence_of :name validates_formatting_of :phone, :using => :us_phone, :unless => lambda { |unlessy| unlessy.name == "Matthew" } end it "validates the phone formatting only if a name is specified" do expect(Unlessy.new(:phone => "(123 345-4567", :name => "Bill")).not_to be_valid expect(Unlessy.new(:phone => "(123 345-4567", :name => "Matthew")).to be_valid end end describe "dollars" do class Money < TestActiveRecord attr_accessor :amount validates_formatting_of :amount, :using => :dollars end it "validates that the dollars amount provided is valid" do expect(Money.new(:amount => "$100.00")).to be_valid expect(Money.new(:amount => "100.00")).to be_valid expect(Money.new(:amount => "12,234,343")).to be_valid expect(Money.new(:amount => "$12.34")).to be_valid expect(Money.new(:amount => "120,123,232.32")).to be_valid expect(Money.new(:amount => "$$1111111100")).not_to be_valid expect(Money.new(:amount => "100;00")).not_to be_valid expect(Money.new(:amount => "238,3423,42..99")).not_to be_valid expect(Money.new(:amount => "$-233")).not_to be_valid end end describe "custom messages" do class Message < TestActiveRecord attr_accessor :first_name validates_formatting_of :first_name, :using => :alpha, :message => "is not a valid first name" end it "are allowed and can be used in displaying error messages" do message = Message.new(:first_name => "invalid-first-name-123") expect(message).not_to be_valid expect(message.errors.keys.class).to eq Array expect(message.errors.full_messages.first).to match(/is not a valid first name/) end end describe "default error messages" do class Problems < TestActiveRecord attr_accessor :name validates_formatting_of :name, :using => :alpha end it "set a default error" do problems = Problems.new(:name => "sdfs12312dfsd") expect(problems).not_to be_valid expect(problems.errors.full_messages.first).to match(/letters/i) email = Email.new(:email => "not.an.email.address") expect(email).not_to be_valid expect(email.errors.full_messages.first).to match(/email/i) end end describe "nil and blank values" do class PeopleTest < TestActiveRecord attr_accessor :email, :email2, :email3 validates_formatting_of :email, :allow_nil => true validates_formatting_of :email2, :using => :email, :allow_blank => true validates_formatting_of :email3, :using => :email end let(:people) { PeopleTest.new(:email => "mbridges.91@gmail.com", :email2 => "mbridges.91@gmail.com", :email3 => "mbridges.91@gmail.com") } it "should test nil and blank values correctly" do people.email = nil expect(people).to be_valid people.email = "mbridges.91@gmail.com" people.email2 = "" expect(people).to be_valid people.email2 = "mbridges.91@gmail.com" people.email3 = nil expect(people).not_to be_valid end end end
mit
rrozewsk/OurProject
UnitTests/test_corporateRates.py
1403
from datetime import date from unittest import TestCase import numpy as np import pandas as pd from Curves.Corporates.CorporateDaily import CorporateRates from parameters import WORKING_DIR periods = '1Y' freq = '1M' t_step = 1.0 / 365.0 simNumber = 10 start = date(2005, 3, 30) trim_start = date(2000, 1, 1) trim_end = date(2010, 12, 31) referenceDate = date(2005, 3, 30) xR = [2.0, 0.05, 0.01, 0.07] # CashFlow Dates myCorp = CorporateRates() myCorp.getCorporates(trim_start, trim_end) myCorp.pickleMe() scheduleComplete = pd.date_range(start=trim_start,end=trim_end) class TestCorporateRates(TestCase): def test_getOIS(self): OIS = myCorp.getOISData(datelist=scheduleComplete) print('AAA', np.shape(OIS)) def test_getCorporateData1(self): AAA = myCorp.getCorporateData(rating='AAA') print(np.shape(AAA)) def test_getCorporateData2(self): OIS = myCorp.getCorporateData(rating='OIS', datelist=scheduleComplete) print('OIS', np.shape(OIS)) def test_pickleMe(self): return fileName = WORKING_DIR + '/myCorp' myCorp.pickleMe(fileName) def test_unPickleMe(self): fileName = WORKING_DIR + '/myCorp.dat' myCorp.unPickleMe(fileName) def test_saveMeExcel(self): fileName = WORKING_DIR + '/myCorp.xlsx' myCorp.saveMeExcel(whichdata=myCorp.corporates, fileName=fileName)
mit
5t111111/tapp
lib/tapp/printer/pretty_print.rb
318
require 'tapp/printer' module Tapp::Printer class PrettyPrint < Base def print(*args) require 'pp' self.class.class_eval do remove_method :print def print(*args) pp(*args) end end print(*args) end end register :pretty_print, PrettyPrint end
mit
MetaMemoryT/node-libcurl
test/main.js
1076
function importTest( name, path, only, skip ) { if ( typeof only == 'undefined' ) only = false; if ( typeof skip == 'undefined' ) skip = false; only = !!only; skip = !!skip; if ( only ) { describe.only( name, function () { require( path ); }); } else if ( skip ) { describe.skip( name, function () { require( path ); }); } else { describe( name, function () { require( path ); }); } } describe( 'Curl', function () { importTest( 'Connection timeout', './curl/connection-timeout' ); importTest( 'setOpt()', './curl/setopt' ); importTest( 'getInfo()', './curl/getinfo' ); importTest( 'reset()', './curl/reset' ); importTest( 'feature()', './curl/feature' ); importTest( 'events', './curl/events' ); importTest( 'Post Fields', './curl/postfields' ); importTest( 'HTTP Auth', './curl/httpauth' ); importTest( 'HTTP Post', './curl/httppost' ); importTest( 'Binary Data', './curl/binary-data' ); });
mit
lrt/lrt
vendor/gedmo/doctrine-extensions/lib/Gedmo/Loggable/Mapping/Driver/Annotation.php
3766
<?php namespace Gedmo\Loggable\Mapping\Driver; use Doctrine\ORM\Mapping\ClassMetadata; use Gedmo\Mapping\Driver\AbstractAnnotationDriver, Gedmo\Exception\InvalidMappingException; /** * This is an annotation mapping driver for Loggable * behavioral extension. Used for extraction of extended * metadata from Annotations specificaly for Loggable * extension. * * @author Boussekeyt Jules <jules.boussekeyt@gmail.com> * @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com> * @package Gedmo.Loggable.Mapping.Driver * @subpackage Annotation * @link http://www.gediminasm.org * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ class Annotation extends AbstractAnnotationDriver { /** * Annotation to define that this object is loggable */ const LOGGABLE = 'Gedmo\\Mapping\\Annotation\\Loggable'; /** * Annotation to define that this property is versioned */ const VERSIONED = 'Gedmo\\Mapping\\Annotation\\Versioned'; /** * {@inheritDoc} */ public function validateFullMetadata(ClassMetadata $meta, array $config) { if ($config && is_array($meta->identifier) && count($meta->identifier) > 1) { throw new InvalidMappingException("Loggable does not support composite identifiers in class - {$meta->name}"); } if (isset($config['versioned']) && !isset($config['loggable'])) { throw new InvalidMappingException("Class must be annoted with Loggable annotation in order to track versioned fields in class - {$meta->name}"); } } /** * {@inheritDoc} */ public function readExtendedMetadata($meta, array &$config) { $class = $this->getMetaReflectionClass($meta); // class annotations if ($annot = $this->reader->getClassAnnotation($class, self::LOGGABLE)) { $config['loggable'] = true; if ($annot->logEntryClass) { if (!class_exists($annot->logEntryClass)) { throw new InvalidMappingException("LogEntry class: {$annot->logEntryClass} does not exist."); } $config['logEntryClass'] = $annot->logEntryClass; } } // property annotations foreach ($class->getProperties() as $property) { if ($meta->isMappedSuperclass && !$property->isPrivate() || $meta->isInheritedField($property->name) || isset($meta->associationMappings[$property->name]['inherited']) ) { continue; } // versioned property if ($versioned = $this->reader->getPropertyAnnotation($property, self::VERSIONED)) { $field = $property->getName(); if ($meta->isCollectionValuedAssociation($field)) { throw new InvalidMappingException("Cannot versioned [{$field}] as it is collection in object - {$meta->name}"); } // fields cannot be overrided and throws mapping exception $config['versioned'][] = $field; } } if (!$meta->isMappedSuperclass && $config) { if (is_array($meta->identifier) && count($meta->identifier) > 1) { throw new InvalidMappingException("Loggable does not support composite identifiers in class - {$meta->name}"); } if (isset($config['versioned']) && !isset($config['loggable'])) { throw new InvalidMappingException("Class must be annoted with Loggable annotation in order to track versioned fields in class - {$meta->name}"); } } } }
mit
shaunstanislaus/phaser
src/pixi/renderers/webgl/WebGLShaders.js
3171
/** * @author Mat Groves http://matgroves.com/ @Doormat23 */ PIXI.initDefaultShaders = function() { PIXI.primitiveShader = new PIXI.PrimitiveShader(); PIXI.primitiveShader.init(); PIXI.stripShader = new PIXI.StripShader(); PIXI.stripShader.init(); PIXI.defaultShader = new PIXI.PixiShader(); PIXI.defaultShader.init(); var gl = PIXI.gl; var shaderProgram = PIXI.defaultShader.program; gl.useProgram(shaderProgram); gl.enableVertexAttribArray(PIXI.defaultShader.aVertexPosition); gl.enableVertexAttribArray(PIXI.defaultShader.colorAttribute); gl.enableVertexAttribArray(PIXI.defaultShader.aTextureCoord); }; PIXI.activatePrimitiveShader = function() { var gl = PIXI.gl; gl.useProgram(PIXI.primitiveShader.program); gl.disableVertexAttribArray(PIXI.defaultShader.aVertexPosition); gl.disableVertexAttribArray(PIXI.defaultShader.colorAttribute); gl.disableVertexAttribArray(PIXI.defaultShader.aTextureCoord); gl.enableVertexAttribArray(PIXI.primitiveShader.aVertexPosition); gl.enableVertexAttribArray(PIXI.primitiveShader.colorAttribute); }; PIXI.deactivatePrimitiveShader = function() { var gl = PIXI.gl; gl.useProgram(PIXI.defaultShader.program); gl.disableVertexAttribArray(PIXI.primitiveShader.aVertexPosition); gl.disableVertexAttribArray(PIXI.primitiveShader.colorAttribute); gl.enableVertexAttribArray(PIXI.defaultShader.aVertexPosition); gl.enableVertexAttribArray(PIXI.defaultShader.colorAttribute); gl.enableVertexAttribArray(PIXI.defaultShader.aTextureCoord); }; PIXI.activateStripShader = function() { var gl = PIXI.gl; gl.useProgram(PIXI.stripShader.program); // gl.disableVertexAttribArray(PIXI.defaultShader.aTextureCoord); }; PIXI.deactivateStripShader = function() { var gl = PIXI.gl; gl.useProgram(PIXI.defaultShader.program); //gl.enableVertexAttribArray(PIXI.defaultShader.aTextureCoord); }; /* SHADER COMPILER HELPERS */ PIXI.CompileVertexShader = function(gl, shaderSrc) { return PIXI._CompileShader(gl, shaderSrc, gl.VERTEX_SHADER); }; PIXI.CompileFragmentShader = function(gl, shaderSrc) { return PIXI._CompileShader(gl, shaderSrc, gl.FRAGMENT_SHADER); }; PIXI._CompileShader = function(gl, shaderSrc, shaderType) { var src = shaderSrc.join("\n"); var shader = gl.createShader(shaderType); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { window.console.log(gl.getShaderInfoLog(shader)); return null; } return shader; }; PIXI.compileProgram = function(vertexSrc, fragmentSrc) { var gl = PIXI.gl; var fragmentShader = PIXI.CompileFragmentShader(gl, fragmentSrc); var vertexShader = PIXI.CompileVertexShader(gl, vertexSrc); var shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, vertexShader); gl.attachShader(shaderProgram, fragmentShader); gl.linkProgram(shaderProgram); if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { window.console.log("Could not initialise shaders"); } return shaderProgram; };
mit
lefela4/agario-clientv4
examples/socks.js
3539
//This is example of connection to agar.io's server through SOCKS4/SOCKS5 server if(process.argv.length < 5) { var warning = [ 'Please launch this script like', ' node ./examples/socks.js SOCKS_VERSION SOCKS_IP SOCKS_PORT', 'SOCKS_IP - IP of SOCKS server', 'SOCKS_PORT - port of SOCKS server', 'SOCKS_VERSION - SOCKS server version. 4/4a/5. You can use "4" for "4a"', '*This script uses `socks` lib and this is params used by lib', ]; for (var line in warning) console.log( warning[line] ); process.exit(0); } console.log('Example will use SOCKS server ' + process.argv[3] + ':' + process.argv[4] + ' version ' + process.argv[2]); //First we need to create agent for connection, you can do it any way with any lib you want. //I will use `socks` lib https://www.npmjs.com/package/socks //var Socks = require('socks'); //DO THIS, not what i do var Socks; try { Socks = require('socks'); } catch(e) { var warning = [ 'Failed to load `socks` lib. Install it in examples path using:', ' mkdir ./node_modules/examples/node_modules', ' npm install socks --prefix ./node_modules/agario-client/examples', ' node ./node_modules/agario-client/examples/socks.js' ]; for (var line in warning) console.log( warning[line] ); process.exit(0); } //And we need agario-client var AgarioClient = require('../agario-client.js'); //Use next line in your code //var AgarioClient = require('agario-client'); //Use this in your code //We will need to create new agent for every new connection so we will make function function createAgent() { return new Socks.Agent({ proxy: { ipaddress: process.argv[3], port: parseInt(process.argv[4]), type: parseInt(process.argv[2]) }} ); } //Here is main code //You need to request server/key and connect to that server from same IP //So you need to request server/key through same SOCKS server that you will be connecting from //Create new agent var agent = createAgent(); //Options for getFFAServer var get_server_opt = { region: 'EU-London', //server region agent: agent //our agent }; //SOCKS version 4 do not accept domain names, we will need to resolve it //SOCKS version 4a and 5 can accept domain names as targets if(process.argv[2] == '4') { get_server_opt.resolve = true; } //Requesting server's IP and key AgarioClient.servers.getFFAServer(get_server_opt, function(srv) { if(!srv.server) { console.log('Failed to request server (error=' + srv.error + ', error_source=' + srv.error_source + ')'); process.exit(0); } console.log('Got agar.io server ' + srv.server + ' with key ' + srv.key); //Here we already have server and key requested through SOCKS server //Now we will create agario-client var client = new AgarioClient('worker'); client.debug = 2; //Create new agent for client client.agent = createAgent(); client.on('leaderBoardUpdate', function(old_highlights, highlights, old_names, names) { client.log('Leaders on server: ' + names.join(', ')); console.log('[SUCCESS!] Example succesfully connected to server through SOCKS server and received data. Example is over.'); client.disconnect(); }); //Connecting to server client.connect('ws://' + srv.server, srv.key); });
mit
kataras/gapi
core/router/router_subdomain_redirect.go
9393
package router import ( "fmt" "net/http" "strconv" "strings" "text/template" "unicode/utf8" "github.com/kataras/iris/v12/context" "github.com/kataras/iris/v12/core/netutil" ) type subdomainRedirectWrapper struct { // the func which will give us the root domain, // it's declared as a func because in that state the application is not configurated neither ran yet. root func() string // the from and to locations, if subdomains must end with dot('.'). from, to string // true if from wildcard subdomain is given by 'from' ("*." or '*'). isFromAny bool // true for the location that is the root domain ('/', '.' or ""). isFromRoot, isToRoot bool } func pathIsRootDomain(partyRelPath string) bool { return partyRelPath == "/" || partyRelPath == "" || partyRelPath == "." } func pathIsWildcard(partyRelPath string) bool { return partyRelPath == SubdomainWildcardIndicator || partyRelPath == "*" } // NewSubdomainRedirectWrapper returns a router wrapper which // if it's registered to the router via `router#WrapRouter` it // redirects(StatusMovedPermanently) a subdomain or the root domain to another subdomain or to the root domain. // // It receives three arguments, // the first one is a function which returns the root domain, (in the application it's the app.ConfigurationReadOnly().GetVHost()). // The second and third are the from and to locations, 'from' can be a wildcard subdomain as well (*. or *) // 'to' is not allowed to be a wildcard for obvious reasons, // 'from' can be the root domain when the 'to' is not the root domain and visa-versa. // To declare a root domain as 'from' or 'to' you MUST pass an empty string or a slash('/') or a dot('.'). // Important note: the 'from' and 'to' should end with "." like we use the `APIBuilder#Party`, if they are subdomains. // // Usage(package-level): // sd := NewSubdomainRedirectWrapper(func() string { return "mydomain.com" }, ".", "www.") // router.AddRouterWrapper(sd) // // Usage(high-level using `iris#Application.SubdomainRedirect`) // www := app.Subdomain("www") // app.SubdomainRedirect(app, www) // Because app's rel path is "/" it translates it to the root domain // and www's party's rel path is the "www.", so it's the target subdomain. // // All the above code snippets will register a router wrapper which will // redirect all http(s)://mydomain.com/%anypath% to http(s)://www.mydomain.com/%anypath%. // // One or more subdomain redirect wrappers can be used to the same router instance. // // NewSubdomainRedirectWrapper may return nil if not allowed input arguments values were received // but in that case, the `AddRouterWrapper` will, simply, ignore that wrapper. // // Example: https://github.com/kataras/iris/tree/master/_examples/routing/subdomains/redirect func NewSubdomainRedirectWrapper(rootDomainGetter func() string, from, to string) WrapperFunc { // we can return nil, // because if wrapper is nil then it's not be used on the `router#AddRouterWrapper`. if from == to { // cannot redirect to the same location, cycle. return nil } if pathIsWildcard(to) { // cannot redirect to "any location". return nil } isFromRoot, isToRoot := pathIsRootDomain(from), pathIsRootDomain(to) if isFromRoot && isToRoot { // cannot redirect to the root domain from the root domain. return nil } sd := &subdomainRedirectWrapper{ root: rootDomainGetter, from: from, to: to, isFromAny: pathIsWildcard(from), isFromRoot: isFromRoot, isToRoot: isToRoot, } return sd.Wrapper } // Wrapper is the function that is being used to wrap the router with a redirect // service that is able to redirect between (sub)domains as fast as possible. // Please take a look at the `NewSubdomainRedirectWrapper` function for more. func (s *subdomainRedirectWrapper) Wrapper(w http.ResponseWriter, r *http.Request, router http.HandlerFunc) { // Author's note: // I use the StatusMovedPermanently(301) instead of the the StatusPermanentRedirect(308) // because older browsers may not be able to recognise that status code (the RFC 7538, is not so old) // although note that move is not the same thing as redirect: move reminds a specific address or location moved while // redirect is a new location. host := context.GetHost(r) root := s.root() if loopback := netutil.GetLoopbackSubdomain(root); loopback != "" { root = strings.Replace(root, loopback, context.GetDomain(host), 1) } hasSubdomain := host != root if !hasSubdomain && !s.isFromRoot { // if the current endpoint is not a subdomain // and the redirect is not configured to be used from root domain to a subdomain. // This check comes first because it's the most common scenario. router(w, r) return } if hasSubdomain { // the current endpoint is a subdomain and // redirect is used for a subdomain to another subdomain or to its root domain. subdomain := strings.TrimSuffix(host, root) // with dot '.'. if s.to == subdomain { // we are in the subdomain we wanted to be redirected, // remember: a redirect response will fire a new request. // This check is needed to not allow cycles (too many redirects). router(w, r) return } if subdomain == s.from || s.isFromAny { resturi := r.URL.RequestURI() if s.isToRoot { // from a specific subdomain or any subdomain to the root domain. RedirectAbsolute(w, r, context.GetScheme(r)+root+resturi, http.StatusMovedPermanently) return } // from a specific subdomain or any subdomain to a specific subdomain. RedirectAbsolute(w, r, context.GetScheme(r)+s.to+root+resturi, http.StatusMovedPermanently) return } /* Think of another way. As it's a breaking change. if s.isFromRoot && !s.isFromAny { // Then we must not continue, // the subdomain didn't match the "to" but the from // was the application root itself, which is not a wildcard // so it shouldn't accept any subdomain, we must fire 404 here. // Something like: // http://registered_host_but_not_in_app.your.mydomain.com http.NotFound(w, r) return } */ // the from subdomain is not matched and it's not from root. router(w, r) return } if s.isFromRoot { resturi := r.URL.RequestURI() // we are not inside a subdomain, so we are in the root domain // and the redirect is configured to be used from root domain to a subdomain. RedirectAbsolute(w, r, context.GetScheme(r)+s.to+root+resturi, http.StatusMovedPermanently) return } router(w, r) } // NewSubdomainPartyRedirectHandler returns a handler which can be registered // through `UseRouter` or `Use` to redirect from the current request's // subdomain to the one which the given `to` Party can handle. func NewSubdomainPartyRedirectHandler(to Party) context.Handler { return NewSubdomainRedirectHandler(to.GetRelPath()) } // NewSubdomainRedirectHandler returns a handler which can be registered // through `UseRouter` or `Use` to redirect from the current request's // subdomain to the given "toSubdomain". func NewSubdomainRedirectHandler(toSubdomain string) context.Handler { toSubdomain, _ = splitSubdomainAndPath(toSubdomain) // let it here so users can just pass the GetRelPath of a Party. if pathIsWildcard(toSubdomain) { return nil } return func(ctx *context.Context) { // en-us.test.mydomain.com host := ctx.Host() fullSubdomain := ctx.SubdomainFull() targetHost := strings.Replace(host, fullSubdomain, toSubdomain, 1) // resturi := ctx.Request().URL.RequestURI() // urlToRedirect := ctx.Scheme() + newHost + resturi r := ctx.Request() r.Host = targetHost r.URL.Host = targetHost urlToRedirect := r.URL.String() RedirectAbsolute(ctx.ResponseWriter(), r, urlToRedirect, http.StatusMovedPermanently) } } // RedirectAbsolute replies to the request with a redirect to an absolute URL. // // The provided code should be in the 3xx range and is usually // StatusMovedPermanently, StatusFound or StatusSeeOther. // // If the Content-Type header has not been set, Redirect sets it // to "text/html; charset=utf-8" and writes a small HTML body. // Setting the Content-Type header to any value, including nil, // disables that behavior. func RedirectAbsolute(w http.ResponseWriter, r *http.Request, url string, code int) { h := w.Header() // RFC 7231 notes that a short HTML body is usually included in // the response because older user agents may not understand 301/307. // Do it only if the request didn't already have a Content-Type header. _, hadCT := h[context.ContentTypeHeaderKey] h.Set("Location", hexEscapeNonASCII(url)) if !hadCT && (r.Method == http.MethodGet || r.Method == http.MethodHead) { h.Set(context.ContentTypeHeaderKey, "text/html; charset=utf-8") } w.WriteHeader(code) // Shouldn't send the body for POST or HEAD; that leaves GET. if !hadCT && r.Method == "GET" { body := "<a href=\"" + template.HTMLEscapeString(url) + "\">" + http.StatusText(code) + "</a>.\n" fmt.Fprintln(w, body) } } func hexEscapeNonASCII(s string) string { // part of the standard library. newLen := 0 for i := 0; i < len(s); i++ { if s[i] >= utf8.RuneSelf { newLen += 3 } else { newLen++ } } if newLen == len(s) { return s } b := make([]byte, 0, newLen) for i := 0; i < len(s); i++ { if s[i] >= utf8.RuneSelf { b = append(b, '%') b = strconv.AppendInt(b, int64(s[i]), 16) } else { b = append(b, s[i]) } } return string(b) }
mit
standard-analytics/mesh-tree
export/exportPropertiesObjects.js
660
let fs = require('fs'); let _ = require('lodash'); let Promise = require('bluebird'); let MeshTree = require('../dist'); let meshTree = new MeshTree(); const MESH = 'http://id.nlm.nih.gov/mesh/'; (Promise.coroutine(function* () { let objs = {}; let ids = yield meshTree.getAllDescUIs({ format: 'rdf' }); for (let id of ids) { console.log(id); let obj = yield meshTree.createPropertiesObject({ '@id': id, properties: ['name','description','synonyms','schemaOrgType','codeValue','codingSystem'] }); objs[id.replace(MESH, '')] = obj; } fs.writeFileSync('mesh_properties_objects.json', JSON.stringify(objs), 'utf8'); }))();
mit
fireball-packages/console
test/renderer/basic.js
1988
'use strict'; describe('Basic', function() { Helper.runPanel( 'console.panel' ); it('should recv ipc "console:log"', function() { let targetEL = Helper.targetEL; Helper.send('console:log', 'foo bar'); expect(targetEL.logs[0] ).to.deep.equal({ type: 'log', text: 'foo bar', desc: 'foo bar', detail: '', count: 0, }); }); it('should recv ipc "console:warn"', function() { let targetEL = Helper.targetEL; Helper.send('console:warn', 'foo bar'); expect(targetEL.logs[0] ).to.deep.equal({ type: 'warn', text: 'foo bar', desc: 'foo bar', detail: '', count: 0, }); }); it('should recv ipc "console:error"', function() { let targetEL = Helper.targetEL; Helper.send('console:error', 'foo bar'); expect(targetEL.logs[0] ).to.deep.equal({ type: 'error', text: 'foo bar', desc: 'foo bar', detail: '', count: 0, }); }); it('should recv logs in order', function() { let targetEL = Helper.targetEL; Helper.send('console:log', 'foobar 01'); Helper.send('console:log', 'foobar 02'); Helper.send('console:error', 'foobar 03 error'); Helper.send('console:warn', 'foobar 04 warn'); Helper.send('console:log', 'foobar 05'); expect( targetEL.logs[0] ).to.have.property( 'text', 'foobar 01' ); expect( targetEL.logs[1] ).to.have.property( 'text', 'foobar 02' ); expect( targetEL.logs[2] ).to.have.property( 'text', 'foobar 03 error' ); expect( targetEL.logs[3] ).to.have.property( 'text', 'foobar 04 warn' ); expect( targetEL.logs[4] ).to.have.property( 'text', 'foobar 05' ); }); it('should recv ipc "console:clear"', function() { let targetEL = Helper.targetEL; Helper.send('console:log', 'foobar 01'); Helper.send('console:log', 'foobar 02'); Helper.send('console:log', 'foobar 03'); Helper.send('console:clear'); expect( targetEL.logs.length ).to.equal(0); }); });
mit
zaoying/EChartsAnnotation
src/cn/edu/gdut/zaoying/Option/series/funnel/markLine/data/p0/SymbolString.java
357
package cn.edu.gdut.zaoying.Option.series.funnel.markLine.data.p0; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface SymbolString { String value() default ""; }
mit
packlnd/IFDS-RA
src/main/java/flow/twist/propagator/backwards/ArgumentSourceHandler.java
2131
package flow.twist.propagator.backwards; import static flow.twist.ifds.Propagator.KillGenInfo.identity; import soot.Local; import soot.SootMethod; import soot.Unit; import soot.Value; import soot.jimple.IdentityStmt; import soot.jimple.ParameterRef; import soot.jimple.Stmt; import flow.twist.TransitiveSinkCaller; import flow.twist.config.AnalysisContext; import flow.twist.ifds.Propagator; import flow.twist.reporter.Report; import flow.twist.trackable.Taint; import flow.twist.trackable.Trackable; import flow.twist.util.AnalysisUtil; public class ArgumentSourceHandler implements Propagator { private final AnalysisContext context; private TransitiveSinkCaller transitiveSinkCaller; public ArgumentSourceHandler(AnalysisContext context, TransitiveSinkCaller transitiveSinkCaller) { this.context = context; this.transitiveSinkCaller = transitiveSinkCaller; } @Override public boolean canHandle(Trackable taint) { return taint instanceof Taint; } @Override public KillGenInfo propagateNormalFlow(Trackable taint, Unit curr, Unit succ) { if (!(curr instanceof IdentityStmt)) return identity(); IdentityStmt idStmt = (IdentityStmt) curr; Value left = AnalysisUtil.getBackwardsBase(idStmt.getLeftOp()); Taint t = (Taint) taint; if (!AnalysisUtil.maybeSameLocation(t.value, left)) return identity(); if (idStmt.getRightOp() instanceof ParameterRef) { if (t.value instanceof Local) { SootMethod m = context.icfg.getMethodOf(idStmt); if (AnalysisUtil.methodMayBeCallableFromApplication(m) && transitiveSinkCaller.isTransitiveCallerOfAnySink(m)) { context.reporter.reportTrackable(new Report(context, taint, curr)); } } } return identity(); } @Override public KillGenInfo propagateCallFlow(Trackable taint, Unit callStmt, SootMethod destinationMethod) { return identity(); } @Override public KillGenInfo propagateReturnFlow(Trackable taint, Unit callSite, SootMethod calleeMethod, Unit exitStmt, Unit returnSite) { return identity(); } @Override public KillGenInfo propagateCallToReturnFlow(Trackable taint, Stmt callSite) { return identity(); } }
mit
vuejs/vue-validator
test/unit/components/validity-group-functional.test.js
8101
import ValidityControl from '../../../src/components/validity/index' import ValidityGroup from '../../../src/components/validity-group.js' const validityControl = ValidityControl(Vue) const validityGroup = ValidityGroup(Vue) describe('validity-group functional component', () => { let el const components = { validityControl, 'validity-group': validityGroup, comp: { data () { return { value: 'hello' } }, render (h) { return h('input', { attrs: { type: 'text' }}) } }, 'comp-input': { props: ['options', 'value'], mounted () { this._handle = e => { this.$emit('input', e.target.value) } this.$el.addEventListener('change', this._handle) }, destroyed () { this.$el.removeEventListener('change', this._handle) }, render (h) { const options = this.options.map((option, index) => { return h('option', { ref: `option${index + 1}`, domProps: { value: option.value }}, [option.text]) }) return h('select', { ref: 'select' }, options) } } } beforeEach(() => { el = document.createElement('div') }) describe('rendering', () => { describe('default', () => { it('should be render with fieldset tag', () => { const vm = new Vue({ components, render (h) { return h('div', [ h('validity-group', { props: { field: 'field1', validators: ['required'] } }, [ h('input', { attrs: { type: 'radio', name: 'group', value: 'one' }}), h('input', { attrs: { type: 'radio', name: 'group', value: 'two' }}), h('input', { attrs: { type: 'radio', name: 'group', value: 'three' }}) ]) ]) } }).$mount(el) assert.equal(vm.$el.outerHTML, '<div><fieldset class="untouched pristine"><input type="radio" name="group" value="one"><input type="radio" name="group" value="two"><input type="radio" name="group" value="three"></fieldset></div>') }) }) describe('tag specify', () => { it('should be render with specify tag', () => { const vm = new Vue({ components, render (h) { return h('div', [ h('validity-group', { props: { tag: 'header', field: 'field1', validators: ['required'] } }, [ h('input', { attrs: { type: 'radio', name: 'group', value: 'one' }}), h('input', { attrs: { type: 'radio', name: 'group', value: 'two' }}), h('input', { attrs: { type: 'radio', name: 'group', value: 'three' }}) ]) ]) } }).$mount(el) assert.equal(vm.$el.outerHTML, '<div><header class="untouched pristine"><input type="radio" name="group" value="one"><input type="radio" name="group" value="two"><input type="radio" name="group" value="three"></header></div>') }) }) }) describe('validate', () => { describe('checkbox', () => { it('should be work', done => { const vm = new Vue({ components, render (h) { return h('div', [ h('validity-group', { props: { field: 'field1', validators: { required: true, minlength: 2 } }, ref: 'validity' }, [ h('input', { ref: 'checkbox1', attrs: { type: 'checkbox', value: 'one' }}), h('input', { ref: 'checkbox2', attrs: { type: 'checkbox', value: 'two' }}), h('input', { ref: 'checkbox3', attrs: { type: 'checkbox', value: 'three' }}) ]) ]) } }).$mount(el) const { validity, checkbox1, checkbox2, checkbox3 } = vm.$refs let result waitForUpdate(() => { validity.validate() // validate !! }).thenWaitFor(1).then(() => { result = validity.result assert(result.required === true) assert(result.minlength === true) assert.deepEqual(result.errors, [{ field: 'field1', validator: 'required' }, { field: 'field1', validator: 'minlength' }]) assert(validity.valid === false) assert(validity.invalid === true) assert(result.valid === false) assert(result.invalid === true) }).then(() => { checkbox1.checked = true validity.validate() // validate !! }).thenWaitFor(1).then(() => { result = validity.result assert(result.required === false) assert(result.minlength === true) assert.deepEqual(result.errors, [{ field: 'field1', validator: 'minlength' }]) assert(validity.valid === false) assert(validity.invalid === true) assert(result.valid === false) assert(result.invalid === true) }).then(() => { checkbox2.checked = true checkbox3.checked = true validity.validate() // validate !! }).thenWaitFor(1).then(() => { result = validity.result assert(result.required === false) assert(result.minlength === false) assert(result.errors === undefined) assert(validity.valid === true) assert(validity.invalid === false) assert(result.valid === true) assert(result.invalid === false) }).then(done) }) }) describe('radio', () => { it('should be work', done => { const vm = new Vue({ components, render (h) { return h('div', [ h('validity-group', { props: { field: 'field1', validators: ['required'] }, ref: 'validity' }, [ h('input', { ref: 'radio1', attrs: { type: 'radio', name: 'group', value: 'one' }}), h('input', { ref: 'radio2', attrs: { type: 'radio', name: 'group', value: 'two' }}), h('input', { ref: 'radio3', attrs: { type: 'radio', name: 'group', value: 'three' }}) ]) ]) } }).$mount(el) const { validity, radio1, radio2, radio3 } = vm.$refs let result waitForUpdate(() => { validity.validate() // validate !! }).thenWaitFor(1).then(() => { result = validity.result assert(result.required === true) assert.deepEqual(result.errors, [{ field: 'field1', validator: 'required' }]) assert(validity.valid === false) assert(validity.invalid === true) assert(result.valid === false) assert(result.invalid === true) }).then(() => { radio1.checked = true validity.validate() // validate !! }).thenWaitFor(1).then(() => { result = validity.result assert(result.required === false) assert(result.errors === undefined) assert(validity.valid === true) assert(validity.invalid === false) assert(result.valid === true) assert(result.invalid === false) }).then(() => { radio1.checked = false radio2.checked = false radio3.checked = true validity.validate() // validate !! }).thenWaitFor(1).then(() => { result = validity.result assert(result.required === false) assert(result.errors === undefined) assert(validity.valid === true) assert(validity.invalid === false) assert(result.valid === true) assert(result.invalid === false) }).then(done) }) }) }) })
mit
korayguney/veteranteam_project
src/views/shows/shows-view.js
789
import ListView from './list-view'; import { View, ViewManager, NavBar, __ } from 'erste'; export default class ShowsView extends View { constructor() { super(); this.vm = new ViewManager(this); this.listView = new ListView(this.vm); this.navBar = new NavBar({ title: __('Top Shows'), hasMenuButton: true, hasBackButton: true }); this.navBar.vm = this.vm; } onAfterRender() { super.onAfterRender(); this.vm.setCurrentView(this.listView); } onActivation() { if (cfg.PLATFORM == 'device') StatusBar.styleLightContent(); } template() { return ` <view class="shows-view"> ${this.navBar} ${this.listView} </view>`; } }
mit
lianke123321/centinel-server
tests.py
3925
import flask from flask import Flask from flask.ext.testing import TestCase from server import app, db, Client import config #for tests import os from cStringIO import StringIO import unittest import uuid import base64 import io from passlib.apps import custom_app_context as pwd_context class MyTest(TestCase): testUsername = str(uuid.uuid4()) testPassword = 'testingpassword' def create_app(self): self.app = Flask(__name__) self.app.config['TESTING'] = True return app def setUp(self): db.create_all() user = Client(username=self.testUsername,password=self.testPassword) db.session.add(user) db.session.commit() def tearDown(self): db.session.remove() db.drop_all() def open_with_auth(self, url, method, username, password): return self.client.open(url, method=method, headers={ 'Authorization': 'Basic ' + base64.b64encode(username + \ ":" + password) } ) def check_broken_auth(self, url): response = self.client.get(url) self.assert_401(response) self.assertTrue('WWW-Authenticate' in response.headers) self.assertTrue('Basic' in response.headers['WWW-Authenticate']) def test_version(self): url = '/version' response = self.client.get(url) self.assert_200(response) self.assertEquals(response.json, {"version" : config.recommended_version}) def test_results_GET(self): url = '/results' #Check for broken auth -> self.check_broken_auth(url) #Check working auth -> response = self.open_with_auth(url,'GET',self.testUsername, self.testPassword) self.assert_200(response) def test_results_POST(self): url = '/results' with open('testfile','wb') as test_file: test_file.write('Hello Centinels') with open('testfile','r') as test_file: headers={ 'Authorization': 'Basic ' + base64.b64encode(self.testUsername + \ ":" + self.testPassword) } files = {'result' : test_file} response = self.client.post(url, data=files, headers=headers) self.assert_status(response, 201) self.assertTrue(os.path.isfile(os.path.join(config.centinel_home, 'results/testfile'))) os.remove(os.path.join(config.centinel_home, 'results/testfile')) os.remove('testfile') ###X: Testing encoding mismatch? def test_experiments(self): url = '/experiments' response = self.client.get(url) self.assert_200(response) #XXX: Could be expanded? for experiment in response.json["experiments"]: url = '/experiments/{0}'.format(experiment) response_ = self.client.get(url) self.assert_200(response) def test_clients(self): url = '/clients' #Check for broken auth -> self.check_broken_auth(url) #Check working auth -> response = self.open_with_auth(url,'GET',self.testUsername, self.testPassword) self.assert_200(response) self.assertEquals(response.json, {"clients" : [self.testUsername]}) def test_register(self): url = '/register' testUsername = str(uuid.uuid4()) testPassword = 'somepassword' response = self.client.post(url, \ data = flask.json.dumps({'username': testUsername, 'password': testPassword}),\ content_type='application/json') self.assertEquals(response.json, {"status" : "success"}) self.assert_status(response,201) client = Client.query.filter_by(username=testUsername).first() self.assertEquals(client.username, testUsername) self.assertTrue(client.verify_password(testPassword)) if __name__ == '__main__': unittest.main()
mit
vegas-cmf/official
app/modules/Project/services/Gallery.php
696
<?php /** * This file is part of Vegas package * * @author Jaroslaw <Macko> * @copyright Amsterdam Standard Sp. Z o.o. * @homepage http://vegas-cmf.github.io * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Project\Services; use Project\Models\Project; use Vegas\DI\Service\ComponentAbstract; class Gallery extends ComponentAbstract { /** * Setups component * * @param array $params * @return mixed */ protected function setUp($params = []) { return [ 'projects' => Project::find(['sort' => ['contributions' => -1]]) ]; } }
mit
gizwits/Gizwits-AirConditioner_Android
src/com/gizwits/framework/activity/onboarding/AutoConfigActivity.java
7594
/** * Project Name:XPGSdkV4AppBase * File Name:AutoConfigActivity.java * Package Name:com.gizwits.framework.activity.onboarding * Date:2015-1-27 14:45:54 * Copyright (c) 2014~2015 Xtreme Programming Group, Inc. * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.gizwits.framework.activity.onboarding; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.InputType; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.Button; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import android.widget.ToggleButton; import android.widget.AdapterView.OnItemSelectedListener; import com.gizwits.aircondition.R; import com.gizwits.framework.activity.BaseActivity; import com.xpg.common.useful.NetworkUtils; import com.xpg.common.useful.StringUtils; import com.xpg.ui.utils.ToastUtils; // TODO: Auto-generated Javadoc /** * * ClassName: Class AutoConfigActivity. <br/> * 自动配置界面 * <br/> * date: 2014-12-9 17:30:20 <br/> * * @author Lien */ public class AutoConfigActivity extends BaseActivity implements OnClickListener { /** The sp mode */ private Spinner sp_mode; private static int mode_temp; /** The tv ssid. */ private TextView tvSsid; /** The et input psw. */ private EditText etInputPsw; /** The tb psw flag. */ private ToggleButton tbPswFlag; /** The btn next. */ private Button btnNext; /** * The iv back. */ private ImageView ivBack; /** 网络状态广播接受器. */ ConnecteChangeBroadcast mChangeBroadcast = new ConnecteChangeBroadcast(); /** The str ssid. */ private String strSsid; /** The str psw. */ private String strPsw; /** * * ClassName: Enum handler_key. <br/> * <br/> * date: 2014-11-26 17:51:10 <br/> * * @author Lien */ private enum handler_key { /** The change wifi. */ CHANGE_WIFI, } /** The handler. */ Handler handler = new Handler() { /* * (non-Javadoc) * * @see android.os.Handler#handleMessage(android.os.Message) */ public void handleMessage(Message msg) { super.handleMessage(msg); handler_key key = handler_key.values()[msg.what]; switch (key) { case CHANGE_WIFI: strSsid = NetworkUtils .getCurentWifiSSID(AutoConfigActivity.this); tvSsid.setText(getString(R.string.wifi_name) + strSsid); break; } } }; /* * (non-Javadoc) * * @see com.gizwits.aircondition.activity.BaseActivity#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_autoconfig); initViews(); initEvents(); } /** * Inits the views. */ private void initViews() { sp_mode = (Spinner) findViewById(R.id.sp_mode); // tvSsid = (TextView) findViewById(R.id.tvSsid); etInputPsw = (EditText) findViewById(R.id.etInputPsw); tbPswFlag = (ToggleButton) findViewById(R.id.tbPswFlag); btnNext = (Button) findViewById(R.id.btnNext); ivBack=(ImageView) findViewById(R.id.ivBack); } /** * Inits the events. */ private void initEvents() { btnNext.setOnClickListener(this); ivBack.setOnClickListener(this); tbPswFlag.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { etInputPsw.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); } else { etInputPsw.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); } } }); sp_mode.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { mode_temp=position; } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } /* * (non-Javadoc) * * @see android.view.View.OnClickListener#onClick(android.view.View) */ @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnNext: if (!NetworkUtils.isWifiConnected(this)){ ToastUtils.showShort(this, getString(R.string.wifi_first)); break; } if(StringUtils.isEmpty(strSsid)){ ToastUtils.showShort(this, getString(R.string.wifi_first)); break; } Intent intent = new Intent(AutoConfigActivity.this,AirlinkActivity.class); intent.putExtra("ssid", strSsid); intent.putExtra("Temp", mode_temp); strPsw = etInputPsw.getText().toString().trim(); if(!StringUtils.isEmpty(strPsw)){ intent.putExtra("psw", strPsw); }else{ intent.putExtra("psw", ""); } startActivity(intent); finish(); break; case R.id.ivBack: onBackPressed(); break; } } /* (non-Javadoc) * @see com.gizwits.framework.activity.BaseActivity#onResume() */ @Override public void onResume() { super.onResume(); IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(mChangeBroadcast, filter); if (NetworkUtils.isWifiConnected(this)) { handler.sendEmptyMessage(handler_key.CHANGE_WIFI.ordinal()); } } /* (non-Javadoc) * @see android.app.Activity#onPause() */ public void onPause() { super.onPause(); unregisterReceiver(mChangeBroadcast); } @Override public void onBackPressed() { startActivity(new Intent(AutoConfigActivity.this,SearchDeviceActivity.class)); finish(); } /** * 广播监听器,监听wifi连上的广播. * * @author Lien */ public class ConnecteChangeBroadcast extends BroadcastReceiver { /* (non-Javadoc) * @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent) */ @Override public void onReceive(Context context, Intent intent) { boolean iswifi = NetworkUtils.isWifiConnected(context); Log.i("networkchange", "change" + iswifi); if (iswifi) { handler.sendEmptyMessage(handler_key.CHANGE_WIFI.ordinal()); } } } }
mit
dsp2003/GARbro
ArcFormats/FC01/WidgetMCG.xaml.cs
2369
using GameRes.Formats.FC01; using GameRes.Formats.Strings; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Windows.Controls; using System.Windows.Data; namespace GameRes.Formats.GUI { /// <summary> /// Interaction logic for WidgetMCG.xaml /// </summary> public partial class WidgetMCG : StackPanel { public WidgetMCG () { InitializeComponent(); var none = new KeyValuePair<string, byte>[] { new KeyValuePair<string, byte> (arcStrings.ArcIgnoreEncryption, 0) }; Title.ItemsSource = none.Concat (McgFormat.KnownKeys.OrderBy (x => x.Key)); } public byte GetKey () { return ByteKeyConverter.StringToByte (this.Passkey.Text); } } internal static class ByteKeyConverter { public static string ByteToString (object value) { byte key = (byte)value; return key.ToString ("X2", CultureInfo.InvariantCulture); } public static byte StringToByte (object value) { string s = value as string; if (string.IsNullOrEmpty (s)) return 0; byte key; if (!byte.TryParse (s, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out key)) return 0; return key; } } [ValueConversion (typeof (byte), typeof (string))] class ByteToStringConverter : IValueConverter { public object Convert (object value, Type targetType, object parameter, CultureInfo culture) { return ByteKeyConverter.ByteToString (value); } public object ConvertBack (object value, Type targetType, object parameter, CultureInfo culture) { return ByteKeyConverter.StringToByte (value); } } [ValueConversion (typeof (string), typeof (byte))] class StringToByteConverter : IValueConverter { public object Convert (object value, Type targetType, object parameter, CultureInfo culture) { return ByteKeyConverter.StringToByte (value); } public object ConvertBack (object value, Type targetType, object parameter, CultureInfo culture) { return ByteKeyConverter.ByteToString (value); } } }
mit
ahellander/Cloud-Metric
resource_mining.py
4126
#! /usr/bin/env python import platform, socket import psutil import sys, datetime, os, json import pymongo from pymongo import MongoClient """ Retrieve memmory information """ def bytes_to_human(n): # >>> bytes2human(10000) # '9.8K' # >>> bytes2human(100001221) # '95.4M' symbols = ('G') prefix = {} for i, s in enumerate(symbols): prefix[s] = 1 << (i + 3) * 10 for s in reversed(symbols): #if n >= prefix[s]: value = float(n) / prefix[s] return '%.1f' % (value) return "%s" %n def get_total_memory(nt): memory = 0 for name in nt._fields: value = getattr(nt, name) if name == 'total': memory = bytes_to_human(value) return memory """ Retrieve CPU information """ def get_block_storage(): disk_size = 0 for part in psutil.disk_partitions(all=False): if os.name == 'nt': if 'cdrom' in part.opts or part.fstype == '': # skip cd-rom drives with no disk in it; they may raise # ENOENT, pop-up a Windows GUI error for a non-ready # partition or just hang. continue usage = psutil.disk_usage(part.mountpoint) disk_size = bytes_to_human(usage.total) return disk_size def detect_ncpus(): """Detects the number of effective CPUs in the system""" #for Linux, Unix and MacOS if hasattr(os, "sysconf"): if "SC_NPROCESSORS_ONLN" in os.sysconf_names: #Linux and Unix ncpus = os.sysconf("SC_NPROCESSORS_ONLN") if isinstance(ncpus, int) and ncpus > 0: return ncpus else: #MacOS X return int(os.popen2("sysctl -n hw.ncpu")[1].read()) #for Windows if "NUMBER_OF_PROCESSORS" in os.environ: ncpus = int(os.environ["NUMBER_OF_PROCESSORS"]) if ncpus > 0: return ncpus #return the default value return 1 def insert_data(ip, clustername): try: CM_DB = 'Node_Data' db = MongoClient(sys.argv[1], 27017)[CM_DB] ''' if "clusters" not in db.collection_names(): db.create_collection( 'clusters', capped=False) ''' #checks if cluster_key was inserted if clustername not in [node['name'] for node in db.clusters.find({},{'_id':0,'name':1})]: cluster_doc = dict() cluster_doc['name'] = clustername db.clusters.insert(cluster_doc) db.clusters.create_index('name',unique=True) ''' #checks for collection name in db if "metered_data" not in db.collection_names(): db.create_collection( 'metered_data', capped=False ) ''' # returns a json object #MEMORY_SIZE = get_total_memory(psutil.virtual_memory()) #DISK_SIZE = get_block_storage() #vCPU_COUNT = detect_ncpus() doc = dict() doc['cluster_id'] = clustername doc['node'] = socket.gethostname() doc['os'] = platform.system() doc['cpu'] = detect_ncpus() doc['memory'] = get_total_memory(psutil.virtual_memory()) doc['disk'] = get_block_storage() #values = {'node': NODE, 'os': OS, 'cpu': vCPU_COUNT, 'memory': MEMORY_SIZE, 'disk': DISK_SIZE} #print vCPU_COUNT #print values #Connect to MongoDB if socket.gethostname() not in [resources['node'] for resources in db.metered_data.find({},{'_id':0, 'node':1})]: db.metered_data.insert(doc) db.metered_data.create_index('node',unique=True) #obj_id = result.inserted_id #print obj_id except Exception as e: print "Could not insert data to db: "+str(e) if __name__=='__main__': if len(sys.argv) < 3: print "Error, Usage: python resource_mining.py [MongoDB IP] [Cluster Name]" sys.exit() insert_data(sys.argv[1], sys.argv[2])
mit
fuhongliang/20150606renren
Application/Common/Common/function.php
23376
<?php // .----------------------------------------------------------------------------------- // | WE TRY THE BEST WAY // |----------------------------------------------------------------------------------- // | Author: 贝贝 <hebiduhebi@163.com> // | Copyright (c) 2013-2015, http://www.gooraye.net. All Rights Reserved. // |----------------------------------------------------------------------------------- /** * 检测用户是否登录 * @return integer 0-未登录,大于0-当前登录用户ID */ function is_login() { $user = session('global_user'); if (empty($user)) { return 0; } else { return session('global_user_sign') == data_auth_sign($user) ? session('uid') : 0; } } /** * 检测当前用户是否为管理员 * @return boolean true-管理员,false-非管理员 * @author 麦当苗儿 <zuojiazi@vip.qq.com> */ function is_administrator($uid = null) { $uid = is_null($uid) ? is_login() : $uid; return $uid && (intval($uid) === C('USER_ADMINISTRATOR')); } /** * apiCall * @param $url * @param array $vars * @param string $layer * @return mixed */ function apiCall($url, $vars=array(), $layer = 'Api') { //TODO:考虑使用func_get_args 获取参数数组 $ret = R($url, $vars, $layer); if(!$ret){ return array('status'=>false,'info'=>'无法调用'.$url); } return $ret; } /** * 记录日志,系统运行过程中可能产生的日志 * Level取值如下: * EMERG 严重错误,导致系统崩溃无法使用 * ALERT 警戒性错误, 必须被立即修改的错误 * CRIT 临界值错误, 超过临界值的错误 * WARN 警告性错误, 需要发出警告的错误 * ERR 一般性错误 * NOTICE 通知,程序可以运行但是还不够完美的错误 * INFO 信息,程序输出信息 * DEBUG 调试,用于调试信息 * SQL SQL语句,该级别只在调试模式开启时有效 */ function LogRecord($msg, $location, $level = 'ERR') { Think\Log::write($location . $msg, $level); } /** * 如果操作失败则记录日志 * @return array 格式:array('status'=>boolean,'info'=>'错误信息') * @author hebiduhebi@163.com */ function ifFailedLogRecord($result, $location) { if ($result['status'] === false) { Think\Log::write($location . $result['info'], 'ERR'); } } /** * 数据签名认证 * @param array $data 被认证的数据 * @return string 签名 */ function data_auth_sign($data) { //数据类型检测 if (!is_array($data)) { $data = (array)$data; } ksort($data); //排序 $code = http_build_query($data); //url编码并生成query字符串 $sign = sha1($code); //生成签名 return $sign; } /** * 获取一个日期时间段 * 如果有查询参数包含startdatetime,enddatetime,则优先使用否则生成 * @param $type 0|1|2|3|其它 * @return array("0"=>开始日期,"1"=>结束日期) */ function getDataRange($type) { $result = array(); switch($type) { case 0 : //今天之内 $result['0'] = I('startdatetime', (date('Y-m-d 00:00:00', time())), 'urldecode'); break; case 1 : //昨天 $result['0'] = I('startdatetime', (date('Y-m-d 00:00:00', time() - 24 * 3600)), 'urldecode'); $result['1'] = I('enddatetime', (date('Y-m-d 00:00:00', time())), 'urldecode'); break; case 2 : //最近7天 $result['0'] = I('startdatetime', (date('Y-m-d H:i:s', time() - 24 * 3600 * 7)), 'urldecode'); break; case 3 : //最近30天 $result['0'] = I('startdatetime', (date('Y-m-d H:i:s', time() - 24 * 3600 * 30)), 'urldecode'); break; default : $result['0'] = I('startdatetime', (date('Y-m-d 00:00:00', time() - 24 * 3600)), 'urldecode'); break; } if (!isset($result['1'])) { $result['1'] = I('enddatetime', (date('Y-m-d H:i:s', time() + 10)), 'urldecode'); } return $result; } /** * 返回 是|否 * @param $param 一个值|对象等 * @return 空|false|0 时返回否,否则返回是 */ function yesorno($param) { if (is_null($param) || $param === false || $param == 0 || $param == "0") { return L("NO"); } else { return L('YES'); } } /** * 返回数据状态的含义 * @status $status 一个数字 -1,0,1,2,3 其它值都是未知 * @return 描述字符串 */ function getStatus($status) { $desc = '未知状态'; switch($status) { case -1 : $desc = "已删除"; break; case 0 : $desc = "禁用"; break; case 1 : $desc = "正常"; break; case 2 : $desc = "待审核"; break; case 3 : $desc = "通过"; break; case 4 : $desc = "不通过"; break; default : break; } return $desc; } /** * 获得皮肤的字符串表示 */ function getSkin($skin) { $desc = ''; switch($skin) { case 0 : $desc = "simplex"; break; case 1 : $desc = "flatly"; break; case 2 : $desc = "darkly"; break; case 3 : $desc = "cosmo"; break; case 4 : $desc = "paper"; break; case 5 : $desc = "slate"; break; case 6 : $desc = "superhero"; break; case 7 : $desc = "united"; break; case 8 : $desc = "yeti"; break; case 9 : $desc = "spruce"; break; case 10 : $desc = "readable"; break; case 11 : $desc = "cyborg"; break; case 12 : $desc = "cerulean"; break; default : $desc = "simplex"; break; } return $desc; } /** * 把返回的数据集转换成Tree * @param array $list 要转换的数据集 * @param string $pk * @param string $pid parent标记字段 * @param string $child * @param int $root * @return array * @internal param string $level level标记字段 */ function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0) { // 创建Tree $tree = array(); if (is_array($list)) { // 创建基于主键的数组引用 $refer = array(); foreach ($list as $key => $data) { $refer[$data[$pk]] = &$list[$key]; } foreach ($list as $key => $data) { // 判断是否存在parent $parentId = $data[$pid]; if ($root == $parentId) { $tree[] = &$list[$key]; } else { if (isset($refer[$parentId])) { $parent = &$refer[$parentId]; $parent[$child][] = &$list[$key]; } } } } return $tree; } /** * 将list_to_tree的树还原成列表 * @param array $tree 原来的树 * @param string $child 孩子节点的键 * @param string $order 排序显示的键,一般是主键 升序排列 * @param array $list 过渡用的中间数组, * @return array 返回排过序的列表数组 * @author yangweijie <yangweijiester@gmail.com> */ function tree_to_list($tree, $child = '_child', $order = 'id', &$list = array()) { if (is_array($tree)) { foreach ($tree as $key => $value) { $reffer = $value; if (isset($reffer[$child])) { unset($reffer[$child]); tree_to_list($value[$child], $child, $order, $list); } $list[] = $reffer; } $list = list_sort_by($list, $order, $sortby = 'asc'); } return $list; } /** * 获取图片表的图片链接 */ function getPictureURL($localpath, $remoteurl) { if (strpos($remoteurl, "http") === 0) { return $remoteurl; } return __ROOT__ . $localpath; } function GUID() { if (function_exists('com_create_guid') === true) { return trim(com_create_guid(), '{}'); } return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535)); } function addWeixinLog($data, $operator = '') { if(is_null($data)){ $data = ""; } $log['ctime'] = time(); $log['loginfo'] = is_array($data) ? serialize($data) : $data; $log['operator'] = $operator; $weixinlog = new \Common\Model\WeixinLogModel(); $weixinlog -> add($log); } /** * 获取订单状态的文字描述 */ function getOrderStatus($status) { switch($status) { case \Shop\Model\OrdersModel::ORDER_COMPLETED : return "已完成"; case \Shop\Model\OrdersModel::ORDER_RETURNED : return "已退货"; case \Shop\Model\OrdersModel::ORDER_SHIPPED : return "已发货"; case \Shop\Model\OrdersModel::ORDER_TOBE_CONFIRMED : return "待确认"; case \Shop\Model\OrdersModel::ORDER_TOBE_SHIPPED : return "待发货"; case \Shop\Model\OrdersModel::ORDER_CANCEL : return "订单已关闭"; case \Shop\Model\OrdersModel::ORDER_RECEIPT_OF_GOODS : return "已收货"; case \Shop\Model\OrdersModel::ORDER_BACK : return "卖家退回"; default : return "未知"; } } /** * 获取支付状态的文字描述 */ function getPayStatus($status) { switch($status) { case \Shop\Model\OrdersModel::ORDER_PAID : return "已支付"; case \Shop\Model\OrdersModel::ORDER_TOBE_PAID : return "待支付"; case \Shop\Model\OrdersModel::ORDER_REFUND : return "已退款"; case \Shop\Model\OrdersModel::ORDER_CASH_ON_DELIVERY : return "货到付款"; default : return "未知"; } } /** * 获取数据字典的ID * TODO: 考虑从数据库中获取 */ function getDatatree($code) { return C("DATATREE." . $code); } /** * 使用fsockopen请求地址 * @param $url 请求地址 ,完整的地址, * @param $post_data 请求参数,数组形式 * @param $cookie * @param $repeat TODO: 重复次数 * @return int */ function fsockopenRequest($url,$post_data = array(),$method="POST", $cookie = array(), $repeat = 1) { if($method == "POST"){ }else{ $method = "GET"; } //通过POST或者GET传递一些参数给要触发的脚本 $url_array = parse_url($url); //获取URL信息 $port = isset($url_array['port']) ? $url_array['port'] : 80; //5秒超时 $fp = @fsockopen($url_array['host'], $port, $errno, $errstr, 5); if (!$fp) { //连接失败 return 0; } //非阻塞设置 stream_set_blocking($fp, FALSE); $getPath = $url_array['path'] . "?" . $url_array['query']; $header = $method . " " . $getPath; $header .= " HTTP/1.1\r\n"; $header .= "Host: " . $url_array['host'] . "\r\n"; //HTTP 1.1 Host域不能省略 /*以下头信息域可以省略 */ $header .= "Referer:http://" . $url_array['host'] . " \r\n"; // $header .= "User-Agent:Mozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X; en-us) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53 \r\n"; // $header .= "Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 \r\n"; // $header .= "Accept-Language:zh-CN,zh;q=0.8,en;q=0.6 \r\n"; // $header .= "Accept-Encoding:gzip, deflate, sdch \r\n"; $header .= "Connection:Close\r\n"; // $header .= "Keep-Alive: 3\r\n"; // $header .= "Connection: keep-alive\r\n"; //需要重复2次 if (!empty($cookie)) { $_cookie = strval(NULL); foreach ($cookie as $k => $v) { $_cookie .= $k . "=" . $v . "; "; } $cookie_str = "Cookie: " . base64_encode($_cookie) . " \r\n"; //传递Cookie $header .= $cookie_str; } if (!empty($post_data)) { $_post = strval(NULL); $i == 0; foreach ($post_data as $k => $v) { if ($i == 0) { $_post .= $k . "=" . $v; } else { $_post .= '&'.$k . "=" . urlencode($v); } $i++; } // $post_str = "Content-Type: multipart/form-data; charset=UTF-8 \r\n"; $post_str = "Content-Type: application/x-www-form-urlencoded; charset=UTF-8 \r\n"; // $_post = "username=demo&password=hahaha"; $post_str .= "Content-Length: " . strlen($_post) . "\r\n"; $post_str .= "\r\n"; //POST数据的长度 $post_str .= $_post; //传递POST数据 $header .= $post_str; }else{ $header .= "\r\n"; } // dump($header); fwrite($fp, $header); //TODO: 从返回结果来判断是否成功 // $result = ""; // while(!feof($fp)){//测试文件指针是否到了文件结束的位置 // $result.= fgets($fp,128); // } // $result = split("\r\n", $result); // for($i=count($result)-1;$i>=0;$i--){ // dump($result); // } fclose($fp); return 1; } /** * 获取当前完整url */ function getCurrentURL(){ $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; return $url; } /** * 记录行为日志,并执行该行为的规则 * @param string $action 行为标识 * @param string $model 触发行为的模型名 * @param int $record_id 触发行为的记录id * @param int $user_id 执行行为的用户id * @return boolean */ function action_log($action = null, $model = null, $record_id = null, $user_id = null){ //参数检查 if(empty($action) || empty($model) || empty($record_id)){ return '参数不能为空'; } if(empty($user_id)){ $user_id = is_login(); } //查询行为,判断是否执行 $action_info = apiCall("Admin/Action/getInfo", array(array("name"=>$action))); // dump($action_info); if($action_info['status'] && is_array($action_info['info']) && $action_info['info']['status'] != 1){ return '该行为被禁用或删除'; } $action_info = $action_info['info']; //插入行为日志 $data['action_id'] = $action_info['id']; $data['user_id'] = $user_id; $data['action_ip'] = ip2long(get_client_ip()); $data['model'] = $model; $data['record_id'] = $record_id; $data['create_time'] = NOW_TIME; //解析日志规则,生成日志备注 if(!empty($action_info['log'])){ if(preg_match_all('/\[(\S+?)\]/', $action_info['log'], $match)){//匹配[],获取[]里的字符串 $log['user'] = $user_id; $log['record'] = $record_id; $log['model'] = $model; $log['time'] = NOW_TIME; $log['data'] = array('user'=>$user_id,'model'=>$model,'record'=>$record_id,'time'=>NOW_TIME); foreach ($match[1] as $value){ $param = explode('|', $value);//分割字符串通过| if(isset($param[1])){ $replace[] = call_user_func($param[1],$log[$param[0]]);//调用函数 }else{ $replace[] = $log[$param[0]]; } } $data['remark'] = str_replace($match[0], $replace, $action_info['log']); }else{ $data['remark'] = $action_info['log']; } }else{ //未定义日志规则,记录操作url $data['remark'] = '操作url:'.$_SERVER['REQUEST_URI']; } $result = apiCall("Admin/ActionLog/add", array($data)); if(!$result['status']){ LogRecord("记录操作日志失败!", $result['info']); } // M('ActionLog')->add($data); if(!empty($action_info['rule'])){ //解析行为 $rules = parse_action($action, $user_id); //执行行为 $res = execute_action($rules, $action_info['id'], $user_id); } } /** * 解析行为规则 * 示例:table:member|field:score|condition:uid={$self} AND status>-1|rule:9-2+3+score*1/1|cycle:24|max:1; * 规则定义 table:$table|field:$field|condition:$condition|rule:$rule[|cycle:$cycle|max:$max][;......] * 规则字段解释:table->要操作的数据表,不需要加表前缀; * field->要操作的字段; * condition->操作的条件,目前支持字符串,默认变量{$self}为执行行为的用户 * rule->对字段进行的具体操作,目前支持四则混合运算,如:1+score*2/2-3 * cycle->执行周期,单位(小时),表示$cycle小时内最多执行$max次 * max->单个周期内的最大执行次数($cycle和$max必须同时定义,否则无效) * 单个行为后可加 ; 连接其他规则 * @param string $action 行为id或者name * @param int $self 替换规则里的变量为执行用户的id * @return boolean|array: false解析出错 , 成功返回规则数组 */ function parse_action($action = null, $self){ if(empty($action)){ return false; } //参数支持id或者name if(is_numeric($action)){ $map = array('id'=>$action); }else{ $map = array('name'=>$action); } //查询行为信息 $result = apiCall("Admin/Action/getInfo", array($map)); if(!$result['status']){ return false; } $info = $result['info']; if(is_null($info) || $info['status'] != 1){ return false; } //解析规则:table:$table|field:$field|condition:$condition|rule:$rule[|cycle:$cycle|max:$max][;......] $rules = $info['rule']; $rules = str_replace('{$self}', $self, $rules); $rules = explode(';', $rules); $return = array(); foreach ($rules as $key=>&$rule){ $rule = explode('|', $rule); foreach ($rule as $k=>$fields){ $field = empty($fields) ? array() : explode(':', $fields); if(!empty($field)){ $return[$key][$field[0]] = $field[1]; } } //cycle(检查周期)和max(周期内最大执行次数)必须同时存在,否则去掉这两个条件 if(!array_key_exists('cycle', $return[$key]) || !array_key_exists('max', $return[$key])){ unset($return[$key]['cycle'],$return[$key]['max']); } } return $return; } /** * 执行行为 * @param array|bool $rules 解析后的规则数组 * @param int $action_id 行为id * @param array $user_id 执行的用户id * @return bool false 失败 , true 成功 * */ function execute_action($rules = false, $action_id = null, $user_id = null){ if(!$rules || empty($action_id) || empty($user_id)){ return false; } $return = true; foreach ($rules as $rule){ //检查执行周期 $map = array('action_id'=>$action_id, 'user_id'=>$user_id); $map['create_time'] = array('gt', NOW_TIME - intval($rule['cycle']) * 3600); //统计执行次数 $exec_count = D('ActionLog')->where($map)->count(); if($exec_count > $rule['max']){ continue; } //执行数据库操作 $Model = D(ucfirst($rule['table'])); $field = $rule['field']; $res = $Model->where($rule['condition'])->setField($field, array('exp', $rule['rule'])); // dump($Model); if(!$res){ $return = false; } } return $return; } /** * 时间戳格式化 * @param int $time * @return string 完整的时间显示 * @author huajie <banhuajie@163.com> */ function time_format($time = NULL,$format='Y-m-d H:i'){ $time = $time === NULL ? NOW_TIME : intval($time); return date($format, $time); } function subtext($text, $length) { if(mb_strlen($text, 'utf8') > $length) return mb_substr($text, 0, $length, 'utf8').'...'; return $text; } /** * 根据用户ID获取用户昵称 * @param integer $uid 用户ID * @return string 用户昵称 */ function get_nickname($uid = 0){ static $list; if(!($uid && is_numeric($uid))){ //获取当前登录用户名 return session('global_user.username'); } /* 获取缓存数据 */ if(empty($list)){ $list = S('sys_user_nickname_list'); } /* 查找用户信息 */ $key = "u{$uid}"; if(isset($list[$key])){ //已缓存,直接使用 $name = $list[$key]; } else { //调用接口获取用户信息 $result = apiCall("Admin/Member/getInfo",array("uid"=>$uid)); // $info = M('Member')->field('nickname')->find($uid); if($result['status'] !== false && $result['info']['nickname'] ){ $nickname = $result['info']['nickname']; $name = $list[$key] = $nickname; /* 缓存用户 */ $count = count($list); $max = 1000; while ($count-- > $max) { array_shift($list); } S('sys_user_nickname_list', $list); } else { $name = ''; } } return $name; } /** * 获取行为数据 * @param string $id 行为id * @param string $field 需要获取的字段 * @return bool */ function get_action($id = null, $field = null){ if(empty($id) && !is_numeric($id)){ return false; } $list = S('action_list'); if(empty($list[$id])){ $map = array('status'=>array('gt', -1), 'id'=>$id); $result = apiCall("Admin/Action/getInfo",array($map)); if($result['status']){ $list[$id] = $result['info']; } } S('action_list',$list); $ret = empty($field) ? $list[$id] : $list[$id][$field]; return $ret; } /** * 获取插件类的类名 * @var string $name 插件名 * @return string */ function get_addon_class($name){ $class = "Addons\\{$name}\\{$name}Addon"; return $class; } /** * 获取插件类的配置文件数组 * @param string $name 插件名 * @return array */ function get_addon_config($name){ $class = get_addon_class($name); if(class_exists($class)) { $addon = new $class(); return $addon->getConfig(); }else { return array(); } } /** * 插件显示内容里生成访问插件的url * @param string $url url * @param array $param 参数 * @return string */ function addons_url($url, $param = array()){ $url = parse_url($url); $case = C('URL_CASE_INSENSITIVE'); $addons = $case ? parse_name($url['scheme']) : $url['scheme']; $controller = $case ? parse_name($url['host']) : $url['host']; $action = trim($case ? strtolower($url['path']) : $url['path'], '/'); /* 解析URL带的参数 */ if(isset($url['query'])){ parse_str($url['query'], $query); $param = array_merge($query, $param); } /* 基础参数 */ $params = array( '_addons' => $addons, '_controller' => $controller, '_action' => $action, ); $params = array_merge($params, $param); //添加额外参数 return U('Addons/execute', $params); } /** * 基于数组创建目录和文件 * */ function create_dir_or_files($files){ foreach ($files as $key => $value) { if(substr($value, -1) == '/'){ mkdir($value); }else{ @file_put_contents($value, ''); } } } /** * 从session中取WxAccountID */ function getWxAccountID(){ if(session("?wxaccountid")){ return session("wxaccountid"); } return -1; }
mit
cjord01/imdb_clone
imdb/app/models/movie.rb
89
class Movie < ActiveRecord::Base has_many :roles has_many :actors, through: :roles end
mit
chicho2114/Proy_Frameworks
app/cache/dev/twig/06/45/e00d68ac581955401f16ae6bf40fd3aec4453b7a1248f1b791dc08b37fb9.php
1540
<?php /* SonataAdminBundle:CRUD:edit_array.html.twig */ class __TwigTemplate_0645e00d68ac581955401f16ae6bf40fd3aec4453b7a1248f1b791dc08b37fb9 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->blocks = array( 'field' => array($this, 'block_field'), ); } protected function doGetParent(array $context) { // line 12 return $this->env->resolveTemplate((isset($context["base_template"]) ? $context["base_template"] : $this->getContext($context, "base_template"))); } protected function doDisplay(array $context, array $blocks = array()) { $this->getParent($context)->display($context, array_merge($this->blocks, $blocks)); } // line 14 public function block_field($context, array $blocks = array()) { // line 15 echo " <span class=\"edit\"> "; // line 16 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["field_element"]) ? $context["field_element"] : $this->getContext($context, "field_element")), 'widget', array("attr" => array("class" => "title"))); echo " </span> "; } public function getTemplateName() { return "SonataAdminBundle:CRUD:edit_array.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 33 => 16, 30 => 15, 27 => 14, 18 => 12,); } }
mit
vihoangson/LearningEnglish
application/controllers/Ajax.php
764
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Ajax extends CI_Controller { public function word_in_cat() { if(!$_REQUEST["id"]) return false; $this->load->model('word'); header('Content-Type: application/json'); echo json_encode($this->word->getByCat($_REQUEST["id"])); } public function autocomplete(){ header('Content-Type: application/json'); //if(strlen($_POST["var_input"]) < 2) return; $this->db->like( 'word_name' , $_POST["var_input"] ); $this->db->limit(10); $arr = $this->db->get('word')->result_array(); foreach ($arr as $key => $value) { $arr_m[] = $value["word_name"]; } echo json_encode((array)$arr_m); } } /* End of file Ajax.php */ /* Location: ./application/controllers/Ajax.php */
mit
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.17.1/io-xdr/io-xdr-debug.js
129
version https://git-lfs.github.com/spec/v1 oid sha256:fc0e8a48504c3168a9c64fd938a26d63c4ca82ab857f63ce78fd885050fb2d4d size 8326
mit
testcontainers/testcontainers-java
modules/db2/src/main/java/org/testcontainers/containers/Db2ContainerProvider.java
604
package org.testcontainers.containers; import org.testcontainers.utility.DockerImageName; public class Db2ContainerProvider extends JdbcDatabaseContainerProvider { @Override public boolean supports(String databaseType) { return databaseType.equals(Db2Container.NAME); } @Override public JdbcDatabaseContainer newInstance() { return newInstance(Db2Container.DEFAULT_TAG); } @Override public JdbcDatabaseContainer newInstance(String tag) { return new Db2Container(DockerImageName.parse(Db2Container.DEFAULT_DB2_IMAGE_NAME).withTag(tag)); } }
mit
tatsuio/converse
spec/dialogue/message_decorators/slack_spec.rb
1288
RSpec.describe Dialogue::MessageDecorators::Slack do let(:channel_id) { "CHANNEL1" } let(:message) { double(:message, user: user_id, channel: channel_id, team: team_id) } let(:team_id) { "TEAM1" } let(:user_id) { "USER1" } subject { described_class.new(message) } describe "#initialize" do it "is initialized with a message" do expect(described_class.new(message).original_message).to eq message end end describe "#channel_id" do it "returns the channel from the original message" do expect(subject.channel_id).to eq channel_id end end describe "#team_id" do it "returns the team from the original message" do expect(subject.team_id).to eq team_id end it "returns the source team from the original message if the team is not present" do allow(message).to receive_messages(team: nil, source_team: team_id) expect(subject.team_id).to eq team_id end end describe "#user_id" do it "returns the user from the original message" do expect(subject.user_id).to eq user_id end end describe "delegating" do it "delegates any other messages to the original message" do allow(message).to receive(:text).and_return "Text" expect(subject.text).to eq "Text" end end end
mit
andygrunwald/go-jira
organization_test.go
10603
package jira import ( "encoding/json" "fmt" "net/http" "testing" ) func TestOrganizationService_GetAllOrganizationsWithContext(t *testing.T) { setup() defer teardown() testMux.HandleFunc("/rest/servicedeskapi/organization", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") testRequestURL(t, r, "/rest/servicedeskapi/organization") w.WriteHeader(http.StatusOK) fmt.Fprint(w, `{ "_expands": [], "size": 1, "start": 1, "limit": 1, "isLastPage": false, "_links": { "base": "https://your-domain.atlassian.net/rest/servicedeskapi", "context": "context", "next": "https://your-domain.atlassian.net/rest/servicedeskapi/organization?start=2&limit=1", "prev": "https://your-domain.atlassian.net/rest/servicedeskapi/organization?start=0&limit=1" }, "values": [ { "id": "1", "name": "Charlie Cakes Franchises", "_links": { "self": "https://your-domain.atlassian.net/rest/servicedeskapi/organization/1" } } ] }`) }) result, _, err := testClient.Organization.GetAllOrganizations(0, 50, "") if result == nil { t.Error("Expected Organizations. Result is nil") } else if result.Size != 1 { t.Errorf("Expected size to be 1, but got %d", result.Size) } if err != nil { t.Errorf("Error given: %s", err) } } func TestOrganizationService_CreateOrganization(t *testing.T) { setup() defer teardown() testMux.HandleFunc("/rest/servicedeskapi/organization", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") testRequestURL(t, r, "/rest/servicedeskapi/organization") o := new(OrganizationCreationDTO) json.NewDecoder(r.Body).Decode(&o) w.WriteHeader(http.StatusCreated) fmt.Fprintf(w, `{ "id": "1", "name": "%s", "_links": { "self": "https://your-domain.atlassian.net/rest/servicedeskapi/organization/1" } }`, o.Name) }) name := "MyOrg" o, _, err := testClient.Organization.CreateOrganization(name) if o == nil { t.Error("Expected Organization. Result is nil") } else if o.Name != name { t.Errorf("Expected name to be %s, but got %s", name, o.Name) } if err != nil { t.Errorf("Error given: %s", err) } } func TestOrganizationService_GetOrganization(t *testing.T) { setup() defer teardown() testMux.HandleFunc("/rest/servicedeskapi/organization/1", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") testRequestURL(t, r, "/rest/servicedeskapi/organization/1") w.WriteHeader(http.StatusOK) fmt.Fprintf(w, `{ "id": "1", "name": "name", "_links": { "self": "https://your-domain.atlassian.net/rest/servicedeskapi/organization/1" } }`) }) id := 1 o, _, err := testClient.Organization.GetOrganization(id) if err != nil { t.Errorf("Error given: %s", err) } if o == nil { t.Error("Expected Organization. Result is nil") } else if o.Name != "name" { t.Errorf("Expected name to be name, but got %s", o.Name) } } func TestOrganizationService_DeleteOrganization(t *testing.T) { setup() defer teardown() testMux.HandleFunc("/rest/servicedeskapi/organization/1", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "DELETE") testRequestURL(t, r, "/rest/servicedeskapi/organization/1") w.WriteHeader(http.StatusNoContent) }) _, err := testClient.Organization.DeleteOrganization(1) if err != nil { t.Errorf("Error given: %s", err) } } func TestOrganizationService_GetPropertiesKeys(t *testing.T) { setup() defer teardown() testMux.HandleFunc("/rest/servicedeskapi/organization/1/property", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") testRequestURL(t, r, "/rest/servicedeskapi/organization/1/property") w.WriteHeader(http.StatusOK) fmt.Fprintf(w, `{ "keys": [ { "self": "/rest/servicedeskapi/organization/1/property/propertyKey", "key": "organization.attributes" } ] }`) }) pk, _, err := testClient.Organization.GetPropertiesKeys(1) if err != nil { t.Errorf("Error given: %s", err) } if pk == nil { t.Error("Expected Keys. Result is nil") } else if pk.Keys[0].Key != "organization.attributes" { t.Errorf("Expected name to be organization.attributes, but got %s", pk.Keys[0].Key) } } func TestOrganizationService_GetProperty(t *testing.T) { setup() defer teardown() testMux.HandleFunc("/rest/servicedeskapi/organization/1/property/organization.attributes", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") testRequestURL(t, r, "/rest/servicedeskapi/organization/1/property/organization.attributes") w.WriteHeader(http.StatusOK) fmt.Fprintf(w, `{ "key": "organization.attributes", "value": { "phone": "0800-1233456789", "mail": "charlie@example.com" } }`) }) key := "organization.attributes" ep, _, err := testClient.Organization.GetProperty(1, key) if err != nil { t.Errorf("Error given: %s", err) } if ep == nil { t.Error("Expected Entity. Result is nil") } else if ep.Key != key { t.Errorf("Expected name to be %s, but got %s", key, ep.Key) } } func TestOrganizationService_SetProperty(t *testing.T) { setup() defer teardown() testMux.HandleFunc("/rest/servicedeskapi/organization/1/property/organization.attributes", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") testRequestURL(t, r, "/rest/servicedeskapi/organization/1/property/organization.attributes") w.WriteHeader(http.StatusOK) }) key := "organization.attributes" _, err := testClient.Organization.SetProperty(1, key) if err != nil { t.Errorf("Error given: %s", err) } } func TestOrganizationService_DeleteProperty(t *testing.T) { setup() defer teardown() testMux.HandleFunc("/rest/servicedeskapi/organization/1/property/organization.attributes", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "DELETE") testRequestURL(t, r, "/rest/servicedeskapi/organization/1/property/organization.attributes") w.WriteHeader(http.StatusOK) }) key := "organization.attributes" _, err := testClient.Organization.DeleteProperty(1, key) if err != nil { t.Errorf("Error given: %s", err) } } func TestOrganizationService_GetUsers(t *testing.T) { setup() defer teardown() testMux.HandleFunc("/rest/servicedeskapi/organization/1/user", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") testRequestURL(t, r, "/rest/servicedeskapi/organization/1/user") w.WriteHeader(http.StatusOK) fmt.Fprintf(w, `{ "_expands": [], "size": 1, "start": 1, "limit": 1, "isLastPage": false, "_links": { "base": "https://your-domain.atlassian.net/rest/servicedeskapi", "context": "context", "next": "https://your-domain.atlassian.net/rest/servicedeskapi/organization/1/user?start=2&limit=1", "prev": "https://your-domain.atlassian.net/rest/servicedeskapi/organization/1/user?start=0&limit=1" }, "values": [ { "accountId": "qm:a713c8ea-1075-4e30-9d96-891a7d181739:5ad6d3581db05e2a66fa80b", "name": "qm:a713c8ea-1075-4e30-9d96-891a7d181739:5ad6d3581db05e2a66fa80b", "key": "qm:a713c8ea-1075-4e30-9d96-891a7d181739:5ad6d3581db05e2a66fa80b", "emailAddress": "fred@example.com", "displayName": "Fred F. User", "active": true, "timeZone": "Australia/Sydney", "_links": { "jiraRest": "https://your-domain.atlassian.net/rest/api/2/user?username=qm:a713c8ea-1075-4e30-9d96-891a7d181739:5ad6d3581db05e2a66fa80b", "avatarUrls": { "48x48": "https://avatar-cdn.atlassian.com/9bc3b5bcb0db050c6d7660b28a5b86c9?s=48", "24x24": "https://avatar-cdn.atlassian.com/9bc3b5bcb0db050c6d7660b28a5b86c9?s=24", "16x16": "https://avatar-cdn.atlassian.com/9bc3b5bcb0db050c6d7660b28a5b86c9?s=16", "32x32": "https://avatar-cdn.atlassian.com/9bc3b5bcb0db050c6d7660b28a5b86c9?s=32" }, "self": "https://your-domain.atlassian.net/rest/api/2/user?username=qm:a713c8ea-1075-4e30-9d96-891a7d181739:5ad6d3581db05e2a66fa80b" } }, { "accountId": "qm:a713c8ea-1075-4e30-9d96-891a7d181739:5ad6d3a01db05e2a66fa80bd", "name": "qm:a713c8ea-1075-4e30-9d96-891a7d181739:5ad6d3a01db05e2a66fa80bd", "key": "qm:a713c8ea-1075-4e30-9d96-891a7d181739:5ad6d3a01db05e2a66fa80bd", "emailAddress": "bob@example.com", "displayName": "Bob D. Builder", "active": true, "timeZone": "Australia/Sydney", "_links": { "jiraRest": "https://your-domain.atlassian.net/rest/api/2/user?username=qm:a713c8ea-1075-4e30-9d96-891a7d181739:5ad6d3a01db05e2a66fa80bd", "avatarUrls": { "48x48": "https://avatar-cdn.atlassian.com/9bc3b5bcb0db050c6d7660b28a5b86c9?s=48", "24x24": "https://avatar-cdn.atlassian.com/9bc3b5bcb0db050c6d7660b28a5b86c9?s=24", "16x16": "https://avatar-cdn.atlassian.com/9bc3b5bcb0db050c6d7660b28a5b86c9?s=16", "32x32": "https://avatar-cdn.atlassian.com/9bc3b5bcb0db050c6d7660b28a5b86c9?s=32" }, "self": "https://your-domain.atlassian.net/rest/api/2/user?username=qm:a713c8ea-1075-4e30-9d96-891a7d181739:5ad6d3a01db05e2a66fa80bd" } } ] }`) }) users, _, err := testClient.Organization.GetUsers(1, 0, 50) if err != nil { t.Errorf("Error given: %s", err) } if users == nil { t.Error("Expected Organizations. Result is nil") } else if users.Size != 1 { t.Errorf("Expected size to be 1, but got %d", users.Size) } if err != nil { t.Errorf("Error given: %s", err) } } func TestOrganizationService_AddUsers(t *testing.T) { setup() defer teardown() testMux.HandleFunc("/rest/servicedeskapi/organization/1/user", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "POST") testRequestURL(t, r, "/rest/servicedeskapi/organization/1/user") w.WriteHeader(http.StatusNoContent) }) users := OrganizationUsersDTO{ AccountIds: []string{ "qm:a713c8ea-1075-4e30-9d96-891a7d181739:5ad6d3581db05e2a66fa80b", "qm:a713c8ea-1075-4e30-9d96-891a7d181739:5ad6d3a01db05e2a66fa80bd", }, } _, err := testClient.Organization.AddUsers(1, users) if err != nil { t.Errorf("Error given: %s", err) } } func TestOrganizationService_RemoveUsers(t *testing.T) { setup() defer teardown() testMux.HandleFunc("/rest/servicedeskapi/organization/1/user", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "DELETE") testRequestURL(t, r, "/rest/servicedeskapi/organization/1/user") w.WriteHeader(http.StatusNoContent) }) users := OrganizationUsersDTO{ AccountIds: []string{ "qm:a713c8ea-1075-4e30-9d96-891a7d181739:5ad6d3581db05e2a66fa80b", "qm:a713c8ea-1075-4e30-9d96-891a7d181739:5ad6d3a01db05e2a66fa80bd", }, } _, err := testClient.Organization.RemoveUsers(1, users) if err != nil { t.Errorf("Error given: %s", err) } }
mit
GlobalcachingEU/GAPP
GAPPSF/MapProviders/OSMBinMap/Way.cs
1012
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GAPPSF.MapProviders.OSMBinMap { public class Way { public class WayCoordinate { public int Latitude { get; set; } public int Longitude { get; set; } } public class WayCoordinateBlock { public List<WayCoordinate> CoordBlock { get; set; } } public class WayData { public List<WayCoordinateBlock> DataBlock { get; set; } } public List<int> TagIDs { get; set; } public int Layer { get; set; } public string Name { get; set; } public string HouseNumber { get; set; } public string Reference { get; set; } public int? LabelLatitude { get; set; } public int? LabelLongitude { get; set; } public List<WayData> WayDataBlocks { get; set; } //from theme public List<RenderInfo> RenderInfos { get; set; } } }
mit
jorupp/conference-room
Bot/Criteria/RoomStatusCriteria.cs
2198
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Bot.Builder.FormFlow; using Microsoft.Bot.Builder.FormFlow.Advanced; using Microsoft.Bot.Builder.Luis.Models; using RightpointLabs.ConferenceRoom.Bot.Extensions; namespace RightpointLabs.ConferenceRoom.Bot.Criteria { [Serializable] public class RoomStatusCriteria : RoomBaseCriteria { public string Room { get { return _room; } set { _room = value; if ((_room ?? "").ToLowerInvariant() == "away sis") _room = "oasis"; } } public string Building { get; set; } private string _room; public override string ToString() { var searchMsg = $"{this.Room}"; if (!string.IsNullOrEmpty(this.Building)) { searchMsg += $" in {this.Building}"; } if (this.StartTime.HasValue) { if (this.EndTime.HasValue) { searchMsg += $" from {this.StartTime.ToSimpleTime()} to {this.EndTime.ToSimpleTime()}"; } else { searchMsg += $" at {this.StartTime.ToSimpleTime()}"; } } return searchMsg; } public static RoomStatusCriteria ParseCriteria(LuisResult result, TimeZoneInfo timezone) { var room = result.Entities .Where(i => i.Type == "room") .Select(i => i.Entity ?? (string)i.Resolution["value"]) .FirstOrDefault(i => !string.IsNullOrEmpty(i)); var building = result.Entities .Where(i => i.Type == "building") .Select(i => i.Entity ?? (string)i.Resolution["value"]) .FirstOrDefault(i => !string.IsNullOrEmpty(i)); var criteria = new RoomStatusCriteria() { Room = room, Building = building, }; criteria.LoadTimeCriteria(result, timezone); return criteria; } } }
mit
romulo1984/bolt
tests/phpunit/unit/Nut/ConfigGetTest.php
1963
<?php namespace Bolt\Tests\Nut; use Bolt\Filesystem\Adapter\Local; use Bolt\Filesystem\Filesystem; use Bolt\Nut\ConfigGet; use Bolt\Tests\BoltUnitTest; use Symfony\Component\Console\Tester\CommandTester; /** * Class to test src/Nut/ConfigGet. * * @author Ross Riley <riley.ross@gmail.com> */ class ConfigGetTest extends BoltUnitTest { public function testGet() { $app = $this->getApp(); $filesystem = new Filesystem(new Local(PHPUNIT_ROOT . '/resources/')); $app['filesystem']->mountFilesystem('config', $filesystem); $command = new ConfigGet($app); $tester = new CommandTester($command); $tester->execute(['key' => 'sitename', '--file' => 'config.yml']); $this->assertRegExp('/sitename: A sample site/', $tester->getDisplay()); // test invalid $tester = new CommandTester($command); $tester->execute(['key' => 'nonexistent', '--file' => 'config.yml']); $this->assertRegExp("/The key 'nonexistent' was not found in config:\/\/config.yml/", $tester->getDisplay()); } public function testDefaultFile() { $app = $this->getApp(); $filesystem = new Filesystem(new Local(PHPUNIT_ROOT . '/resources/')); $app['filesystem']->mountFilesystem('config', $filesystem); $command = new ConfigGet($app); $tester = new CommandTester($command); $tester->execute(['key' => 'sitename']); $this->assertRegExp('/sitename: A sample site/', $tester->getDisplay()); } public function setUp() { @mkdir(PHPUNIT_ROOT . '/resources/', 0777, true); @mkdir(TEST_ROOT . '/app/cache/', 0777, true); $distname = realpath(TEST_ROOT . '/app/config/config.yml.dist'); @copy($distname, PHPUNIT_ROOT . '/resources/config.yml'); } public function tearDown() { @unlink(PHPUNIT_ROOT . '/resources/config.yml'); @unlink(TEST_ROOT . '/app/cache/'); } }
mit
jhelbig/postman-linux-app
app/resources/app/node_modules/parley/test/fixtures/validate.fixture.js
4355
/** * Module dependencies */ var _ = require('@sailshq/lodash'); var parley = require('../../'); /** * validate.fixture.js * * A simplified mock of a hypothetical `validate()` model method * that is actually synchronous. (This is primarily for use in benchmarks.) * * @param {Function} explicitCbMaybe * * @returns {Deferred} If no callback specified */ module.exports = function validate(explicitCbMaybe){ var metadata = {}; // This deferred may or may not actually need to get built. // (but in case it does, we define it out here so we can unambiguously // return it below) var deferred; // If an explicit callback was specified, then go ahead // and proceed to where the real action is at. // Otherwise, no callback was specified explicitly, // so we'll build and return a Deferred instead. deferred = parley(function (finalCb){ // Now actually do stuff. // ...except actually don't-- this is just pretend. // All done. return finalCb(); }, explicitCbMaybe); // If we ended up building a Deferred above, we would have done so synchronously. // In other words, if there's going to be a Deferred, we have it here. // // So if we DON'T have a Deferred, then we know that we must have already went ahead // and performed our business logic. So we'll just return undefined. if (!deferred) { return; }//-• // IWMIH, then we know we have a Deferred. // (and thus we haven't actually done anything yet.) // At this point, we might opt to attach some methods to our Deferred. // --(1)------------------------------------------------------- // --too slow: // --(e.g. 212k ops/sec) // deferred.meta = function (_meta){ // metadata.meta = _meta; // return deferred; // }; // --(2)------------------------------------------------------- // --perfectly fast, but doesn't do anything: // --(e.g. 373k ops/sec) // var theMeta = function (_meta){ // metadata.meta = _meta; // return deferred; // }; // --(3)------------------------------------------------------- // --somewhat better than the original!!... // --(e.g. 273k ops/sec) // --....but problematic, because it doesn't actually mutate // --the original deferred, which could cause inconsistencies. // deferred = _.extend({ // meta: function (_meta){ // metadata.meta = _meta; // return deferred; // } // }, deferred); // --(4)------------------------------------------------------- // --considerably better than the original!! // --(Even more than #3... plus it's totally valid!) // --(e.g. ~268k-292k ops/sec) _.extend(deferred, { meta: function (_meta){ metadata.meta = _meta; return deferred; }, // Uncomment these methods for testing performance: // (this function gets slower and slower the more you add dynamically like this) // ================================================================================================ // a: function (beep, boop) { console.log(Math.random()+'hi0'); return deferred; }, // b: function (baa, baaa, black, sheep) { console.log(Math.random()+'hi1'); return deferred; }, // c: function (beep, boop) { console.log(Math.random()+'hi2'); return deferred; }, // d: function (baa, baaa, black, sheep) { console.log(Math.random()+'hi3'); return deferred; }, // e: function (beep, boop) { console.log(Math.random()+'hi5'); return deferred; }, // f: function (baa, baaa, black, sheep) { console.log(Math.random()+'hi5'); return deferred; }, // g: function (beep, boop) { console.log(Math.random()+'hi6'); return deferred; }, // h: function (baa, baaa, black, sheep) { console.log(Math.random()+'hi7'); return deferred; }, // i: function (beep, boop) { console.log(Math.random()+'hi8'); return deferred; }, // j: function (baa, baaa, black, sheep) { console.log(Math.random()+'hi9'); return deferred; }, // k: function (beep, boop) { console.log(Math.random()+'hi10'); return deferred; }, // l: function (baa, baaa, black, sheep) { console.log(Math.random()+'hi11'); return deferred; }, // ================================================================================================ }); // When we're confident that our Deferred is ready for primetime, // we finish up by returning it. return deferred; };
mit
brussell/leadsneeds
addentry.php
2588
<div id="inputs"> <form action=""> <fieldset> <h2>Add a lead or a need.</h2> <div class="field"> <label for="givenname">First Name</label><br /> <input type="text" id="givenname" /> </div> <div class="field"> <label for="additionalname">Middle Name</label><br /> <input type="text" id="additionalname" value="" /> </div> <div class="field"> <label for="familyname">Last Name</label><br /> <input type="text" id="familyname" /> </div> <div class="field"> <label for="vorg">Organization</label><br /> <input type="text" id="vorg" value="" /> </div> <div class="field"> <label for="street">Street</label><br /> <input type="text" id="street" /> </div> <div class="field"> <label for="city">City</label><br /> <input type="text" id="city" /> </div> <div class="field"> <label for="region">State/Province</label><br /> <input type="text" id="region" /> </div> <div class="field"> <label for="postal">Postal Code</label><br /> <input type="text" id="postal" /> </div> <div class="field"> <label for="country">Country Name</label><br /> <input type="text" id="country" /> </div> <div class="field"> <label for="phone">Phone</label><br /> <input type="text" id="phone" /> </div> <div class="field"> <label for="email">Email</label><br /> <input type="text" id="email" /> </div> <div class="field"> <label for="url">URL</label><br /> <input type="text" id="url" /> </div> <div class="field"> <label for="photo">Photo Url</label><br /> <input type="text" id="photo" /> </div> <div class="field"> <label for="aim"><abbr title="AOL Instant Messenger">AIM</abbr> screenname</label><br /> <input type="text" id="aim" /> </div> <div class="field"> <label for="yim"><abbr title="Yahoo Instant Messenger">YIM</abbr> screenname</label><br /> <input type="text" id="yim" /> </div> <div class="field"> <label for="jabber">Jabber screenname</label><br /> <input type="text" id="jabber" /> </div> <div class="field"> <label for="tags">Tags (comma separated)</label><br /> <input type="text" id="tags" /> </div> <div class="field"> <p>Which column does this contact belong in?<br /> <label for="leeds">Leeds</label> <input type="radio" name="browser" value="leed"><br /> <label for="needs">Needs<label> <input type="radio" name="browser" value="needs"><br /> </p> </div> <div class="submit"> <input type="button" value="submit" class="button"> </div> </fieldset> </form> </div>
mit
nsartor/Squire
source/Range.js
15413
/*jshint strict:false, undef:false, unused:false, latedef:false */ var getNodeBefore = function ( node, offset ) { var children = node.childNodes; while ( offset && node.nodeType === ELEMENT_NODE ) { node = children[ offset - 1 ]; children = node.childNodes; offset = children.length; } return node; }; var getNodeAfter = function ( node, offset ) { if ( node.nodeType === ELEMENT_NODE ) { var children = node.childNodes; if ( offset < children.length ) { node = children[ offset ]; } else { while ( node && !node.nextSibling ) { node = node.parentNode; } if ( node ) { node = node.nextSibling; } } } return node; }; // --- var insertNodeInRange = function ( range, node ) { // Insert at start. var startContainer = range.startContainer, startOffset = range.startOffset, endContainer = range.endContainer, endOffset = range.endOffset, parent, children, childCount, afterSplit; // If part way through a text node, split it. if ( startContainer.nodeType === TEXT_NODE ) { parent = startContainer.parentNode; children = parent.childNodes; if ( startOffset === startContainer.length ) { startOffset = indexOf.call( children, startContainer ) + 1; if ( range.collapsed ) { endContainer = parent; endOffset = startOffset; } } else { if ( startOffset ) { afterSplit = startContainer.splitText( startOffset ); if ( endContainer === startContainer ) { endOffset -= startOffset; endContainer = afterSplit; } else if ( endContainer === parent ) { endOffset += 1; } startContainer = afterSplit; } startOffset = indexOf.call( children, startContainer ); } startContainer = parent; } else { children = startContainer.childNodes; } childCount = children.length; if ( startOffset === childCount) { startContainer.appendChild( node ); } else { startContainer.insertBefore( node, children[ startOffset ] ); } if ( startContainer === endContainer ) { endOffset += children.length - childCount; } range.setStart( startContainer, startOffset ); range.setEnd( endContainer, endOffset ); }; var extractContentsOfRange = function ( range, common ) { var startContainer = range.startContainer, startOffset = range.startOffset, endContainer = range.endContainer, endOffset = range.endOffset; if ( !common ) { common = range.commonAncestorContainer; } if ( common.nodeType === TEXT_NODE ) { common = common.parentNode; } var endNode = split( endContainer, endOffset, common ), startNode = split( startContainer, startOffset, common ), frag = common.ownerDocument.createDocumentFragment(), next, before, after; // End node will be null if at end of child nodes list. while ( startNode !== endNode ) { next = startNode.nextSibling; frag.appendChild( startNode ); startNode = next; } startContainer = common; startOffset = endNode ? indexOf.call( common.childNodes, endNode ) : common.childNodes.length; // Merge text nodes if adjacent. IE10 in particular will not focus // between two text nodes after = common.childNodes[ startOffset ]; before = after && after.previousSibling; if ( before && before.nodeType === TEXT_NODE && after.nodeType === TEXT_NODE ) { startContainer = before; startOffset = before.length; before.appendData( after.data ); detach( after ); } range.setStart( startContainer, startOffset ); range.collapse( true ); fixCursor( common ); return frag; }; var deleteContentsOfRange = function ( range ) { // Move boundaries up as much as possible to reduce need to split. moveRangeBoundariesUpTree( range ); // Remove selected range extractContentsOfRange( range ); // Move boundaries back down tree so that they are inside the blocks. // If we don't do this, the range may be collapsed to a point between // two blocks, so get(Start|End)BlockOfRange will return null. moveRangeBoundariesDownTree( range ); // If we split into two different blocks, merge the blocks. var startBlock = getStartBlockOfRange( range ), endBlock = getEndBlockOfRange( range ); if ( startBlock && endBlock && startBlock !== endBlock ) { mergeWithBlock( startBlock, endBlock, range ); } // Ensure block has necessary children if ( startBlock ) { fixCursor( startBlock ); } // Ensure body has a block-level element in it. var body = range.endContainer.ownerDocument.body, child = body.firstChild; if ( !child || child.nodeName === 'BR' ) { fixCursor( body ); range.selectNodeContents( body.firstChild ); } }; // --- var insertTreeFragmentIntoRange = function ( range, frag ) { // Check if it's all inline content var allInline = true, children = frag.childNodes, l = children.length; while ( l-- ) { if ( !isInline( children[l] ) ) { allInline = false; break; } } // Delete any selected content if ( !range.collapsed ) { deleteContentsOfRange( range ); } // Move range down into text nodes moveRangeBoundariesDownTree( range ); // If inline, just insert at the current position. if ( allInline ) { insertNodeInRange( range, frag ); range.collapse( false ); } // Otherwise, split up to blockquote (if a parent) or body, insert inline // before and after split and insert block in between split, then merge // containers. else { var splitPoint = range.startContainer, nodeAfterSplit = split( splitPoint, range.startOffset, getNearest( splitPoint.parentNode, 'BLOCKQUOTE' ) || splitPoint.ownerDocument.body ), nodeBeforeSplit = nodeAfterSplit.previousSibling, startContainer = nodeBeforeSplit, startOffset = startContainer.childNodes.length, endContainer = nodeAfterSplit, endOffset = 0, parent = nodeAfterSplit.parentNode, child, node; while ( ( child = startContainer.lastChild ) && child.nodeType === ELEMENT_NODE && child.nodeName !== 'BR' ) { startContainer = child; startOffset = startContainer.childNodes.length; } while ( ( child = endContainer.firstChild ) && child.nodeType === ELEMENT_NODE && child.nodeName !== 'BR' ) { endContainer = child; } while ( ( child = frag.firstChild ) && isInline( child ) ) { startContainer.appendChild( child ); } while ( ( child = frag.lastChild ) && isInline( child ) ) { endContainer.insertBefore( child, endContainer.firstChild ); endOffset += 1; } // Fix cursor then insert block(s) node = frag; while ( node = getNextBlock( node ) ) { fixCursor( node ); } parent.insertBefore( frag, nodeAfterSplit ); // Remove empty nodes created by split and merge inserted containers // with edges of split node = nodeAfterSplit.previousSibling; if ( !nodeAfterSplit.textContent ) { parent.removeChild( nodeAfterSplit ); } else { mergeContainers( nodeAfterSplit ); } if ( !nodeAfterSplit.parentNode ) { endContainer = node; endOffset = getLength( endContainer ); } if ( !nodeBeforeSplit.textContent) { startContainer = nodeBeforeSplit.nextSibling; startOffset = 0; parent.removeChild( nodeBeforeSplit ); } else { mergeContainers( nodeBeforeSplit ); } range.setStart( startContainer, startOffset ); range.setEnd( endContainer, endOffset ); moveRangeBoundariesDownTree( range ); } }; // --- var isNodeContainedInRange = function ( range, node, partial ) { var nodeRange = node.ownerDocument.createRange(); nodeRange.selectNode( node ); if ( partial ) { // Node must not finish before range starts or start after range // finishes. var nodeEndBeforeStart = ( range.compareBoundaryPoints( END_TO_START, nodeRange ) > -1 ), nodeStartAfterEnd = ( range.compareBoundaryPoints( START_TO_END, nodeRange ) < 1 ); return ( !nodeEndBeforeStart && !nodeStartAfterEnd ); } else { // Node must start after range starts and finish before range // finishes var nodeStartAfterStart = ( range.compareBoundaryPoints( START_TO_START, nodeRange ) < 1 ), nodeEndBeforeEnd = ( range.compareBoundaryPoints( END_TO_END, nodeRange ) > -1 ); return ( nodeStartAfterStart && nodeEndBeforeEnd ); } }; var moveRangeBoundariesDownTree = function ( range ) { var startContainer = range.startContainer, startOffset = range.startOffset, endContainer = range.endContainer, endOffset = range.endOffset, child; while ( startContainer.nodeType !== TEXT_NODE ) { child = startContainer.childNodes[ startOffset ]; if ( !child || isLeaf( child ) ) { break; } startContainer = child; startOffset = 0; } if ( endOffset ) { while ( endContainer.nodeType !== TEXT_NODE ) { child = endContainer.childNodes[ endOffset - 1 ]; if ( !child || isLeaf( child ) ) { break; } endContainer = child; endOffset = getLength( endContainer ); } } else { while ( endContainer.nodeType !== TEXT_NODE ) { child = endContainer.firstChild; if ( !child || isLeaf( child ) ) { break; } endContainer = child; } } // If collapsed, this algorithm finds the nearest text node positions // *outside* the range rather than inside, but also it flips which is // assigned to which. if ( range.collapsed ) { range.setStart( endContainer, endOffset ); range.setEnd( startContainer, startOffset ); } else { range.setStart( startContainer, startOffset ); range.setEnd( endContainer, endOffset ); } }; var moveRangeBoundariesUpTree = function ( range, common ) { var startContainer = range.startContainer, startOffset = range.startOffset, endContainer = range.endContainer, endOffset = range.endOffset, parent; if ( !common ) { common = range.commonAncestorContainer; } while ( startContainer !== common && !startOffset ) { parent = startContainer.parentNode; startOffset = indexOf.call( parent.childNodes, startContainer ); startContainer = parent; } while ( endContainer !== common && endOffset === getLength( endContainer ) ) { parent = endContainer.parentNode; endOffset = indexOf.call( parent.childNodes, endContainer ) + 1; endContainer = parent; } range.setStart( startContainer, startOffset ); range.setEnd( endContainer, endOffset ); }; // Returns the first block at least partially contained by the range, // or null if no block is contained by the range. var getStartBlockOfRange = function ( range ) { var container = range.startContainer, block; // If inline, get the containing block. if ( isInline( container ) ) { block = getPreviousBlock( container ); } else if ( isBlock( container ) ) { block = container; } else { block = getNodeBefore( container, range.startOffset ); block = getNextBlock( block ); } // Check the block actually intersects the range return block && isNodeContainedInRange( range, block, true ) ? block : null; }; // Returns the last block at least partially contained by the range, // or null if no block is contained by the range. var getEndBlockOfRange = function ( range ) { var container = range.endContainer, block, child; // If inline, get the containing block. if ( isInline( container ) ) { block = getPreviousBlock( container ); } else if ( isBlock( container ) ) { block = container; } else { block = getNodeAfter( container, range.endOffset ); if ( !block ) { block = container.ownerDocument.body; while ( child = block.lastChild ) { block = child; } } block = getPreviousBlock( block ); } // Check the block actually intersects the range return block && isNodeContainedInRange( range, block, true ) ? block : null; }; var contentWalker = new TreeWalker( null, SHOW_TEXT|SHOW_ELEMENT, function ( node ) { return node.nodeType === TEXT_NODE ? notWS.test( node.data ) : node.nodeName === 'IMG'; } ); var rangeDoesStartAtBlockBoundary = function ( range ) { var startContainer = range.startContainer, startOffset = range.startOffset; // If in the middle or end of a text node, we're not at the boundary. if ( startContainer.nodeType === TEXT_NODE ) { if ( startOffset ) { return false; } contentWalker.currentNode = startContainer; } else { contentWalker.currentNode = getNodeAfter( startContainer, startOffset ); } // Otherwise, look for any previous content in the same block. contentWalker.root = getStartBlockOfRange( range ); return !contentWalker.previousNode(); }; var rangeDoesEndAtBlockBoundary = function ( range ) { var endContainer = range.endContainer, endOffset = range.endOffset, length; // If in a text node with content, and not at the end, we're not // at the boundary if ( endContainer.nodeType === TEXT_NODE ) { length = endContainer.data.length; if ( length && endOffset < length ) { return false; } contentWalker.currentNode = endContainer; } else { contentWalker.currentNode = getNodeBefore( endContainer, endOffset ); } // Otherwise, look for any further content in the same block. contentWalker.root = getEndBlockOfRange( range ); return !contentWalker.nextNode(); }; var expandRangeToBlockBoundaries = function ( range ) { var start = getStartBlockOfRange( range ), end = getEndBlockOfRange( range ), parent; if ( start && end ) { parent = start.parentNode; range.setStart( parent, indexOf.call( parent.childNodes, start ) ); parent = end.parentNode; range.setEnd( parent, indexOf.call( parent.childNodes, end ) + 1 ); } };
mit
Yobeekster/SolidWorks
SolidDna/AngelSix.SolidDna/SolidWorks/Models/Feature/FeatureData/FeatureDeleteBodyData.cs
485
using SolidWorks.Interop.sldworks; namespace AngelSix.SolidDna { /// <summary> /// Represents a SolidWorks Delete Body feature data /// </summary> public class FeatureDeleteBodyData : SolidDnaObject<IDeleteBodyFeatureData> { #region Constructor /// <summary> /// Default constructor /// </summary> public FeatureDeleteBodyData(IDeleteBodyFeatureData model) : base(model) { } #endregion } }
mit
m00s/MS-MealPlanner-CLIENT-
client/components/recipe/recipe.service.js
169
'use strict'; angular.module('msMealPlannerApp.recipe', ['restangular']) .factory('Recipe', function (Restangular) { return Restangular.service('recipes'); });
mit
srthurman/transitland-python-client
transitland/errors.py
452
##### Exceptions ##### class ExistingIdentifierError(KeyError): pass class NoPointsError(ValueError): pass class InvalidFeedRegistryError(ValueError): pass class InvalidChecksumError(ValueError): pass class DatastoreError(Exception): def __init__(self, message, response_code=None, response_body=None): super(DatastoreError, self).__init__(message) self.response_code = response_code self.response_body = response_body
mit
bburnichon/PHPExiftool
lib/PHPExiftool/Driver/Tag/IFD0/LinearityLimitGreen.php
808
<?php /* * This file is part of the PHPExifTool package. * * (c) Alchemy <support@alchemy.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\IFD0; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class LinearityLimitGreen extends AbstractTag { protected $Id = 15; protected $Name = 'LinearityLimitGreen'; protected $FullName = 'PanasonicRaw::Main'; protected $GroupName = 'IFD0'; protected $g0 = 'EXIF'; protected $g1 = 'IFD0'; protected $g2 = 'Image'; protected $Type = 'int16u'; protected $Writable = true; protected $Description = 'Linearity Limit Green'; }
mit
HANDLL/Dynamoid
spec/dynamoid_spec.rb
356
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "Dynamoid" do it "doesn't puke when asked for the assocations of a new record" do User.new.books.should == [] end it "doesn't connect automatically when configured" do Dynamoid::Adapter.expects(:reconnect!).never Dynamoid.configure { |config| nil } end end
mit
KeyteqLabs/benchit.com
js/main.js
3694
var cloudfront = 'd6z0ab4she5iy.cloudfront.net'; angular.module('benchit.com', ['ui.router']) .config(function($locationProvider, $urlRouterProvider, $stateProvider) { $locationProvider.html5Mode({ enabled: true, requireBase: false }); $urlRouterProvider.when('', '/'); var featuresResolver = ['$http', function($http) { return $http.get('/features.json').then(function(data) { return data; }); }]; $stateProvider .state('main', { url: '/', templateUrl: '/views/main.html', controller: 'Main', resolve: { features: featuresResolver } }) .state('signup', { url: '/signup', controller: 'Signup', templateUrl: '/views/signup.html', }) .state('signup.done', { url: '/done', templateUrl: '/views/signup-done.html', params: {ok:true,new:true}, controller: function($scope, $stateParams, $state) { if (typeof $stateParams.new === 'undefined') { $state.go('signup'); } $scope.new = $stateParams.new; $scope.ok = $stateParams.ok; } }) .state('feature', { url: '/feature/:feature', templateUrl: '/views/feature.html', controller: 'Feature', resolve: { features: featuresResolver, feature: function($stateParams, features) { var key = $stateParams.feature; for (var i = 0; i < features.data.length; i++) { if (features.data[i].url === key) { return features.data[i] } } return null; } } }) var staticPages = ['faq', 'terms']; staticPages.forEach(function(state) { $stateProvider.state(state, { url: '/' + state, templateUrl: '/views/' + state + '.html' }); }); }) .run(function($rootScope) { $rootScope.mediaUrl = function(id, width, height) { height = height || 900; return '//' + cloudfront + '/' + width + 'x' + height + '/' + id + '.png?original=1'; } }) .controller('Feature', function($scope, feature) { $scope.feature = feature; }) .controller('Main', function($scope, $rootScope, features) { $scope.imgWidth = 350; $scope.featureList = features.data; }) .controller('Signup', function($scope, $http, $state) { $scope.user = { email: '' }; var url = "http://platform.launchrock.com/v1/createSiteUser"; $scope.submit = function() { $scope.loading = true; var data = { email: $scope.user.email, site_id: "YZGIKVEW", source: "CE9TOXQR" }; $.ajax({ url: url, data: data, method: 'post' }).success(function(res) { var data = res[0].response; $state.go('signup.done', { ok: data.status == 'OK', new: data.site_user.new_user == '1' }); }); }; });
mit
dblock/slack-ruby-bot
examples/market/marketbot.rb
931
# frozen_string_literal: true require 'iex-ruby-client' require 'slack-ruby-bot' SlackRubyBot::Client.logger.level = Logger::WARN class MarketBot < SlackRubyBot::Bot scan(/([A-Z]{2,5}+)/) do |client, data, stocks| stocks.each do |stock| begin quote = IEX::Resources::Quote.get(stock.first) client.web_client.chat_postMessage( channel: data.channel, as_user: true, attachments: [ { fallback: "#{quote.company_name} (#{quote.symbol}): $#{quote.latest_price}", title: "#{quote.company_name} (#{quote.symbol})", text: "$#{quote.latest_price} (#{quote.change_percent})", color: quote.change.to_f > 0 ? '#00FF00' : '#FF0000' } ] ) rescue IEX::Errors::SymbolNotFoundError logger.warn "no stock found for symbol #{stock}" end end end end MarketBot.run
mit