hexsha string | size int64 | ext string | lang string | max_stars_repo_path string | max_stars_repo_name string | max_stars_repo_head_hexsha string | max_stars_repo_licenses list | max_stars_count int64 | max_stars_repo_stars_event_min_datetime string | max_stars_repo_stars_event_max_datetime string | max_issues_repo_path string | max_issues_repo_name string | max_issues_repo_head_hexsha string | max_issues_repo_licenses list | max_issues_count int64 | max_issues_repo_issues_event_min_datetime string | max_issues_repo_issues_event_max_datetime string | max_forks_repo_path string | max_forks_repo_name string | max_forks_repo_head_hexsha string | max_forks_repo_licenses list | max_forks_count int64 | max_forks_repo_forks_event_min_datetime string | max_forks_repo_forks_event_max_datetime string | content string | avg_line_length float64 | max_line_length int64 | alphanum_fraction float64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6fca79756ea61e49d5b6219a3535aad48f802712 | 1,344 | js | JavaScript | src/javascripts/lib/interpolate.js | dzucconi/without-order | 95c107ba0d49d96cdd1d1c342937c47d49b278a5 | [
"MIT"
] | 2 | 2018-09-19T01:05:42.000Z | 2018-10-10T17:10:47.000Z | src/javascripts/lib/interpolate.js | dzucconi/without-order | 95c107ba0d49d96cdd1d1c342937c47d49b278a5 | [
"MIT"
] | 13 | 2017-07-04T04:04:58.000Z | 2022-03-22T00:54:22.000Z | src/javascripts/lib/interpolate.js | dzucconi/without-order | 95c107ba0d49d96cdd1d1c342937c47d49b278a5 | [
"MIT"
] | null | null | null | import SVG from "svg.js";
import "svg.shapes.js";
import { interpolate, toCircle, fromCircle } from "flubber";
import * as shapes from "./shapes";
export default class Interpolate {
constructor(el) {
this.el = el;
this.width = el.offsetWidth;
this.height = el.offsetHeight;
this.surface = SVG(this.el.id).size(this.width, this.height);
}
from(shape) {
this.fromShape = shape;
return this;
}
to(shape) {
if (!this.fromShape) throw new Error("Must first populate `from`");
this.toShape = shape;
if (this.fromShape === "circle") {
const x = this.height / 2;
const y = this.height / 2;
const r = (x + y) / 2 - 2;
const toShape = shapes[this.toShape](this.surface);
this.surface.remove();
return fromCircle(x, y, r, toShape.array().value);
}
if (this.toShape === "circle") {
const x = this.height / 2;
const y = this.height / 2;
const r = (x + y) / 2 - 2;
const fromShape = shapes[this.fromShape](this.surface);
this.surface.remove();
return toCircle(fromShape.array().value, x, y, r);
}
const toShape = shapes[this.toShape](this.surface);
const fromShape = shapes[this.fromShape](this.surface);
this.surface.remove();
return interpolate(fromShape.array().value, toShape.array().value);
}
}
| 26.352941 | 71 | 0.615327 |
6fca79a87da10e94235d120929d8aff3cf6601c5 | 1,426 | js | JavaScript | omui/src/components/code/code.stories.js | m15e/omui | 73e71d7fa75449b2a4fe7ee2ec776f68ea5764ac | [
"Apache-2.0"
] | 11 | 2020-06-08T15:03:34.000Z | 2021-06-23T07:15:19.000Z | omui/src/components/code/code.stories.js | m15e/omui | 73e71d7fa75449b2a4fe7ee2ec776f68ea5764ac | [
"Apache-2.0"
] | 20 | 2020-07-18T01:19:46.000Z | 2021-07-01T11:02:09.000Z | omui/src/components/code/code.stories.js | m15e/omui | 73e71d7fa75449b2a4fe7ee2ec776f68ea5764ac | [
"Apache-2.0"
] | 8 | 2020-06-30T12:32:13.000Z | 2021-06-24T09:01:26.000Z | import React from 'react';
import { withKnobs, boolean, text, select } from '@storybook/addon-knobs';
import { Code, CodeEditor } from './';
import { Text } from '../../';
import {
themeCodeLanguages,
themeCodePrettyLanguages
} from '../../theme/helpers';
const themeLanguages = {};
themeCodePrettyLanguages.forEach((lang, index) => {
themeLanguages[lang] = themeCodeLanguages[index];
});
const sampleCode = `import React, { useState } from "react";
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}`;
export default { title: 'Components/Code', decorators: [withKnobs] };
export const Default = () => (
<Code
language={select('Language', themeLanguages, 'jsx')}
lineNumbers={boolean('Show line numbers?', true)}
>
{text('Code', sampleCode)}
</Code>
);
Default.parameters = {
knobs: {
escapeHTML: false
}
};
export const Editable = () => (
<CodeEditor
language={select('Language', themeLanguages, 'jsx')}
onChange={(code) => console.log('Got the code here', code)}
>
{sampleCode}
</CodeEditor>
);
export const Inline = () => (
<Text as="span">
Just remember to call{' '}
<Code language="javascript" inline>
console.log(myVar);
</Code>{' '}
when debugging!
</Text>
);
| 21.606061 | 74 | 0.617812 |
6fca7e9486f6ce983052834a212c3e798b1c2397 | 1,963 | js | JavaScript | packages/with-view-layout-props/test/index.js | nmccready/hocs | 8ad07d80a165e02473054b36280db6798160b0cd | [
"MIT"
] | 1,850 | 2017-08-01T07:33:51.000Z | 2022-02-28T09:17:26.000Z | packages/with-view-layout-props/test/index.js | nmccready/hocs | 8ad07d80a165e02473054b36280db6798160b0cd | [
"MIT"
] | 36 | 2017-08-02T19:51:27.000Z | 2021-09-01T03:45:49.000Z | packages/with-view-layout-props/test/index.js | nmccready/hocs | 8ad07d80a165e02473054b36280db6798160b0cd | [
"MIT"
] | 60 | 2017-08-02T13:51:58.000Z | 2022-03-20T23:21:16.000Z | import React from 'react'
import { mount } from 'enzyme'
import withViewLayoutProps from '../src/'
const Target = () => null
describe('withViewLayoutProps', () => {
it('should pass props through', () => {
const EnhancedTarget = withViewLayoutProps((state) => state)(Target)
const wrapper = mount(
<EnhancedTarget a={1} b={2} />
)
expect(wrapper.find(Target)).toMatchSnapshot()
})
it('should map layout dimensions to props', () => {
const mockStateToProps = jest.fn((state) => state)
const EnhancedTarget = withViewLayoutProps(mockStateToProps)(Target)
const wrapper = mount(
<EnhancedTarget />
)
wrapper.find(Target).prop('onLayout')({
nativeEvent: {
layout: {
width: 1,
height: 2,
x: 3,
y: 4
}
}
})
wrapper.update()
expect(mockStateToProps.mock.calls).toMatchSnapshot()
expect(wrapper.find(Target)).toMatchSnapshot()
})
it('should use provided custom `onLayout` handler name', () => {
const EnhancedTarget = withViewLayoutProps(() => {}, 'onMyViewLayout')(Target)
const wrapper = mount(
<EnhancedTarget />
)
expect(wrapper.find(Target)).toMatchSnapshot()
})
describe('display name', () => {
const origNodeEnv = process.env.NODE_ENV
afterAll(() => {
process.env.NODE_ENV = origNodeEnv
})
it('should wrap display name in non-production env', () => {
process.env.NODE_ENV = 'test'
const EnhancedTarget = withViewLayoutProps(() => {})(Target)
const wrapper = mount(
<EnhancedTarget />
)
expect(wrapper).toMatchSnapshot()
})
it('should not wrap display name in production env', () => {
process.env.NODE_ENV = 'production'
const EnhancedTarget = withViewLayoutProps(() => {})(Target)
const wrapper = mount(
<EnhancedTarget />
)
expect(wrapper).toMatchSnapshot()
})
})
})
| 24.5375 | 82 | 0.604687 |
6fcb5433def855cdb4a35c02f8c60cff1fa20f1b | 274 | js | JavaScript | WebAppBuilderForArcGIS/client/stemapp3d/widgets/Environment/nls/sr/strings.js | vgauri1797/Eclipse | d342fe9e7e68718ae736c2b9a1e88c84ad50dfcf | [
"Apache-2.0"
] | null | null | null | WebAppBuilderForArcGIS/client/stemapp3d/widgets/Environment/nls/sr/strings.js | vgauri1797/Eclipse | d342fe9e7e68718ae736c2b9a1e88c84ad50dfcf | [
"Apache-2.0"
] | null | null | null | WebAppBuilderForArcGIS/client/stemapp3d/widgets/Environment/nls/sr/strings.js | vgauri1797/Eclipse | d342fe9e7e68718ae736c2b9a1e88c84ad50dfcf | [
"Apache-2.0"
] | null | null | null | define({
"_widgetLabel": "Okruženje",
"dragSunSliderText": "Prevucite slajder da biste promenili vreme dana.",
"directShadow": "Direktna senka (bačena sunčevom svetlošću)",
"diffuseShadow": "Difuzne senke (ambijentalna okluzija)",
"shadowing": "Senčenje"
}); | 39.142857 | 75 | 0.711679 |
6fcb566ce7e30dc12036b98741faadaeb98ef128 | 61,754 | js | JavaScript | public/libs/pusher.min.js | codewithvinit/test-push | 28ddc787813afe092997a3ce93b75070a95362d4 | [
"MIT"
] | null | null | null | public/libs/pusher.min.js | codewithvinit/test-push | 28ddc787813afe092997a3ce93b75070a95362d4 | [
"MIT"
] | 7 | 2021-06-18T16:04:18.000Z | 2022-02-27T15:24:31.000Z | public/libs/pusher.min.js | codewithvinit/test-push | 28ddc787813afe092997a3ce93b75070a95362d4 | [
"MIT"
] | null | null | null | /*!
* Pusher JavaScript Library v3.1.0
* http://pusher.com/
*
* Copyright 2016, Pusher
* Released under the MIT licence.
*/
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Pusher=e():t.Pusher=e()}(this,function(){return function(t){function e(i){if(n[i])return n[i].exports;var o=n[i]={exports:{},id:i,loaded:!1};return t[i].call(o.exports,o,o.exports,e),o.loaded=!0,o.exports}var n={};return e.m=t,e.c=n,e.p="",e(0)}([function(t,e,n){"use strict";var i=n(1);t.exports=i["default"]},function(t,e,n){"use strict";function i(t){if(null===t||void 0===t)throw"You must pass your app key when you instantiate Pusher."}var o=n(2),r=n(9),s=n(23),a=n(38),c=n(39),u=n(40),l=n(12),h=n(5),f=n(62),p=n(8),d=n(42),y=function(){function t(e,n){var l=this;i(e),n=n||{},this.key=e,this.config=r.extend(f.getGlobalConfig(),n.cluster?f.getClusterConfig(n.cluster):{},n),this.channels=d["default"].createChannels(),this.global_emitter=new s["default"],this.sessionID=Math.floor(1e9*Math.random()),this.timeline=new a["default"](this.key,this.sessionID,{cluster:this.config.cluster,features:t.getClientFeatures(),params:this.config.timelineParams||{},limit:50,level:c["default"].INFO,version:h["default"].VERSION}),this.config.disableStats||(this.timelineSender=d["default"].createTimelineSender(this.timeline,{host:this.config.statsHost,path:"/timeline/v2/"+o["default"].TimelineTransport.name}));var y=function(t){var e=r.extend({},l.config,t);return u.build(o["default"].getDefaultStrategy(e),e)};this.connection=d["default"].createConnectionManager(this.key,r.extend({getStrategy:y,timeline:this.timeline,activityTimeout:this.config.activity_timeout,pongTimeout:this.config.pong_timeout,unavailableTimeout:this.config.unavailable_timeout},this.config,{encrypted:this.isEncrypted()})),this.connection.bind("connected",function(){l.subscribeAll(),l.timelineSender&&l.timelineSender.send(l.connection.isEncrypted())}),this.connection.bind("message",function(t){var e=0===t.event.indexOf("pusher_internal:");if(t.channel){var n=l.channel(t.channel);n&&n.handleEvent(t.event,t.data)}e||l.global_emitter.emit(t.event,t.data)}),this.connection.bind("disconnected",function(){l.channels.disconnect()}),this.connection.bind("error",function(t){p["default"].warn("Error",t)}),t.instances.push(this),this.timeline.info({instances:t.instances.length}),t.isReady&&this.connect()}return t.ready=function(){t.isReady=!0;for(var e=0,n=t.instances.length;n>e;e++)t.instances[e].connect()},t.log=function(e){var n=Function("return this")();t.logToConsole&&n.console&&n.console.log&&n.console.log(e)},t.getClientFeatures=function(){return r.keys(r.filterObject({ws:o["default"].Transports.ws},function(t){return t.isSupported({})}))},t.prototype.channel=function(t){return this.channels.find(t)},t.prototype.allChannels=function(){return this.channels.all()},t.prototype.connect=function(){if(this.connection.connect(),this.timelineSender&&!this.timelineSenderTimer){var t=this.connection.isEncrypted(),e=this.timelineSender;this.timelineSenderTimer=new l.PeriodicTimer(6e4,function(){e.send(t)})}},t.prototype.disconnect=function(){this.connection.disconnect(),this.timelineSenderTimer&&(this.timelineSenderTimer.ensureAborted(),this.timelineSenderTimer=null)},t.prototype.bind=function(t,e){return this.global_emitter.bind(t,e),this},t.prototype.bind_all=function(t){return this.global_emitter.bind_all(t),this},t.prototype.subscribeAll=function(){var t;for(t in this.channels.channels)this.channels.channels.hasOwnProperty(t)&&this.subscribe(t)},t.prototype.subscribe=function(t){var e=this.channels.add(t,this);return"connected"===this.connection.state&&e.subscribe(),e},t.prototype.unsubscribe=function(t){var e=this.channels.remove(t);e&&"connected"===this.connection.state&&e.unsubscribe()},t.prototype.send_event=function(t,e,n){return this.connection.send_event(t,e,n)},t.prototype.isEncrypted=function(){return"https:"===o["default"].getProtocol()?!0:Boolean(this.config.encrypted)},t.instances=[],t.isReady=!1,t.logToConsole=!1,t.Runtime=o["default"],t.ScriptReceivers=o["default"].ScriptReceivers,t.DependenciesReceivers=o["default"].DependenciesReceivers,t.auth_callbacks=o["default"].auth_callbacks,t}();e.__esModule=!0,e["default"]=y,o["default"].setup(y)},function(t,e,n){"use strict";var i=n(3),o=n(7),r=n(14),s=n(15),a=n(16),c=n(4),u=n(17),l=n(18),h=n(25),f=n(26),p=n(27),d=n(28),y={nextAuthCallbackID:1,auth_callbacks:{},ScriptReceivers:c.ScriptReceivers,DependenciesReceivers:i.DependenciesReceivers,getDefaultStrategy:f["default"],Transports:l["default"],transportConnectionInitializer:p["default"],HTTPFactory:d["default"],TimelineTransport:u["default"],getXHRAPI:function(){return window.XMLHttpRequest},getWebSocketAPI:function(){return window.WebSocket||window.MozWebSocket},setup:function(t){var e=this;window.Pusher=t;var n=function(){e.onDocumentBody(t.ready)};window.JSON?n():i.Dependencies.load("json2",{},n)},getDocument:function(){return document},getProtocol:function(){return this.getDocument().location.protocol},getGlobal:function(){return window},getAuthorizers:function(){return{ajax:o["default"],jsonp:r["default"]}},onDocumentBody:function(t){var e=this;document.body?t():setTimeout(function(){e.onDocumentBody(t)},0)},createJSONPRequest:function(t,e){return new a["default"](t,e)},createScriptRequest:function(t){return new s["default"](t)},getLocalStorage:function(){try{return window.localStorage}catch(t){return}},createXHR:function(){return this.getXHRAPI()?this.createXMLHttpRequest():this.createMicrosoftXHR()},createXMLHttpRequest:function(){var t=this.getXHRAPI();return new t},createMicrosoftXHR:function(){return new ActiveXObject("Microsoft.XMLHTTP")},getNetwork:function(){return h.Network},createWebSocket:function(t){var e=this.getWebSocketAPI();return new e(t)},createSocketRequest:function(t,e){if(this.isXHRSupported())return this.HTTPFactory.createXHR(t,e);if(this.isXDRSupported(0===e.indexOf("https:")))return this.HTTPFactory.createXDR(t,e);throw"Cross-origin HTTP requests are not supported"},isXHRSupported:function(){var t=this.getXHRAPI();return Boolean(t)&&void 0!==(new t).withCredentials},isXDRSupported:function(t){var e=t?"https:":"http:",n=this.getProtocol();return Boolean(window.XDomainRequest)&&n===e},addUnloadListener:function(t){void 0!==window.addEventListener?window.addEventListener("unload",t,!1):void 0!==window.attachEvent&&window.attachEvent("onunload",t)},removeUnloadListener:function(t){void 0!==window.addEventListener?window.removeEventListener("unload",t,!1):void 0!==window.detachEvent&&window.detachEvent("onunload",t)}};e.__esModule=!0,e["default"]=y},function(t,e,n){"use strict";var i=n(4),o=n(5),r=n(6);e.DependenciesReceivers=new i.ScriptReceiverFactory("_pusher_dependencies","Pusher.DependenciesReceivers"),e.Dependencies=new r["default"]({cdn_http:o["default"].cdn_http,cdn_https:o["default"].cdn_https,version:o["default"].VERSION,suffix:o["default"].dependency_suffix,receivers:e.DependenciesReceivers})},function(t,e){"use strict";var n=function(){function t(t,e){this.lastId=0,this.prefix=t,this.name=e}return t.prototype.create=function(t){this.lastId++;var e=this.lastId,n=this.prefix+e,i=this.name+"["+e+"]",o=!1,r=function(){o||(t.apply(null,arguments),o=!0)};return this[e]=r,{number:e,id:n,name:i,callback:r}},t.prototype.remove=function(t){delete this[t.number]},t}();e.ScriptReceiverFactory=n,e.ScriptReceivers=new n("_pusher_script_","Pusher.ScriptReceivers")},function(t,e){"use strict";var n={VERSION:"3.1.0",PROTOCOL:7,host:"ws.pusherapp.com",ws_port:80,wss_port:443,sockjs_host:"sockjs.pusher.com",sockjs_http_port:80,sockjs_https_port:443,sockjs_path:"/pusher",stats_host:"stats.pusher.com",channel_auth_endpoint:"/pusher/auth",channel_auth_transport:"ajax",activity_timeout:12e4,pong_timeout:3e4,unavailable_timeout:1e4,cdn_http:"http://js.pusher.com",cdn_https:"https://js.pusher.com",dependency_suffix:".min"};e.__esModule=!0,e["default"]=n},function(t,e,n){"use strict";var i=n(4),o=n(2),r=function(){function t(t){this.options=t,this.receivers=t.receivers||i.ScriptReceivers,this.loading={}}return t.prototype.load=function(t,e,n){var i=this;if(i.loading[t]&&i.loading[t].length>0)i.loading[t].push(n);else{i.loading[t]=[n];var r=o["default"].createScriptRequest(i.getPath(t,e)),s=i.receivers.create(function(e){if(i.receivers.remove(s),i.loading[t]){var n=i.loading[t];delete i.loading[t];for(var o=function(t){t||r.cleanup()},a=0;a<n.length;a++)n[a](e,o)}});r.send(s)}},t.prototype.getRoot=function(t){var e,n=o["default"].getDocument().location.protocol;return e=t&&t.encrypted||"https:"===n?this.options.cdn_https:this.options.cdn_http,e.replace(/\/*$/,"")+"/"+this.options.version},t.prototype.getPath=function(t,e){return this.getRoot(e)+"/"+t+this.options.suffix+".js"},t}();e.__esModule=!0,e["default"]=r},function(t,e,n){"use strict";var i=n(8),o=n(2),r=function(t,e,n){var r,s=this;r=o["default"].createXHR(),r.open("POST",s.options.authEndpoint,!0),r.setRequestHeader("Content-Type","application/x-www-form-urlencoded");for(var a in this.authOptions.headers)r.setRequestHeader(a,this.authOptions.headers[a]);return r.onreadystatechange=function(){if(4===r.readyState)if(200===r.status){var t,e=!1;try{t=JSON.parse(r.responseText),e=!0}catch(o){n(!0,"JSON returned from webapp was invalid, yet status code was 200. Data was: "+r.responseText)}e&&n(!1,t)}else i["default"].warn("Couldn't get auth info from your webapp",r.status),n(!0,r.status)},r.send(this.composeQuery(e)),r};e.__esModule=!0,e["default"]=r},function(t,e,n){"use strict";var i=n(9),o=n(1),r={debug:function(){for(var t=[],e=0;e<arguments.length;e++)t[e-0]=arguments[e];o["default"].log&&o["default"].log(i.stringify.apply(this,arguments))},warn:function(){for(var t=[],e=0;e<arguments.length;e++)t[e-0]=arguments[e];var n=i.stringify.apply(this,arguments),r=Function("return this")();r.console&&(r.console.warn?r.console.warn(n):r.console.log&&r.console.log(n)),o["default"].log&&o["default"].log(n)}};e.__esModule=!0,e["default"]=r},function(t,e,n){"use strict";function i(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];for(var o=0;o<e.length;o++){var r=e[o];for(var s in r)r[s]&&r[s].constructor&&r[s].constructor===Object?t[s]=i(t[s]||{},r[s]):t[s]=r[s]}return t}function o(){for(var t=["Pusher"],e=0;e<arguments.length;e++)"string"==typeof arguments[e]?t.push(arguments[e]):t.push(JSON.stringify(arguments[e]));return t.join(" : ")}function r(t,e){var n=Array.prototype.indexOf;if(null===t)return-1;if(n&&t.indexOf===n)return t.indexOf(e);for(var i=0,o=t.length;o>i;i++)if(t[i]===e)return i;return-1}function s(t,e){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e(t[n],n,t)}function a(t){var e=[];return s(t,function(t,n){e.push(n)}),e}function c(t){var e=[];return s(t,function(t){e.push(t)}),e}function u(t,e,n){for(var i=0;i<t.length;i++)e.call(n||w,t[i],i,t)}function l(t,e){for(var n=[],i=0;i<t.length;i++)n.push(e(t[i],i,t,n));return n}function h(t,e){var n={};return s(t,function(t,i){n[i]=e(t)}),n}function f(t,e){e=e||function(t){return!!t};for(var n=[],i=0;i<t.length;i++)e(t[i],i,t,n)&&n.push(t[i]);return n}function p(t,e){var n={};return s(t,function(i,o){(e&&e(i,o,t,n)||Boolean(i))&&(n[o]=i)}),n}function d(t){var e=[];return s(t,function(t,n){e.push([n,t])}),e}function y(t,e){for(var n=0;n<t.length;n++)if(e(t[n],n,t))return!0;return!1}function m(t,e){for(var n=0;n<t.length;n++)if(!e(t[n],n,t))return!1;return!0}function v(t){return h(t,function(t){return"object"==typeof t&&(t=JSON.stringify(t)),encodeURIComponent(b["default"](t.toString()))})}function g(t){var e=p(t,function(t){return void 0!==t}),n=l(d(v(e)),k["default"].method("join","=")).join("&");return n}function _(t){var e=[],n=JSON.stringify(t,function(t,n){if("object"==typeof n&&null!==n){if(-1!==e.indexOf(n))return;e.push(n)}return n});return e=null,n}var b=n(10),k=n(11),w=Function("return this")();e.extend=i,e.stringify=o,e.arrayIndexOf=r,e.objectApply=s,e.keys=a,e.values=c,e.apply=u,e.map=l,e.mapObject=h,e.filter=f,e.filterObject=p,e.flatten=d,e.any=y,e.all=m,e.encodeParamsObject=v,e.buildQueryString=g,e.safeJSONStringify=_},function(t,e){"use strict";function n(t){return f(l(t))}var i=Function("return this")();e.__esModule=!0,e["default"]=n;for(var o=String.fromCharCode,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s={},a=0,c=r.length;c>a;a++)s[r.charAt(a)]=a;var u=function(t){var e=t.charCodeAt(0);return 128>e?t:2048>e?o(192|e>>>6)+o(128|63&e):o(224|e>>>12&15)+o(128|e>>>6&63)+o(128|63&e)},l=function(t){return t.replace(/[^\x00-\x7F]/g,u)},h=function(t){var e=[0,2,1][t.length%3],n=t.charCodeAt(0)<<16|(t.length>1?t.charCodeAt(1):0)<<8|(t.length>2?t.charCodeAt(2):0),i=[r.charAt(n>>>18),r.charAt(n>>>12&63),e>=2?"=":r.charAt(n>>>6&63),e>=1?"=":r.charAt(63&n)];return i.join("")},f=i.btoa||function(t){return t.replace(/[\s\S]{1,3}/g,h)}},function(t,e,n){"use strict";var i=n(12),o={getGlobal:function(){return Function("return this")()},now:function(){return Date.now?Date.now():(new Date).valueOf()},defer:function(t){return new i.OneOffTimer(0,t)},method:function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];var i=Array.prototype.slice.call(arguments,1);return function(e){return e[t].apply(e,i.concat(arguments))}}};e.__esModule=!0,e["default"]=o},function(t,e,n){"use strict";function i(t){a.clearTimeout(t)}function o(t){a.clearInterval(t)}var r=this&&this.__extends||function(t,e){function n(){this.constructor=t}for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)},s=n(13),a=Function("return this")(),c=function(t){function e(e,n){t.call(this,setTimeout,i,e,function(t){return n(),null})}return r(e,t),e}(s["default"]);e.OneOffTimer=c;var u=function(t){function e(e,n){t.call(this,setInterval,o,e,function(t){return n(),t})}return r(e,t),e}(s["default"]);e.PeriodicTimer=u},function(t,e){"use strict";var n=function(){function t(t,e,n,i){var o=this;this.clear=e,this.timer=t(function(){o.timer&&(o.timer=i(o.timer))},n)}return t.prototype.isRunning=function(){return null!==this.timer},t.prototype.ensureAborted=function(){this.timer&&(this.clear(this.timer),this.timer=null)},t}();e.__esModule=!0,e["default"]=n},function(t,e,n){"use strict";var i=n(8),o=function(t,e,n){void 0!==this.authOptions.headers&&i["default"].warn("Warn","To send headers with the auth request, you must use AJAX, rather than JSONP.");var o=t.nextAuthCallbackID.toString();t.nextAuthCallbackID++;var r=t.getDocument(),s=r.createElement("script");t.auth_callbacks[o]=function(t){n(!1,t)};var a="Pusher.auth_callbacks['"+o+"']";s.src=this.options.authEndpoint+"?callback="+encodeURIComponent(a)+"&"+this.composeQuery(e);var c=r.getElementsByTagName("head")[0]||r.documentElement;c.insertBefore(s,c.firstChild)};e.__esModule=!0,e["default"]=o},function(t,e){"use strict";var n=function(){function t(t){this.src=t}return t.prototype.send=function(t){var e=this,n="Error loading "+e.src;e.script=document.createElement("script"),e.script.id=t.id,e.script.src=e.src,e.script.type="text/javascript",e.script.charset="UTF-8",e.script.addEventListener?(e.script.onerror=function(){t.callback(n)},e.script.onload=function(){t.callback(null)}):e.script.onreadystatechange=function(){("loaded"===e.script.readyState||"complete"===e.script.readyState)&&t.callback(null)},void 0===e.script.async&&document.attachEvent&&/opera/i.test(navigator.userAgent)?(e.errorScript=document.createElement("script"),e.errorScript.id=t.id+"_error",e.errorScript.text=t.name+"('"+n+"');",e.script.async=e.errorScript.async=!1):e.script.async=!0;var i=document.getElementsByTagName("head")[0];i.insertBefore(e.script,i.firstChild),e.errorScript&&i.insertBefore(e.errorScript,e.script.nextSibling)},t.prototype.cleanup=function(){this.script&&(this.script.onload=this.script.onerror=null,this.script.onreadystatechange=null),this.script&&this.script.parentNode&&this.script.parentNode.removeChild(this.script),this.errorScript&&this.errorScript.parentNode&&this.errorScript.parentNode.removeChild(this.errorScript),this.script=null,this.errorScript=null},t}();e.__esModule=!0,e["default"]=n},function(t,e,n){"use strict";var i=n(9),o=n(2),r=function(){function t(t,e){this.url=t,this.data=e}return t.prototype.send=function(t){if(!this.request){var e=i.buildQueryString(this.data),n=this.url+"/"+t.number+"?"+e;this.request=o["default"].createScriptRequest(n),this.request.send(t)}},t.prototype.cleanup=function(){this.request&&this.request.cleanup()},t}();e.__esModule=!0,e["default"]=r},function(t,e,n){"use strict";var i=n(2),o=n(4),r=function(t,e){return function(n,r){var s="http"+(e?"s":"")+"://",a=s+(t.host||t.options.host)+t.options.path,c=i["default"].createJSONPRequest(a,n),u=i["default"].ScriptReceivers.create(function(e,n){o.ScriptReceivers.remove(u),c.cleanup(),n&&n.host&&(t.host=n.host),r&&r(e,n)});c.send(u)}},s={name:"jsonp",getAgent:r};e.__esModule=!0,e["default"]=s},function(t,e,n){"use strict";var i=n(19),o=n(21),r=n(20),s=n(2),a=n(3),c=n(9),u=new o["default"]({file:"sockjs",urls:r.sockjs,handlesActivityChecks:!0,supportsPing:!1,isSupported:function(){return!0},isInitialized:function(){return void 0!==window.SockJS},getSocket:function(t,e){return new window.SockJS(t,null,{js_path:a.Dependencies.getPath("sockjs",{encrypted:e.encrypted}),ignore_null_origin:e.ignoreNullOrigin})},beforeOpen:function(t,e){t.send(JSON.stringify({path:e}))}}),l={isSupported:function(t){var e=s["default"].isXDRSupported(t.encrypted);return e}},h=new o["default"](c.extend({},i.streamingConfiguration,l)),f=new o["default"](c.extend({},i.pollingConfiguration,l));i["default"].xdr_streaming=h,i["default"].xdr_polling=f,i["default"].sockjs=u,e.__esModule=!0,e["default"]=i["default"]},function(t,e,n){"use strict";var i=n(20),o=n(21),r=n(9),s=n(2),a=new o["default"]({urls:i.ws,handlesActivityChecks:!1,supportsPing:!1,isInitialized:function(){return Boolean(s["default"].getWebSocketAPI())},isSupported:function(){return Boolean(s["default"].getWebSocketAPI())},getSocket:function(t){return s["default"].createWebSocket(t)}}),c={urls:i.http,handlesActivityChecks:!1,supportsPing:!0,isInitialized:function(){return!0}};e.streamingConfiguration=r.extend({getSocket:function(t){return s["default"].HTTPFactory.createStreamingSocket(t)}},c),e.pollingConfiguration=r.extend({getSocket:function(t){return s["default"].HTTPFactory.createPollingSocket(t)}},c);var u={isSupported:function(){return s["default"].isXHRSupported()}},l=new o["default"](r.extend({},e.streamingConfiguration,u)),h=new o["default"](r.extend({},e.pollingConfiguration,u)),f={ws:a,xhr_streaming:l,xhr_polling:h};e.__esModule=!0,e["default"]=f},function(t,e,n){"use strict";function i(t,e,n){var i=t+(e.encrypted?"s":""),o=e.encrypted?e.hostEncrypted:e.hostUnencrypted;return i+"://"+o+n}function o(t,e){var n="/app/"+t,i="?protocol="+r["default"].PROTOCOL+"&client=js&version="+r["default"].VERSION+(e?"&"+e:"");return n+i}var r=n(5);e.ws={getInitial:function(t,e){return i("ws",e,o(t,"flash=false"))}},e.http={getInitial:function(t,e){var n=(e.httpPath||"/pusher")+o(t);return i("http",e,n)}},e.sockjs={getInitial:function(t,e){return i("http",e,e.httpPath||"/pusher")},getPath:function(t,e){return o(t)}}},function(t,e,n){"use strict";var i=n(22),o=function(){function t(t){this.hooks=t}return t.prototype.isSupported=function(t){return this.hooks.isSupported(t)},t.prototype.createConnection=function(t,e,n,o){return new i["default"](this.hooks,t,e,n,o)},t}();e.__esModule=!0,e["default"]=o},function(t,e,n){"use strict";var i=this&&this.__extends||function(t,e){function n(){this.constructor=t}for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)},o=n(11),r=n(9),s=n(23),a=n(8),c=n(2),u=function(t){function e(e,n,i,o,r){t.call(this),this.initialize=c["default"].transportConnectionInitializer,this.hooks=e,this.name=n,this.priority=i,this.key=o,this.options=r,this.state="new",this.timeline=r.timeline,this.activityTimeout=r.activityTimeout,this.id=this.timeline.generateUniqueID()}return i(e,t),e.prototype.handlesActivityChecks=function(){return Boolean(this.hooks.handlesActivityChecks)},e.prototype.supportsPing=function(){return Boolean(this.hooks.supportsPing)},e.prototype.connect=function(){var t=this;if(this.socket||"initialized"!==this.state)return!1;var e=this.hooks.urls.getInitial(this.key,this.options);try{this.socket=this.hooks.getSocket(e,this.options)}catch(n){return o["default"].defer(function(){t.onError(n),t.changeState("closed")}),!1}return this.bindListeners(),a["default"].debug("Connecting",{transport:this.name,url:e}),this.changeState("connecting"),!0},e.prototype.close=function(){return this.socket?(this.socket.close(),!0):!1},e.prototype.send=function(t){var e=this;return"open"===this.state?(o["default"].defer(function(){e.socket&&e.socket.send(t)}),!0):!1},e.prototype.ping=function(){"open"===this.state&&this.supportsPing()&&this.socket.ping()},e.prototype.onOpen=function(){this.hooks.beforeOpen&&this.hooks.beforeOpen(this.socket,this.hooks.urls.getPath(this.key,this.options)),this.changeState("open"),this.socket.onopen=void 0},e.prototype.onError=function(t){this.emit("error",{type:"WebSocketError",error:t}),this.timeline.error(this.buildTimelineMessage({error:t.toString()}))},e.prototype.onClose=function(t){t?this.changeState("closed",{code:t.code,reason:t.reason,wasClean:t.wasClean}):this.changeState("closed"),this.unbindListeners(),this.socket=void 0},e.prototype.onMessage=function(t){this.emit("message",t)},e.prototype.onActivity=function(){this.emit("activity")},e.prototype.bindListeners=function(){var t=this;this.socket.onopen=function(){t.onOpen()},this.socket.onerror=function(e){t.onError(e)},this.socket.onclose=function(e){t.onClose(e)},this.socket.onmessage=function(e){t.onMessage(e)},this.supportsPing()&&(this.socket.onactivity=function(){t.onActivity()})},e.prototype.unbindListeners=function(){this.socket&&(this.socket.onopen=void 0,this.socket.onerror=void 0,this.socket.onclose=void 0,this.socket.onmessage=void 0,this.supportsPing()&&(this.socket.onactivity=void 0))},e.prototype.changeState=function(t,e){this.state=t,this.timeline.info(this.buildTimelineMessage({state:t,params:e})),this.emit(t,e)},e.prototype.buildTimelineMessage=function(t){return r.extend({cid:this.id},t)},e}(s["default"]);e.__esModule=!0,e["default"]=u},function(t,e,n){"use strict";var i=n(24),o=Function("return this")(),r=function(){function t(t){this.callbacks=new i["default"],this.global_callbacks=[],this.failThrough=t}return t.prototype.bind=function(t,e,n){return this.callbacks.add(t,e,n),this},t.prototype.bind_all=function(t){return this.global_callbacks.push(t),this},t.prototype.unbind=function(t,e,n){return this.callbacks.remove(t,e,n),this},t.prototype.unbind_all=function(t,e){return this.callbacks.remove(t,e),this},t.prototype.emit=function(t,e){var n;for(n=0;n<this.global_callbacks.length;n++)this.global_callbacks[n](t,e);var i=this.callbacks.get(t);if(i&&i.length>0)for(n=0;n<i.length;n++)i[n].fn.call(i[n].context||o,e);else this.failThrough&&this.failThrough(t,e);return this},t}();e.__esModule=!0,e["default"]=r},function(t,e,n){"use strict";function i(t){return"_"+t}var o=n(9),r=function(){function t(){this._callbacks={}}return t.prototype.get=function(t){return this._callbacks[i(t)]},t.prototype.add=function(t,e,n){var o=i(t);this._callbacks[o]=this._callbacks[o]||[],this._callbacks[o].push({fn:e,context:n})},t.prototype.remove=function(t,e,n){if(!t&&!e&&!n)return void(this._callbacks={});var r=t?[i(t)]:o.keys(this._callbacks);e||n?this.removeCallback(r,e,n):this.removeAllCallbacks(r)},t.prototype.removeCallback=function(t,e,n){o.apply(t,function(t){this._callbacks[t]=o.filter(this._callbacks[t]||[],function(t){return e&&e!==t.fn||n&&n!==t.context}),0===this._callbacks[t].length&&delete this._callbacks[t]},this)},t.prototype.removeAllCallbacks=function(t){o.apply(t,function(t){delete this._callbacks[t]},this)},t}();e.__esModule=!0,e["default"]=r},function(t,e,n){"use strict";var i=this&&this.__extends||function(t,e){function n(){this.constructor=t}for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)},o=n(23),r=function(t){function e(){t.call(this);var e=this;void 0!==window.addEventListener&&(window.addEventListener("online",function(){e.emit("online")},!1),window.addEventListener("offline",function(){e.emit("offline")},!1))}return i(e,t),e.prototype.isOnline=function(){return void 0===window.navigator.onLine?!0:window.navigator.onLine},e}(o["default"]);e.NetInfo=r,e.Network=new r},function(t,e){"use strict";var n=function(t){var e;return e=t.encrypted?[":best_connected_ever",":ws_loop",[":delayed",2e3,[":http_fallback_loop"]]]:[":best_connected_ever",":ws_loop",[":delayed",2e3,[":wss_loop"]],[":delayed",5e3,[":http_fallback_loop"]]],[[":def","ws_options",{hostUnencrypted:t.wsHost+":"+t.wsPort,hostEncrypted:t.wsHost+":"+t.wssPort}],[":def","wss_options",[":extend",":ws_options",{encrypted:!0}]],[":def","sockjs_options",{hostUnencrypted:t.httpHost+":"+t.httpPort,hostEncrypted:t.httpHost+":"+t.httpsPort,httpPath:t.httpPath}],[":def","timeouts",{loop:!0,timeout:15e3,timeoutLimit:6e4}],[":def","ws_manager",[":transport_manager",{lives:2,minPingDelay:1e4,maxPingDelay:t.activity_timeout}]],[":def","streaming_manager",[":transport_manager",{lives:2,minPingDelay:1e4,maxPingDelay:t.activity_timeout}]],[":def_transport","ws","ws",3,":ws_options",":ws_manager"],[":def_transport","wss","ws",3,":wss_options",":ws_manager"],[":def_transport","sockjs","sockjs",1,":sockjs_options"],[":def_transport","xhr_streaming","xhr_streaming",1,":sockjs_options",":streaming_manager"],[":def_transport","xdr_streaming","xdr_streaming",1,":sockjs_options",":streaming_manager"],[":def_transport","xhr_polling","xhr_polling",1,":sockjs_options"],[":def_transport","xdr_polling","xdr_polling",1,":sockjs_options"],[":def","ws_loop",[":sequential",":timeouts",":ws"]],[":def","wss_loop",[":sequential",":timeouts",":wss"]],[":def","sockjs_loop",[":sequential",":timeouts",":sockjs"]],[":def","streaming_loop",[":sequential",":timeouts",[":if",[":is_supported",":xhr_streaming"],":xhr_streaming",":xdr_streaming"]]],[":def","polling_loop",[":sequential",":timeouts",[":if",[":is_supported",":xhr_polling"],":xhr_polling",":xdr_polling"]]],[":def","http_loop",[":if",[":is_supported",":streaming_loop"],[":best_connected_ever",":streaming_loop",[":delayed",4e3,[":polling_loop"]]],[":polling_loop"]]],[":def","http_fallback_loop",[":if",[":is_supported",":http_loop"],[":http_loop"],[":sockjs_loop"]]],[":def","strategy",[":cached",18e5,[":first_connected",[":if",[":is_supported",":ws"],e,":http_fallback_loop"]]]]]};e.__esModule=!0,e["default"]=n},function(t,e,n){"use strict";function i(){var t=this;t.timeline.info(t.buildTimelineMessage({transport:t.name+(t.options.encrypted?"s":"")})),t.hooks.isInitialized()?t.changeState("initialized"):t.hooks.file?(t.changeState("initializing"),o.Dependencies.load(t.hooks.file,{encrypted:t.options.encrypted},function(e,n){t.hooks.isInitialized()?(t.changeState("initialized"),n(!0)):(e&&t.onError(e),t.onClose(),n(!1))})):t.onClose()}var o=n(3);e.__esModule=!0,e["default"]=i},function(t,e,n){"use strict";var i=n(29),o=n(31);o["default"].createXDR=function(t,e){return this.createRequest(i["default"],t,e)},e.__esModule=!0,e["default"]=o["default"]},function(t,e,n){"use strict";var i=n(30),o={getRequest:function(t){var e=new window.XDomainRequest;return e.ontimeout=function(){t.emit("error",new i.RequestTimedOut),t.close()},e.onerror=function(e){t.emit("error",e),t.close()},e.onprogress=function(){e.responseText&&e.responseText.length>0&&t.onChunk(200,e.responseText)},e.onload=function(){e.responseText&&e.responseText.length>0&&t.onChunk(200,e.responseText),t.emit("finished",200),t.close()},e},abortRequest:function(t){t.ontimeout=t.onerror=t.onprogress=t.onload=null,t.abort()}};e.__esModule=!0,e["default"]=o},function(t,e){"use strict";var n=this&&this.__extends||function(t,e){function n(){this.constructor=t}for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)},i=function(t){function e(){t.apply(this,arguments)}return n(e,t),e}(Error);e.BadEventName=i;var o=function(t){function e(){t.apply(this,arguments)}return n(e,t),e}(Error);e.RequestTimedOut=o;var r=function(t){function e(){t.apply(this,arguments)}return n(e,t),e}(Error);e.TransportPriorityTooLow=r;var s=function(t){function e(){t.apply(this,arguments)}return n(e,t),e}(Error);e.TransportClosed=s;var a=function(t){function e(){t.apply(this,arguments)}return n(e,t),e}(Error);e.UnsupportedTransport=a;var c=function(t){function e(){t.apply(this,arguments)}return n(e,t),e}(Error);e.UnsupportedStrategy=c},function(t,e,n){"use strict";var i=n(32),o=n(33),r=n(35),s=n(36),a=n(37),c={createStreamingSocket:function(t){return this.createSocket(r["default"],t)},createPollingSocket:function(t){return this.createSocket(s["default"],t)},createSocket:function(t,e){return new o["default"](t,e)},createXHR:function(t,e){return this.createRequest(a["default"],t,e)},createRequest:function(t,e,n){return new i["default"](t,e,n)}};e.__esModule=!0,e["default"]=c},function(t,e,n){"use strict";var i=this&&this.__extends||function(t,e){function n(){this.constructor=t}for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)},o=n(2),r=n(23),s=262144,a=function(t){function e(e,n,i){t.call(this),this.hooks=e,this.method=n,this.url=i}return i(e,t),e.prototype.start=function(t){var e=this;this.position=0,this.xhr=this.hooks.getRequest(this),this.unloader=function(){e.close()},o["default"].addUnloadListener(this.unloader),this.xhr.open(this.method,this.url,!0),this.xhr.setRequestHeader&&this.xhr.setRequestHeader("Content-Type","application/json"),this.xhr.send(t)},e.prototype.close=function(){this.unloader&&(o["default"].removeUnloadListener(this.unloader),this.unloader=null),this.xhr&&(this.hooks.abortRequest(this.xhr),this.xhr=null)},e.prototype.onChunk=function(t,e){for(;;){var n=this.advanceBuffer(e);if(!n)break;this.emit("chunk",{status:t,data:n})}this.isBufferTooLong(e)&&this.emit("buffer_too_long")},e.prototype.advanceBuffer=function(t){var e=t.slice(this.position),n=e.indexOf("\n");return-1!==n?(this.position+=n+1,e.slice(0,n)):null},e.prototype.isBufferTooLong=function(t){return this.position===t.length&&t.length>s},e}(r["default"]);e.__esModule=!0,e["default"]=a},function(t,e,n){"use strict";function i(t){var e=/([^\?]*)\/*(\??.*)/.exec(t);return{base:e[1],queryString:e[2]}}function o(t,e){return t.base+"/"+e+"/xhr_send"}function r(t){var e=-1===t.indexOf("?")?"?":"&";return t+e+"t="+ +new Date+"&n="+f++}function s(t,e){var n=/(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(t);return n[1]+e+n[3]}function a(t){return Math.floor(Math.random()*t)}function c(t){for(var e=[],n=0;t>n;n++)e.push(a(32).toString(32));return e.join("")}var u=n(34),l=n(11),h=n(2),f=1,p=function(){function t(t,e){this.hooks=t,this.session=a(1e3)+"/"+c(8),this.location=i(e),this.readyState=u["default"].CONNECTING,this.openStream()}return t.prototype.send=function(t){return this.sendRaw(JSON.stringify([t]))},t.prototype.ping=function(){this.hooks.sendHeartbeat(this)},t.prototype.close=function(t,e){this.onClose(t,e,!0)},t.prototype.sendRaw=function(t){if(this.readyState!==u["default"].OPEN)return!1;try{return h["default"].createSocketRequest("POST",r(o(this.location,this.session))).start(t),!0}catch(e){return!1}},t.prototype.reconnect=function(){this.closeStream(),this.openStream()},t.prototype.onClose=function(t,e,n){this.closeStream(),this.readyState=u["default"].CLOSED,this.onclose&&this.onclose({code:t,reason:e,wasClean:n})},t.prototype.onChunk=function(t){if(200===t.status){this.readyState===u["default"].OPEN&&this.onActivity();var e,n=t.data.slice(0,1);switch(n){case"o":e=JSON.parse(t.data.slice(1)||"{}"),
this.onOpen(e);break;case"a":e=JSON.parse(t.data.slice(1)||"[]");for(var i=0;i<e.length;i++)this.onEvent(e[i]);break;case"m":e=JSON.parse(t.data.slice(1)||"null"),this.onEvent(e);break;case"h":this.hooks.onHeartbeat(this);break;case"c":e=JSON.parse(t.data.slice(1)||"[]"),this.onClose(e[0],e[1],!0)}}},t.prototype.onOpen=function(t){this.readyState===u["default"].CONNECTING?(t&&t.hostname&&(this.location.base=s(this.location.base,t.hostname)),this.readyState=u["default"].OPEN,this.onopen&&this.onopen()):this.onClose(1006,"Server lost session",!0)},t.prototype.onEvent=function(t){this.readyState===u["default"].OPEN&&this.onmessage&&this.onmessage({data:t})},t.prototype.onActivity=function(){this.onactivity&&this.onactivity()},t.prototype.onError=function(t){this.onerror&&this.onerror(t)},t.prototype.openStream=function(){var t=this;this.stream=h["default"].createSocketRequest("POST",r(this.hooks.getReceiveURL(this.location,this.session))),this.stream.bind("chunk",function(e){t.onChunk(e)}),this.stream.bind("finished",function(e){t.hooks.onFinished(t,e)}),this.stream.bind("buffer_too_long",function(){t.reconnect()});try{this.stream.start()}catch(e){l["default"].defer(function(){t.onError(e),t.onClose(1006,"Could not start streaming",!1)})}},t.prototype.closeStream=function(){this.stream&&(this.stream.unbind_all(),this.stream.close(),this.stream=null)},t}();e.__esModule=!0,e["default"]=p},function(t,e){"use strict";var n;!function(t){t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSED=3]="CLOSED"}(n||(n={})),e.__esModule=!0,e["default"]=n},function(t,e){"use strict";var n={getReceiveURL:function(t,e){return t.base+"/"+e+"/xhr_streaming"+t.queryString},onHeartbeat:function(t){t.sendRaw("[]")},sendHeartbeat:function(t){t.sendRaw("[]")},onFinished:function(t,e){t.onClose(1006,"Connection interrupted ("+e+")",!1)}};e.__esModule=!0,e["default"]=n},function(t,e){"use strict";var n={getReceiveURL:function(t,e){return t.base+"/"+e+"/xhr"+t.queryString},onHeartbeat:function(){},sendHeartbeat:function(t){t.sendRaw("[]")},onFinished:function(t,e){200===e?t.reconnect():t.onClose(1006,"Connection interrupted ("+e+")",!1)}};e.__esModule=!0,e["default"]=n},function(t,e,n){"use strict";var i=n(2),o={getRequest:function(t){var e=i["default"].getXHRAPI(),n=new e;return n.onreadystatechange=n.onprogress=function(){switch(n.readyState){case 3:n.responseText&&n.responseText.length>0&&t.onChunk(n.status,n.responseText);break;case 4:n.responseText&&n.responseText.length>0&&t.onChunk(n.status,n.responseText),t.emit("finished",n.status),t.close()}},n},abortRequest:function(t){t.onreadystatechange=null,t.abort()}};e.__esModule=!0,e["default"]=o},function(t,e,n){"use strict";var i=n(9),o=n(11),r=n(39),s=function(){function t(t,e,n){this.key=t,this.session=e,this.events=[],this.options=n||{},this.sent=0,this.uniqueID=0}return t.prototype.log=function(t,e){t<=this.options.level&&(this.events.push(i.extend({},e,{timestamp:o["default"].now()})),this.options.limit&&this.events.length>this.options.limit&&this.events.shift())},t.prototype.error=function(t){this.log(r["default"].ERROR,t)},t.prototype.info=function(t){this.log(r["default"].INFO,t)},t.prototype.debug=function(t){this.log(r["default"].DEBUG,t)},t.prototype.isEmpty=function(){return 0===this.events.length},t.prototype.send=function(t,e){var n=this,o=i.extend({session:this.session,bundle:this.sent+1,key:this.key,lib:"js",version:this.options.version,cluster:this.options.cluster,features:this.options.features,timeline:this.events},this.options.params);return this.events=[],t(o,function(t,i){t||n.sent++,e&&e(t,i)}),!0},t.prototype.generateUniqueID=function(){return this.uniqueID++,this.uniqueID},t}();e.__esModule=!0,e["default"]=s},function(t,e){"use strict";var n;!function(t){t[t.ERROR=3]="ERROR",t[t.INFO=6]="INFO",t[t.DEBUG=7]="DEBUG"}(n||(n={})),e.__esModule=!0,e["default"]=n},function(t,e,n){"use strict";function i(t){return function(e){return[t.apply(this,arguments),e]}}function o(t){return"string"==typeof t&&":"===t.charAt(0)}function r(t,e){return e[t.slice(1)]}function s(t,e){if(0===t.length)return[[],e];var n=u(t[0],e),i=s(t.slice(1),n[1]);return[[n[0]].concat(i[0]),i[1]]}function a(t,e){if(!o(t))return[t,e];var n=r(t,e);if(void 0===n)throw"Undefined symbol "+t;return[n,e]}function c(t,e){if(o(t[0])){var n=r(t[0],e);if(t.length>1){if("function"!=typeof n)throw"Calling non-function "+t[0];var i=[l.extend({},e)].concat(l.map(t.slice(1),function(t){return u(t,l.extend({},e))[0]}));return n.apply(this,i)}return[n,e]}return s(t,e)}function u(t,e){return"string"==typeof t?a(t,e):"object"==typeof t&&t instanceof Array&&t.length>0?c(t,e):[t,e]}var l=n(9),h=n(11),f=n(41),p=n(30),d=n(55),y=n(56),m=n(57),v=n(58),g=n(59),_=n(60),b=n(61),k=n(2),w=k["default"].Transports;e.build=function(t,e){var n=l.extend({},C,e);return u(t,n)[1].strategy};var S={isSupported:function(){return!1},connect:function(t,e){var n=h["default"].defer(function(){e(new p.UnsupportedStrategy)});return{abort:function(){n.ensureAborted()},forceMinPriority:function(){}}}},C={extend:function(t,e,n){return[l.extend({},e,n),t]},def:function(t,e,n){if(void 0!==t[e])throw"Redefining symbol "+e;return t[e]=n,[void 0,t]},def_transport:function(t,e,n,i,o,r){var s=w[n];if(!s)throw new p.UnsupportedTransport(n);var a,c=!(t.enabledTransports&&-1===l.arrayIndexOf(t.enabledTransports,e)||t.disabledTransports&&-1!==l.arrayIndexOf(t.disabledTransports,e));a=c?new d["default"](e,i,r?r.getAssistant(s):s,l.extend({key:t.key,encrypted:t.encrypted,timeline:t.timeline,ignoreNullOrigin:t.ignoreNullOrigin},o)):S;var u=t.def(t,e,a)[1];return u.Transports=t.Transports||{},u.Transports[e]=a,[void 0,u]},transport_manager:i(function(t,e){return new f["default"](e)}),sequential:i(function(t,e){var n=Array.prototype.slice.call(arguments,2);return new y["default"](n,e)}),cached:i(function(t,e,n){return new v["default"](n,t.Transports,{ttl:e,timeline:t.timeline,encrypted:t.encrypted})}),first_connected:i(function(t,e){return new b["default"](e)}),best_connected_ever:i(function(){var t=Array.prototype.slice.call(arguments,1);return new m["default"](t)}),delayed:i(function(t,e,n){return new g["default"](n,{delay:e})}),"if":i(function(t,e,n,i){return new _["default"](e,n,i)}),is_supported:i(function(t,e){return function(){return e.isSupported()}})}},function(t,e,n){"use strict";var i=n(42),o=function(){function t(t){this.options=t||{},this.livesLeft=this.options.lives||1/0}return t.prototype.getAssistant=function(t){return i["default"].createAssistantToTheTransportManager(this,t,{minPingDelay:this.options.minPingDelay,maxPingDelay:this.options.maxPingDelay})},t.prototype.isAlive=function(){return this.livesLeft>0},t.prototype.reportDeath=function(){this.livesLeft-=1},t}();e.__esModule=!0,e["default"]=o},function(t,e,n){"use strict";var i=n(43),o=n(44),r=n(47),s=n(48),a=n(49),c=n(50),u=n(51),l=n(53),h=n(54),f={createChannels:function(){return new h["default"]},createConnectionManager:function(t,e){return new l["default"](t,e)},createChannel:function(t,e){return new u["default"](t,e)},createPrivateChannel:function(t,e){return new c["default"](t,e)},createPresenceChannel:function(t,e){return new a["default"](t,e)},createTimelineSender:function(t,e){return new s["default"](t,e)},createAuthorizer:function(t,e){return new r["default"](t,e)},createHandshake:function(t,e){return new o["default"](t,e)},createAssistantToTheTransportManager:function(t,e,n){return new i["default"](t,e,n)}};e.__esModule=!0,e["default"]=f},function(t,e,n){"use strict";var i=n(11),o=n(9),r=function(){function t(t,e,n){this.manager=t,this.transport=e,this.minPingDelay=n.minPingDelay,this.maxPingDelay=n.maxPingDelay,this.pingDelay=void 0}return t.prototype.createConnection=function(t,e,n,r){var s=this;r=o.extend({},r,{activityTimeout:this.pingDelay});var a=this.transport.createConnection(t,e,n,r),c=null,u=function(){a.unbind("open",u),a.bind("closed",l),c=i["default"].now()},l=function(t){if(a.unbind("closed",l),1002===t.code||1003===t.code)s.manager.reportDeath();else if(!t.wasClean&&c){var e=i["default"].now()-c;e<2*s.maxPingDelay&&(s.manager.reportDeath(),s.pingDelay=Math.max(e/2,s.minPingDelay))}};return a.bind("open",u),a},t.prototype.isSupported=function(t){return this.manager.isAlive()&&this.transport.isSupported(t)},t}();e.__esModule=!0,e["default"]=r},function(t,e,n){"use strict";var i=n(9),o=n(45),r=n(46),s=function(){function t(t,e){this.transport=t,this.callback=e,this.bindListeners()}return t.prototype.close=function(){this.unbindListeners(),this.transport.close()},t.prototype.bindListeners=function(){var t=this;this.onMessage=function(e){t.unbindListeners();var n;try{n=o.processHandshake(e)}catch(i){return t.finish("error",{error:i}),void t.transport.close()}"connected"===n.action?t.finish("connected",{connection:new r["default"](n.id,t.transport),activityTimeout:n.activityTimeout}):(t.finish(n.action,{error:n.error}),t.transport.close())},this.onClosed=function(e){t.unbindListeners();var n=o.getCloseAction(e)||"backoff",i=o.getCloseError(e);t.finish(n,{error:i})},this.transport.bind("message",this.onMessage),this.transport.bind("closed",this.onClosed)},t.prototype.unbindListeners=function(){this.transport.unbind("message",this.onMessage),this.transport.unbind("closed",this.onClosed)},t.prototype.finish=function(t,e){this.callback(i.extend({transport:this.transport,action:t},e))},t}();e.__esModule=!0,e["default"]=s},function(t,e){"use strict";e.decodeMessage=function(t){try{var e=JSON.parse(t.data);if("string"==typeof e.data)try{e.data=JSON.parse(e.data)}catch(n){if(!(n instanceof SyntaxError))throw n}return e}catch(n){throw{type:"MessageParseError",error:n,data:t.data}}},e.encodeMessage=function(t){return JSON.stringify(t)},e.processHandshake=function(t){if(t=e.decodeMessage(t),"pusher:connection_established"===t.event){if(!t.data.activity_timeout)throw"No activity timeout specified in handshake";return{action:"connected",id:t.data.socket_id,activityTimeout:1e3*t.data.activity_timeout}}if("pusher:error"===t.event)return{action:this.getCloseAction(t.data),error:this.getCloseError(t.data)};throw"Invalid handshake"},e.getCloseAction=function(t){return t.code<4e3?t.code>=1002&&t.code<=1004?"backoff":null:4e3===t.code?"ssl_only":t.code<4100?"refused":t.code<4200?"backoff":t.code<4300?"retry":"refused"},e.getCloseError=function(t){return 1e3!==t.code&&1001!==t.code?{type:"PusherError",data:{code:t.code,message:t.reason||t.message}}:null}},function(t,e,n){"use strict";var i=this&&this.__extends||function(t,e){function n(){this.constructor=t}for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)},o=n(9),r=n(23),s=n(45),a=n(8),c=function(t){function e(e,n){t.call(this),this.id=e,this.transport=n,this.activityTimeout=n.activityTimeout,this.bindListeners()}return i(e,t),e.prototype.handlesActivityChecks=function(){return this.transport.handlesActivityChecks()},e.prototype.send=function(t){return this.transport.send(t)},e.prototype.send_event=function(t,e,n){var i={event:t,data:e};return n&&(i.channel=n),a["default"].debug("Event sent",i),this.send(s.encodeMessage(i))},e.prototype.ping=function(){this.transport.supportsPing()?this.transport.ping():this.send_event("pusher:ping",{})},e.prototype.close=function(){this.transport.close()},e.prototype.bindListeners=function(){var t=this,e={message:function(e){var n;try{n=s.decodeMessage(e)}catch(i){t.emit("error",{type:"MessageParseError",error:i,data:e.data})}if(void 0!==n){switch(a["default"].debug("Event recd",n),n.event){case"pusher:error":t.emit("error",{type:"PusherError",data:n.data});break;case"pusher:ping":t.emit("ping");break;case"pusher:pong":t.emit("pong")}t.emit("message",n)}},activity:function(){t.emit("activity")},error:function(e){t.emit("error",{type:"WebSocketError",error:e})},closed:function(e){n(),e&&e.code&&t.handleCloseEvent(e),t.transport=null,t.emit("closed")}},n=function(){o.objectApply(e,function(e,n){t.transport.unbind(n,e)})};o.objectApply(e,function(e,n){t.transport.bind(n,e)})},e.prototype.handleCloseEvent=function(t){var e=s.getCloseAction(t),n=s.getCloseError(t);n&&this.emit("error",n),e&&this.emit(e)},e}(r["default"]);e.__esModule=!0,e["default"]=c},function(t,e,n){"use strict";var i=n(2),o=function(){function t(t,e){this.channel=t;var n=e.authTransport;if("undefined"==typeof i["default"].getAuthorizers()[n])throw"'"+n+"' is not a recognized auth transport";this.type=n,this.options=e,this.authOptions=(e||{}).auth||{}}return t.prototype.composeQuery=function(t){var e="socket_id="+encodeURIComponent(t)+"&channel_name="+encodeURIComponent(this.channel.name);for(var n in this.authOptions.params)e+="&"+encodeURIComponent(n)+"="+encodeURIComponent(this.authOptions.params[n]);return e},t.prototype.authorize=function(e,n){return t.authorizers=t.authorizers||i["default"].getAuthorizers(),t.authorizers[this.type].call(this,i["default"],e,n)},t}();e.__esModule=!0,e["default"]=o},function(t,e,n){"use strict";var i=n(2),o=function(){function t(t,e){this.timeline=t,this.options=e||{}}return t.prototype.send=function(t,e){this.timeline.isEmpty()||this.timeline.send(i["default"].TimelineTransport.getAgent(this,t),e)},t}();e.__esModule=!0,e["default"]=o},function(t,e,n){"use strict";var i=this&&this.__extends||function(t,e){function n(){this.constructor=t}for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)},o=n(50),r=n(8),s=n(52),a=function(t){function e(e,n){t.call(this,e,n),this.members=new s["default"]}return i(e,t),e.prototype.authorize=function(e,n){var i=this;t.prototype.authorize.call(this,e,function(t,e){if(!t){if(void 0===e.channel_data)return r["default"].warn("Invalid auth response for channel '"+i.name+"', expected 'channel_data' field"),void n("Invalid auth response");var o=JSON.parse(e.channel_data);i.members.setMyID(o.user_id)}n(t,e)})},e.prototype.handleEvent=function(t,e){switch(t){case"pusher_internal:subscription_succeeded":this.members.onSubscription(e),this.subscribed=!0,this.emit("pusher:subscription_succeeded",this.members);break;case"pusher_internal:member_added":var n=this.members.addMember(e);this.emit("pusher:member_added",n);break;case"pusher_internal:member_removed":var i=this.members.removeMember(e);i&&this.emit("pusher:member_removed",i);break;default:o["default"].prototype.handleEvent.call(this,t,e)}},e.prototype.disconnect=function(){this.members.reset(),t.prototype.disconnect.call(this)},e}(o["default"]);e.__esModule=!0,e["default"]=a},function(t,e,n){"use strict";var i=this&&this.__extends||function(t,e){function n(){this.constructor=t}for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)},o=n(42),r=n(51),s=function(t){function e(){t.apply(this,arguments)}return i(e,t),e.prototype.authorize=function(t,e){var n=o["default"].createAuthorizer(this,this.pusher.config);return n.authorize(t,e)},e}(r["default"]);e.__esModule=!0,e["default"]=s},function(t,e,n){"use strict";var i=this&&this.__extends||function(t,e){function n(){this.constructor=t}for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)},o=n(23),r=n(30),s=n(8),a=function(t){function e(e,n){t.call(this,function(t,n){s["default"].debug("No callbacks on "+e+" for "+t)}),this.name=e,this.pusher=n,this.subscribed=!1}return i(e,t),e.prototype.authorize=function(t,e){return e(!1,{})},e.prototype.trigger=function(t,e){if(0!==t.indexOf("client-"))throw new r.BadEventName("Event '"+t+"' does not start with 'client-'");return this.pusher.send_event(t,e,this.name)},e.prototype.disconnect=function(){this.subscribed=!1},e.prototype.handleEvent=function(t,e){0===t.indexOf("pusher_internal:")?"pusher_internal:subscription_succeeded"===t&&(this.subscribed=!0,this.emit("pusher:subscription_succeeded",e)):this.emit(t,e)},e.prototype.subscribe=function(){var t=this;this.authorize(this.pusher.connection.socket_id,function(e,n){e?t.handleEvent("pusher:subscription_error",n):t.pusher.send_event("pusher:subscribe",{auth:n.auth,channel_data:n.channel_data,channel:t.name})})},e.prototype.unsubscribe=function(){this.pusher.send_event("pusher:unsubscribe",{channel:this.name})},e}(o["default"]);e.__esModule=!0,e["default"]=a},function(t,e,n){"use strict";var i=n(9),o=function(){function t(){this.reset()}return t.prototype.get=function(t){return Object.prototype.hasOwnProperty.call(this.members,t)?{id:t,info:this.members[t]}:null},t.prototype.each=function(t){var e=this;i.objectApply(this.members,function(n,i){t(e.get(i))})},t.prototype.setMyID=function(t){this.myID=t},t.prototype.onSubscription=function(t){this.members=t.presence.hash,this.count=t.presence.count,this.me=this.get(this.myID)},t.prototype.addMember=function(t){return null===this.get(t.user_id)&&this.count++,this.members[t.user_id]=t.user_info,this.get(t.user_id)},t.prototype.removeMember=function(t){var e=this.get(t.user_id);return e&&(delete this.members[t.user_id],this.count--),e},t.prototype.reset=function(){this.members={},this.count=0,this.myID=null,this.me=null},t}();e.__esModule=!0,e["default"]=o},function(t,e,n){"use strict";var i=this&&this.__extends||function(t,e){function n(){this.constructor=t}for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)},o=n(23),r=n(12),s=n(8),a=n(9),c=n(2),u=function(t){function e(e,n){var i=this;t.call(this),this.key=e,this.options=n||{},this.state="initialized",this.connection=null,this.encrypted=!!n.encrypted,this.timeline=this.options.timeline,this.connectionCallbacks=this.buildConnectionCallbacks(),this.errorCallbacks=this.buildErrorCallbacks(),this.handshakeCallbacks=this.buildHandshakeCallbacks(this.errorCallbacks);var o=c["default"].getNetwork();o.bind("online",function(){i.timeline.info({netinfo:"online"}),("connecting"===i.state||"unavailable"===i.state)&&i.retryIn(0)}),o.bind("offline",function(){i.timeline.info({netinfo:"offline"}),i.connection&&i.sendActivityCheck()}),this.updateStrategy()}return i(e,t),e.prototype.connect=function(){if(!this.connection&&!this.runner){if(!this.strategy.isSupported())return void this.updateState("failed");this.updateState("connecting"),this.startConnecting(),this.setUnavailableTimer()}},e.prototype.send=function(t){return this.connection?this.connection.send(t):!1},e.prototype.send_event=function(t,e,n){return this.connection?this.connection.send_event(t,e,n):!1},e.prototype.disconnect=function(){this.disconnectInternally(),this.updateState("disconnected")},e.prototype.isEncrypted=function(){return this.encrypted},e.prototype.startConnecting=function(){var t=this,e=function(n,i){n?t.runner=t.strategy.connect(0,e):"error"===i.action?(t.emit("error",{type:"HandshakeError",error:i.error}),t.timeline.error({handshakeError:i.error})):(t.abortConnecting(),t.handshakeCallbacks[i.action](i))};this.runner=this.strategy.connect(0,e)},e.prototype.abortConnecting=function(){this.runner&&(this.runner.abort(),this.runner=null)},e.prototype.disconnectInternally=function(){if(this.abortConnecting(),this.clearRetryTimer(),this.clearUnavailableTimer(),this.connection){var t=this.abandonConnection();t.close()}},e.prototype.updateStrategy=function(){this.strategy=this.options.getStrategy({key:this.key,timeline:this.timeline,encrypted:this.encrypted})},e.prototype.retryIn=function(t){var e=this;this.timeline.info({action:"retry",delay:t}),t>0&&this.emit("connecting_in",Math.round(t/1e3)),this.retryTimer=new r.OneOffTimer(t||0,function(){e.disconnectInternally(),e.connect()})},e.prototype.clearRetryTimer=function(){this.retryTimer&&(this.retryTimer.ensureAborted(),this.retryTimer=null)},e.prototype.setUnavailableTimer=function(){var t=this;this.unavailableTimer=new r.OneOffTimer(this.options.unavailableTimeout,function(){t.updateState("unavailable")})},e.prototype.clearUnavailableTimer=function(){this.unavailableTimer&&this.unavailableTimer.ensureAborted()},e.prototype.sendActivityCheck=function(){var t=this;this.stopActivityCheck(),this.connection.ping(),this.activityTimer=new r.OneOffTimer(this.options.pongTimeout,function(){t.timeline.error({pong_timed_out:t.options.pongTimeout}),t.retryIn(0)})},e.prototype.resetActivityCheck=function(){var t=this;this.stopActivityCheck(),this.connection.handlesActivityChecks()||(this.activityTimer=new r.OneOffTimer(this.activityTimeout,function(){t.sendActivityCheck()}))},e.prototype.stopActivityCheck=function(){this.activityTimer&&this.activityTimer.ensureAborted()},e.prototype.buildConnectionCallbacks=function(){var t=this;return{message:function(e){t.resetActivityCheck(),t.emit("message",e)},ping:function(){t.send_event("pusher:pong",{})},activity:function(){t.resetActivityCheck()},error:function(e){t.emit("error",{type:"WebSocketError",error:e})},closed:function(){t.abandonConnection(),t.shouldRetry()&&t.retryIn(1e3)}}},e.prototype.buildHandshakeCallbacks=function(t){var e=this;return a.extend({},t,{connected:function(t){e.activityTimeout=Math.min(e.options.activityTimeout,t.activityTimeout,t.connection.activityTimeout||1/0),e.clearUnavailableTimer(),e.setConnection(t.connection),e.socket_id=e.connection.id,e.updateState("connected",{socket_id:e.socket_id})}})},e.prototype.buildErrorCallbacks=function(){var t=this,e=function(e){return function(n){n.error&&t.emit("error",{type:"WebSocketError",error:n.error}),e(n)}};return{ssl_only:e(function(){t.encrypted=!0,t.updateStrategy(),t.retryIn(0)}),refused:e(function(){t.disconnect()}),backoff:e(function(){t.retryIn(1e3)}),retry:e(function(){t.retryIn(0)})}},e.prototype.setConnection=function(t){this.connection=t;for(var e in this.connectionCallbacks)this.connection.bind(e,this.connectionCallbacks[e]);this.resetActivityCheck()},e.prototype.abandonConnection=function(){if(this.connection){this.stopActivityCheck();for(var t in this.connectionCallbacks)this.connection.unbind(t,this.connectionCallbacks[t]);var e=this.connection;return this.connection=null,e}},e.prototype.updateState=function(t,e){var n=this.state;if(this.state=t,n!==t){var i=t;"connected"===i&&(i+=" with new socket ID "+e.socket_id),s["default"].debug("State changed",n+" -> "+i),this.timeline.info({state:t,params:e}),this.emit("state_change",{previous:n,current:t}),this.emit(t,e)}},e.prototype.shouldRetry=function(){return"connecting"===this.state||"connected"===this.state},e}(o["default"]);e.__esModule=!0,e["default"]=u},function(t,e,n){"use strict";function i(t,e){return 0===t.indexOf("private-")?r["default"].createPrivateChannel(t,e):0===t.indexOf("presence-")?r["default"].createPresenceChannel(t,e):r["default"].createChannel(t,e)}var o=n(9),r=n(42),s=function(){function t(){this.channels={}}return t.prototype.add=function(t,e){return this.channels[t]||(this.channels[t]=i(t,e)),this.channels[t]},t.prototype.all=function(){return o.values(this.channels)},t.prototype.find=function(t){return this.channels[t]},t.prototype.remove=function(t){var e=this.channels[t];return delete this.channels[t],e},t.prototype.disconnect=function(){o.objectApply(this.channels,function(t){t.disconnect()})},t}();e.__esModule=!0,e["default"]=s},function(t,e,n){"use strict";function i(t,e){return r["default"].defer(function(){e(t)}),{abort:function(){},forceMinPriority:function(){}}}var o=n(42),r=n(11),s=n(30),a=n(9),c=function(){function t(t,e,n,i){this.name=t,this.priority=e,this.transport=n,this.options=i||{}}return t.prototype.isSupported=function(){return this.transport.isSupported({encrypted:this.options.encrypted})},t.prototype.connect=function(t,e){var n=this;if(!this.isSupported())return i(new s.UnsupportedStrategy,e);if(this.priority<t)return i(new s.TransportPriorityTooLow,e);var r=!1,c=this.transport.createConnection(this.name,this.priority,this.options.key,this.options),u=null,l=function(){c.unbind("initialized",l),c.connect()},h=function(){u=o["default"].createHandshake(c,function(t){r=!0,d(),e(null,t)})},f=function(t){d(),e(t)},p=function(){d();var t;try{t=JSON.stringify(c)}catch(n){t=a.safeJSONStringify(c)}e(new s.TransportClosed(t))},d=function(){c.unbind("initialized",l),c.unbind("open",h),c.unbind("error",f),c.unbind("closed",p)};return c.bind("initialized",l),c.bind("open",h),c.bind("error",f),c.bind("closed",p),c.initialize(),{abort:function(){r||(d(),u?u.close():c.close())},forceMinPriority:function(t){r||n.priority<t&&(u?u.close():c.close())}}},t}();e.__esModule=!0,e["default"]=c},function(t,e,n){"use strict";var i=n(9),o=n(11),r=n(12),s=function(){function t(t,e){this.strategies=t,this.loop=Boolean(e.loop),this.failFast=Boolean(e.failFast),this.timeout=e.timeout,this.timeoutLimit=e.timeoutLimit}return t.prototype.isSupported=function(){return i.any(this.strategies,o["default"].method("isSupported"))},t.prototype.connect=function(t,e){var n=this,i=this.strategies,o=0,r=this.timeout,s=null,a=function(c,u){u?e(null,u):(o+=1,n.loop&&(o%=i.length),o<i.length?(r&&(r=2*r,n.timeoutLimit&&(r=Math.min(r,n.timeoutLimit))),s=n.tryStrategy(i[o],t,{timeout:r,failFast:n.failFast},a)):e(!0))};return s=this.tryStrategy(i[o],t,{timeout:r,failFast:this.failFast},a),{abort:function(){s.abort()},forceMinPriority:function(e){t=e,s&&s.forceMinPriority(e)}}},t.prototype.tryStrategy=function(t,e,n,i){var o=null,s=null;return n.timeout>0&&(o=new r.OneOffTimer(n.timeout,function(){s.abort(),i(!0)})),s=t.connect(e,function(t,e){t&&o&&o.isRunning()&&!n.failFast||(o&&o.ensureAborted(),i(t,e))}),{abort:function(){o&&o.ensureAborted(),s.abort()},forceMinPriority:function(t){s.forceMinPriority(t)}}},t}();e.__esModule=!0,e["default"]=s},function(t,e,n){"use strict";function i(t,e,n){var i=s.map(t,function(t,i,o,r){return t.connect(e,n(i,r))});return{abort:function(){s.apply(i,r)},forceMinPriority:function(t){s.apply(i,function(e){e.forceMinPriority(t)})}}}function o(t){return s.all(t,function(t){return Boolean(t.error)})}function r(t){t.error||t.aborted||(t.abort(),t.aborted=!0)}var s=n(9),a=n(11),c=function(){function t(t){this.strategies=t}return t.prototype.isSupported=function(){return s.any(this.strategies,a["default"].method("isSupported"))},t.prototype.connect=function(t,e){return i(this.strategies,t,function(t,n){return function(i,r){return n[t].error=i,i?void(o(n)&&e(!0)):(s.apply(n,function(t){t.forceMinPriority(r.transport.priority)}),void e(null,r))}})},t}();e.__esModule=!0,e["default"]=c},function(t,e,n){"use strict";function i(t){return"pusherTransport"+(t?"Encrypted":"Unencrypted")}function o(t){var e=c["default"].getLocalStorage();if(e)try{var n=e[i(t)];if(n)return JSON.parse(n)}catch(o){s(t)}return null}function r(t,e,n){var o=c["default"].getLocalStorage();if(o)try{o[i(t)]=JSON.stringify({timestamp:a["default"].now(),transport:e,latency:n})}catch(r){}}function s(t){var e=c["default"].getLocalStorage();if(e)try{delete e[i(t)]}catch(n){}}var a=n(11),c=n(2),u=n(56),l=function(){function t(t,e,n){this.strategy=t,this.transports=e,this.ttl=n.ttl||18e5,this.encrypted=n.encrypted,this.timeline=n.timeline}return t.prototype.isSupported=function(){return this.strategy.isSupported()},t.prototype.connect=function(t,e){var n=this.encrypted,i=o(n),c=[this.strategy];if(i&&i.timestamp+this.ttl>=a["default"].now()){var l=this.transports[i.transport];l&&(this.timeline.info({cached:!0,transport:i.transport,latency:i.latency}),c.push(new u["default"]([l],{timeout:2*i.latency+1e3,failFast:!0})))}var h=a["default"].now(),f=c.pop().connect(t,function p(i,o){i?(s(n),c.length>0?(h=a["default"].now(),f=c.pop().connect(t,p)):e(i)):(r(n,o.transport.name,a["default"].now()-h),e(null,o))});return{abort:function(){f.abort()},forceMinPriority:function(e){t=e,f&&f.forceMinPriority(e)}}},t}();e.__esModule=!0,e["default"]=l},function(t,e,n){"use strict";var i=n(12),o=function(){function t(t,e){var n=e.delay;this.strategy=t,this.options={delay:n}}return t.prototype.isSupported=function(){return this.strategy.isSupported()},t.prototype.connect=function(t,e){var n,o=this.strategy,r=new i.OneOffTimer(this.options.delay,function(){n=o.connect(t,e)});return{abort:function(){r.ensureAborted(),n&&n.abort()},forceMinPriority:function(e){t=e,n&&n.forceMinPriority(e)}}},t}();e.__esModule=!0,e["default"]=o},function(t,e){"use strict";var n=function(){function t(t,e,n){this.test=t,this.trueBranch=e,this.falseBranch=n}return t.prototype.isSupported=function(){var t=this.test()?this.trueBranch:this.falseBranch;return t.isSupported()},t.prototype.connect=function(t,e){var n=this.test()?this.trueBranch:this.falseBranch;return n.connect(t,e)},t}();e.__esModule=!0,e["default"]=n},function(t,e){"use strict";var n=function(){function t(t){this.strategy=t}return t.prototype.isSupported=function(){return this.strategy.isSupported()},t.prototype.connect=function(t,e){var n=this.strategy.connect(t,function(t,i){i&&n.abort(),e(t,i)});return n},t}();e.__esModule=!0,e["default"]=n},function(t,e,n){"use strict";var i=n(5);e.getGlobalConfig=function(){return{wsHost:i["default"].host,wsPort:i["default"].ws_port,wssPort:i["default"].wss_port,httpHost:i["default"].sockjs_host,httpPort:i["default"].sockjs_http_port,httpsPort:i["default"].sockjs_https_port,httpPath:i["default"].sockjs_path,statsHost:i["default"].stats_host,authEndpoint:i["default"].channel_auth_endpoint,authTransport:i["default"].channel_auth_transport,activity_timeout:i["default"].activity_timeout,pong_timeout:i["default"].pong_timeout,unavailable_timeout:i["default"].unavailable_timeout}},e.getClusterConfig=function(t){return{wsHost:"ws-"+t+".pusher.com",httpHost:"sockjs-"+t+".pusher.com"}}}])});
| 6,175.4 | 32,023 | 0.732163 |
6fcb63273e31bee19b7c0be810babf5ee34ccfb6 | 7,808 | js | JavaScript | ethereumcontract/runtime.js | unvYoda/EthereumC2Plugin | 4dad907462261c9d2f22f045039bbee67b8d4e89 | [
"MIT"
] | null | null | null | ethereumcontract/runtime.js | unvYoda/EthereumC2Plugin | 4dad907462261c9d2f22f045039bbee67b8d4e89 | [
"MIT"
] | null | null | null | ethereumcontract/runtime.js | unvYoda/EthereumC2Plugin | 4dad907462261c9d2f22f045039bbee67b8d4e89 | [
"MIT"
] | null | null | null | // ECMAScript 5 strict mode
"use strict";
assert2(cr, "cr namespace not created");
assert2(cr.plugins_, "cr.plugins_ not created");
/////////////////////////////////////
// Plugin class
cr.plugins_.EthereumContract = function(runtime)
{
this.runtime = runtime;
};
(function ()
{
var pluginProto = cr.plugins_.EthereumContract.prototype;
/////////////////////////////////////
// Object type class
pluginProto.Type = function(plugin)
{
this.plugin = plugin;
this.runtime = plugin.runtime;
};
var typeProto = pluginProto.Type.prototype;
var runtime;
var currentEvent;
typeProto.onCreate = function()
{
};
/////////////////////////////////////
// Instance class
pluginProto.Instance = function(type)
{
this.type = type;
this.runtime = type.runtime;
};
var instanceProto = pluginProto.Instance.prototype;
instanceProto.onCreate = function()
{
if (this.runtime.isDomFree)
{
cr.logexport("[Construct 2] EthereumContract plugin not supported on this platform - the object will not be created");
return;
}
this.runtime.tickMe(this);
runtime = this.runtime;
var contractABI = JSON.parse(this.properties[0]);
var MyContract = web3.eth.contract(contractABI);
var contractAddress;
switch (web3.version.network)
{
//Expanse
case "2": contractAddress = this.properties[1]; break;
//Mainnet
case "1": contractAddress = this.properties[1]; break;
//Ropsten
case "3": contractAddress = this.properties[2]; break;
//Kovan
case "42": contractAddress = this.properties[3]; break;
//Rinkeby
case "4": contractAddress = this.properties[4]; break;
//Unknown
default: cr.logexport("This ethereum network is not supported by this ethereum plugin."); return;
}
if (!contractAddress)
{
cr.logexport("This ethereum network is not supported by this dapp.");
return;
}
this.contractInstance = MyContract.at(contractAddress);
this.currentCallbackId = "";
this.currentCallbackResponse = "";
this.currentCallbackError = "";
var events = this.contractInstance.allEvents();
// watch for changes
var self = this;
events.watch(function(err, ev){
if (!err)
{
self.currentEvent = ev;
runtime.trigger(pluginProto.cnds.OnEvent, self);
}
});
};
instanceProto.tick = function ()
{
};
instanceProto.onLayoutChange = function ()
{
};
//////////////////////////////////////
// Conditions
function Cnds() {};
Cnds.prototype.OnFunctionSuccess = function (id)
{
return id == '' || this.currentCallbackId == id;
};
Cnds.prototype.OnFunctionError = function (id)
{
return id == '' || this.currentCallbackId == id;
};
Cnds.prototype.OnFunctionCallback = function (id)
{
return id == '' || this.currentCallbackId == id;
};
Cnds.prototype.OnEvent = function (ev)
{
return this.currentEvent == ev;
};
pluginProto.cnds = new Cnds();
//////////////////////////////////////
// Actions
function Acts() {};
Acts.prototype.Call = function (name, paramsArray, id)
{
var self = this;
if (paramsArray.length == 0 || paramsArray.length == 1 && paramsArray[0] == '')
this.contractInstance[name].call(function (err, res) { self.OnCallback (err, res, id); });
else if (paramsArray.length == 1)
this.contractInstance[name].call(paramsArray[0], function (err, res) { self.OnCallback (err, res, id); });
else if (paramsArray.length == 2)
this.contractInstance[name].call(paramsArray[0], paramsArray[1], function (err, res) { self.OnCallback (err, res, id); });
else if (paramsArray.length == 3)
this.contractInstance[name].call(paramsArray[0], paramsArray[1], paramsArray[2], function (err, res) { self.OnCallback (err, res, id); });
else if (paramsArray.length == 4)
this.contractInstance[name].call(paramsArray[0], paramsArray[1], paramsArray[2], paramsArray[3], function (err, res) { self.OnCallback (err, res, id); });
else if (paramsArray.length == 5)
this.contractInstance[name].call(paramsArray[0], paramsArray[1], paramsArray[2], paramsArray[3], paramsArray[4], function (err, res) { self.OnCallback (err, res, id); });
}
Acts.prototype.Send = function (name, paramsArray, id, v)
{
var self = this;
if (paramsArray.length == 0 || paramsArray.length == 1 && paramsArray[0] == '')
this.contractInstance[name].sendTransaction({value:v}, function (err, res) { self.OnCallback (err, res, id); });
else if (paramsArray.length == 1)
this.contractInstance[name].sendTransaction(paramsArray[0], {value:v}, function (err, res) { self.OnCallback (err, res, id); });
else if (paramsArray.length == 2)
this.contractInstance[name].sendTransaction(paramsArray[0], paramsArray[1], {value:v}, function (err, res) { self.OnCallback (err, res, id); });
else if (paramsArray.length == 3)
this.contractInstance[name].sendTransaction(paramsArray[0], paramsArray[1], paramsArray[2], {value:v}, function (err, res) { self.OnCallback (err, res, id); });
else if (paramsArray.length == 4)
this.contractInstance[name].sendTransaction(paramsArray[0], paramsArray[1], paramsArray[2], paramsArray[3], {value:v}, function (err, res) { self.OnCallback (err, res, id); });
else if (paramsArray.length == 5)
this.contractInstance[name].sendTransaction(paramsArray[0], paramsArray[1], paramsArray[2], paramsArray[3], paramsArray[4], {value:v}, function (err, res) { self.OnCallback (err, res, id); });
}
Acts.prototype.EstimateGas = function (name, paramsArray, id)
{
var self = this;
if (paramsArray.length == 0 || paramsArray.length == 1 && paramsArray[0] == '')
this.contractInstance[name].estimateGas(function (err, res) { self.OnCallback (err, res, id); });
else if (paramsArray.length == 1)
this.contractInstance[name].estimateGas(paramsArray[0], function (err, res) { self.OnCallback (err, res, id); });
else if (paramsArray.length == 2)
this.contractInstance[name].estimateGas(paramsArray[0], paramsArray[1], function (err, res) { self.OnCallback (err, res, id); });
else if (paramsArray.length == 3)
this.contractInstance[name].estimateGas(paramsArray[0], paramsArray[1], paramsArray[2], function (err, res) { self.OnCallback (err, res, id); });
else if (paramsArray.length == 4)
this.contractInstance[name].estimateGas(paramsArray[0], paramsArray[1], paramsArray[2], paramsArray[3], function (err, res) { self.OnCallback (err, res, id); });
else if (paramsArray.length == 5)
this.contractInstance[name].estimateGas(paramsArray[0], paramsArray[1], paramsArray[2], paramsArray[3], paramsArray[4], function (err, res) { self.OnCallback (err, res, id); });
}
instanceProto.OnCallback = function(error, result, id)
{
this.currentCallbackId = id;
if (error)
{
this.currentCallbackResponse = "";
this.currentCallbackError = error;
runtime.trigger(cr.plugins_.EthereumContract.prototype.cnds.OnFunctionError, this);
runtime.trigger(cr.plugins_.EthereumContract.prototype.cnds.OnFunctionCallback, this);
}
else
{
this.currentCallbackError = "";
this.currentCallbackResponse = result;
runtime.trigger(cr.plugins_.EthereumContract.prototype.cnds.OnFunctionSuccess, this);
runtime.trigger(cr.plugins_.EthereumContract.prototype.cnds.OnFunctionCallback, this);
}
};
pluginProto.acts = new Acts();
//////////////////////////////////////
// Expressions
function Exps() {};
Exps.prototype.CurrentCallbackId = function (ret)
{
ret.set_string(currentCallbackId);
};
Exps.prototype.CurrentCallbackError = function (ret)
{
ret.set_string(this.currentCallbackError ? this.currentCallbackError.toString() : "");
};
Exps.prototype.CurrentCallbackResponse = function (ret)
{
ret.set_string(this.currentCallbackResponse ? this.currentCallbackResponse.toString() : "");
};
pluginProto.exps = new Exps();
}());
| 33.800866 | 195 | 0.672643 |
6fcbcff38e18d4ab24278670130d2b7e75c092f7 | 444 | js | JavaScript | app/Helpers/Fileupload.js | AhmedMedDev/Node-NoSQL-Auth | 8602048782469ec1cc457524b3f0855bff6b09a9 | [
"MIT"
] | 2 | 2022-02-20T01:53:41.000Z | 2022-03-08T04:02:32.000Z | app/Helpers/Fileupload.js | AhmedMedDev/Node-NoSQL-Auth | 8602048782469ec1cc457524b3f0855bff6b09a9 | [
"MIT"
] | null | null | null | app/Helpers/Fileupload.js | AhmedMedDev/Node-NoSQL-Auth | 8602048782469ec1cc457524b3f0855bff6b09a9 | [
"MIT"
] | null | null | null |
module.exports = {
saveFile (path, file)
{
let today = new Date();
let date = today.getFullYear()+';'+(today.getMonth()+1)+';'+today.getDate();
let time = today.getHours() + "," + today.getMinutes() + "," + today.getSeconds();
let dateTime = `${date}${time}`;
let filename = `${dateTime}${file.name}`
file.mv(`./public/uploads/${path}/${filename}`);
return filename;
}
}; | 27.75 | 90 | 0.527027 |
6fcc03b6040a9b3dda358d11eaa454f4e62126fd | 394 | js | JavaScript | src/standard-library.js | baixiaoji/dropbear | b679a69c8f1f56a4b5449dac246e9d9715e6412a | [
"Apache-2.0"
] | 90 | 2019-05-30T15:21:30.000Z | 2022-03-29T08:08:33.000Z | src/standard-library.js | baixiaoji/dropbear | b679a69c8f1f56a4b5449dac246e9d9715e6412a | [
"Apache-2.0"
] | 5 | 2019-11-12T12:59:34.000Z | 2021-05-09T00:01:31.000Z | src/standard-library.js | wDKidd/icecream | 87e49728c7f47d9e513f8e890a698ca25b8f890a | [
"Apache-2.0"
] | 67 | 2019-05-30T15:21:31.000Z | 2022-03-29T08:08:40.000Z | const all = fn => (...list) => list.reduce(fn);
const add = all((a, b) => a + b);
const subtract = all((a, b) => a - b);
const multiply = all((a, b) => a * b);
const divide = all((a, b) => a / b);
const modulo = all((a, b) => a % b);
const log = console.log;
const environment = {
add,
subtract,
multiply,
divide,
modulo,
log,
pi: Math.PI,
};
module.exports = { environment };
| 18.761905 | 47 | 0.550761 |
6fcc56da81ae3c73f6525e9f2e4f99cc290eee6f | 294 | js | JavaScript | public/main.js | GrafSoul/dictantor-chrome-app | a0dc1c696f552142c051f40463d31e034f22a40b | [
"MIT"
] | null | null | null | public/main.js | GrafSoul/dictantor-chrome-app | a0dc1c696f552142c051f40463d31e034f22a40b | [
"MIT"
] | null | null | null | public/main.js | GrafSoul/dictantor-chrome-app | a0dc1c696f552142c051f40463d31e034f22a40b | [
"MIT"
] | null | null | null | chrome.app.runtime.onLaunched.addListener(function () {
chrome.app.window.create('index.html', {
id: 'root',
innerBounds: {
width: 600,
height: 450,
minWidth: 360,
minHeight: 280,
},
frame: 'none',
});
});
| 22.615385 | 55 | 0.479592 |
6fcc90a6ea572da370ffaf5253fd9709dc29c350 | 133,525 | js | JavaScript | data/mods/ssb/moves.js | TheMezStrikes/Pokemon-Showdown | fc458396f234d126b4fb2ac4beb094b89293cde7 | [
"MIT"
] | null | null | null | data/mods/ssb/moves.js | TheMezStrikes/Pokemon-Showdown | fc458396f234d126b4fb2ac4beb094b89293cde7 | [
"MIT"
] | null | null | null | data/mods/ssb/moves.js | TheMezStrikes/Pokemon-Showdown | fc458396f234d126b4fb2ac4beb094b89293cde7 | [
"MIT"
] | null | null | null | 'use strict';
// Used for bumbadadabum and Snaquaza's move
const RandomStaffBrosTeams = require('./random-teams');
/** @type {typeof import('../../../sim/pokemon').Pokemon} */
const Pokemon = require(/** @type {any} */ ('../../../.sim-dist/pokemon')).Pokemon;
/** @type {{[k: string]: ModdedMoveData}} */
let BattleMovedex = {
/*
// Example
"moveid": {
accuracy: 100, // a number or true for always hits
basePower: 100, // Not used for Status moves, base power of the move, number
category: "Physical", // "Physical", "Special", or "Status"
desc: "", // long description
shortDesc: "", // short description, shows up in /dt
id: "moveid",
name: "Move Name",
pp: 10, // unboosted PP count
priority: 0, // move priority, -6 -> 6
flags: {}, // Move flags https://github.com/Zarel/Pokemon-Showdown/blob/master/data/moves.js#L1-L27
secondary: {
status: "tox",
chance: 20,
}, // secondary, set to null to not use one. Exact usage varies, check data/moves.js for examples
target: "normal", // What does this move hit?
// normal = the targeted foe, self = the user, allySide = your side (eg light screen), foeSide = the foe's side (eg spikes), all = the field (eg raindance). More can be found in data/moves.js
type: "Water", // The move's type
// Other useful things
noPPBoosts: true, // add this to not boost the PP of a move, not needed for Z moves, dont include it otherwise
isZ: "crystalname", // marks a move as a z move, list the crystal name inside
zMoveEffect: '', // for status moves, what happens when this is used as a Z move? check data/moves.js for examples
zMoveBoost: {atk: 2}, // for status moves, stat boost given when used as a z move
critRatio: 2, // The higher the number (above 1) the higher the ratio, lowering it lowers the crit ratio
drain: [1, 2], // recover first num / second num % of the damage dealt
heal: [1, 2], // recover first num / second num % of the target's HP
},
*/
// Please keep sets organized alphabetically based on staff member name!
// 2xTheTap
noblehowl: {
accuracy: true,
basePower: 0,
category: "Status",
desc: "Raises the user's Attack by two stages and cures the user of burns, paralysis, and poison. Removes Reflect, Light Screen, Aurora Veil, Safeguard, and Mist from the opponent's side and removes Spikes, Toxic Spikes, Stealth Rock, and Sticky Web from both sides.",
shortDesc: "Raises Attack by 2, clears hazards/user status.",
id: "noblehowl",
name: "Noble Howl",
isNonstandard: "Custom",
pp: 3,
noPPBoosts: true,
priority: 0,
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Howl', source);
this.add('-anim', source, 'Boomburst', source);
},
onHit(target, source, move) {
this.boost({atk: 2}, source, source, this.getActiveMove('Noble Howl'));
if (!(['', 'slp', 'frz'].includes(source.status))) {
source.cureStatus();
}
let removeTarget = ['reflect', 'lightscreen', 'auroraveil', 'safeguard', 'mist', 'spikes', 'toxicspikes', 'stealthrock', 'stickyweb'];
let removeAll = ['spikes', 'toxicspikes', 'stealthrock', 'stickyweb'];
for (const targetCondition of removeTarget) {
if (target.side.removeSideCondition(targetCondition)) {
if (!removeAll.includes(targetCondition)) continue;
this.add('-sideend', target.side, this.getEffect(targetCondition).name, '[from] move: Noble Howl', '[of] ' + target);
}
}
for (const sideCondition of removeAll) {
if (source.side.removeSideCondition(sideCondition)) {
this.add('-sideend', source.side, this.getEffect(sideCondition).name, '[from] move: Noble Howl', '[of] ' + source);
}
}
},
flags: {mirror: 1, snatch: 1, authentic: 1},
secondary: null,
target: "normal",
type: "Normal",
},
// 5gen
toomuchsaws: {
accuracy: 100,
basePower: 85,
basePowerCallback(pokemon, target, move) {
if (target.newlySwitched) {
return move.basePower * 2;
}
return move.basePower;
},
category: "Physical",
desc: "Base Power doubles if the foe switches out the turn this move is used.",
shortDesc: "Power doubles if foe switches out.",
id: "toomuchsaws",
name: "Too Much Saws",
isNonstandard: "Custom",
pp: 10,
priority: 0,
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Headbutt', target);
},
flags: {protect: 1, mirror: 1, contact: 1},
secondary: null,
target: "normal",
type: "Grass",
},
// ACakeWearingAHat
sparcedance: {
accuracy: true,
category: "Status",
desc: "Boosts the user's Attack, Defense, and Speed by one stage.",
shortDesc: "+1 atk, def, and spe.",
id: "sparcedance",
name: "Sparce Dance",
isNonstandard: "Custom",
pp: 15,
priority: 0,
flags: {snatch: 1, mirror: 1, dance: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Quiver Dance", source);
},
boosts: {atk: 1, def: 1, spe: 1},
secondary: null,
target: "self",
type: "Normal",
},
// Aelita
energyfield: {
accuracy: 100,
basePower: 140,
category: "Special",
desc: "Has a 40% chance to paralyze the target. Lowers the user's Special Attack, Special Defense, and Speed by one stage.",
shortDesc: "40% to paralyze. Lowers user's SpA, SpD, Spe.",
id: "energyfield",
name: "Energy Field",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {protect: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Electro Ball", target);
this.add('-anim', source, "Ion Deluge", target);
},
self: {boosts: {spa: -1, spd: -1, spe: -1}},
secondary: {
chance: 40,
status: 'par',
},
target: "normal",
type: "Electric",
zMovePower: 200,
},
// Akir
compost: {
accuracy: true,
category: "Status",
desc: "The user recovers half their HP. If any of the user's allies fainted the previous turn, this move heals the active Pokemon by 50% of the user's HP on the following turn. Cures the user's party of all status conditions.",
shortDesc: "Heal 50%; cures party; If ally fainted last turn: wish.",
id: "compost",
name: "Compost",
isNonstandard: "Custom",
pp: 5,
priority: 0,
flags: {snatch: 1, heal: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Ingrain", target);
},
onHit(target, source) {
let didSomething = false;
let side = source.side;
if (side.faintedLastTurn) {
this.add('-anim', source, "Wish", target);
side.addSlotCondition(source, 'wish', source);
this.add('-message', `${source.name} made a wish!`);
didSomething = true;
}
for (const ally of side.pokemon) {
if (ally.cureStatus()) didSomething = true;
}
if (this.heal(source.maxhp / 2, source)) didSomething = true;
return didSomething;
},
secondary: null,
target: "self",
type: "Ghost",
},
// Amaluna
turismosplash: {
accuracy: true,
basePower: 0,
category: "Status",
desc: "Summons Trick Room and raises the user's Special Attack by one stage.",
shortDesc: "User's Sp. Atk +1; sets Trick Room.",
id: "turismosplash",
name: "Turismo Splash",
isNonstandard: "Custom",
pp: 5,
priority: -6,
onModifyMove(move) {
if (!this.field.pseudoWeather.trickroom) {
move.pseudoWeather = 'trickroom';
}
},
flags: {snatch: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Coil", source);
this.add('-anim', source, "Extreme Evoboost", source);
},
boosts: {
spa: 1,
},
secondary: null,
target: "self",
type: "Water",
},
// Andy
pilfer: {
accuracy: 100,
basePower: 70,
category: "Physical",
desc: "If the target uses certain non-damaging moves this turn, the user steals the move to use itself. This move fails if no move is stolen or if the user is under the effect of Sky Drop.",
shortDesc: "Steals foe's move. Fails if target attacks. Priority.",
id: "pilfer",
name: "Pilfer",
isNonstandard: "Custom",
pp: 5,
priority: 1,
flags: {protect: 1, mirror: 1, contact: 1, authentic: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onTryHit(target, source) {
let decision = this.willMove(target);
if (decision) {
let move = this.getActiveMove(decision.move.id);
if (move.category === 'Status' && move.id !== 'mefirst' && move.target) {
if (['all', 'adjacentAllyOrSelf', 'allySide', 'allyTeam', 'self'].includes(move.target)) {
this.useMove(move, source, source);
} else {
this.useMove(move, source, target);
}
this.add('-anim', source, "Sucker Punch", target);
this.add('-anim', source, "Night Slash", target);
return;
}
}
return false;
},
volatileStatus: 'pilfer',
effect: {
// Simulate the snatch effect while being able to use the pilfered move 1st
duration: 1,
onStart() {
},
onBeforeMovePriority: 3,
onBeforeMove(pokemon, target, move) {
if (move.category === 'Status') {
this.add('-message', move.name + ' was pilfered and unable to be used.');
return false;
}
},
},
target: "normal",
type: "Dark",
},
// ant
truant: {
accuracy: 100,
basePower: 100,
category: "Physical",
desc: "The target's ability is changed to Truant if this move hits.",
shortDesc: "Changes the target's ability to Truant.",
id: "truant",
name: "TRU ANT",
isNonstandard: "Custom",
pp: 5,
flags: {protect: 1, mirror: 1, contact: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Sunsteel Strike', target);
},
onHit(pokemon) {
if (pokemon.ability === 'truant') return;
let oldAbility = pokemon.setAbility('truant');
if (oldAbility) {
this.add('-ability', pokemon, 'Truant', '[from] move: TRU ANT');
return;
}
return false;
},
target: "normal",
type: "Steel",
},
// A Quag to The Past
murkyambush: {
accuracy: true,
basePower: 150,
category: "Physical",
desc: "This move fails unless a foe uses a contact move on the user before the user can execute the move on the same turn. If this move is successful, the foe's move has its secondary effects suppressed and damage halved. If the user survives a hit, it attacks, and the effect ends.",
shortDesc: "User must be hit by a contact move before moving.",
id: "murkyambush",
name: "Murky Ambush",
isNonstandard: "Custom",
pp: 20,
priority: -3,
flags: {contact: 1, protect: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
if (source.volatiles['murkyambush'] && source.volatiles['murkyambush'].gotHit) {
this.add('-anim', source, "Crunch", target);
}
},
beforeTurnCallback(pokemon) {
pokemon.addVolatile('murkyambush');
this.add('-message', `${pokemon.name} anticipates the opposing Pokémon's next move!`);
this.attrLastMove('[still]');
this.add('-anim', pokemon, "Work Up", pokemon);
},
beforeMoveCallback(pokemon) {
if (pokemon.volatiles['murkyambush'] && !pokemon.volatiles['murkyambush'].gotHit) {
this.add('cant', pokemon, 'Murky Ambush', 'Murky Ambush');
this.add('-message', `${pokemon.name} eases up.`);
return true;
}
this.add('-message', `${pokemon.side.foe.active[0].name} was caught in the ambush!`);
},
effect: {
duration: 1,
onStart(pokemon) {
this.add('-singleturn', pokemon, 'move: Murky Ambush');
},
onBasePowerPriority: 7,
onSourceBasePower() {
this.debug('Murky Ambush weaken');
return this.chainModify(0.5);
},
onFoeTryMove(target, source, move) {
if (move.secondaries && move.flags.contact) {
this.debug('Murky Ambush secondary effects suppression');
delete move.secondaries;
}
},
onHit(pokemon, source, move) {
if (pokemon.side !== source.side && move.flags.contact) {
pokemon.volatiles['murkyambush'].gotHit = true;
}
},
},
target: "normal",
type: "Dark",
},
// Arcticblast
trashalanche: {
basePower: 80,
basePowerCallback(pokemon, target, move) {
let noitem = 0;
for (const foes of target.side.pokemon) {
if (!foes.item) noitem += 20;
}
return move.basePower + noitem;
},
accuracy: 100,
category: "Physical",
desc: "This move's Base Power increases by 20 for every foe that is not holding an item.",
shortDesc: "+20 power for each item-less opponent.",
id: "trashalanche",
name: "Trashalanche",
isNonstandard: "Custom",
pp: 10,
flags: {protect: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Gunk Shot", target);
},
secondary: null,
target: "normal",
type: "Poison",
},
// Arsenal
comeonyougunners: {
accuracy: 100,
basePower: 100,
category: "Special",
desc: "This move's type depends on the user's held Plate. If the target has the same type as this move, its Base Power is boosted by 1.5x.",
shortDesc: "Type = Plate. 1.5x power if foe has the move's type.",
id: "comeonyougunners",
name: "Come on you Gunners",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {protect: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source, move) {
this.add('-anim', source, 'Judgment', target);
this.add('-anim', target, 'Extreme Evoboost', target);
// Modifying BP here so it happens AFTER ModifyMove
if (target.types.includes(move.type)) {
this.debug('Come on you Gunners BP boost');
move.basePower = move.basePower * 1.5;
}
},
onModifyMove(move, pokemon) {
const item = pokemon.getItem();
if (item.id && item.onPlate && !item.zMove) {
this.debug(`Come on you Gunners type changed to: ${item.onPlate}`);
move.type = item.onPlate;
}
},
secondary: null,
target: "normal",
type: "Normal",
},
// Beowulf
buzzingoftheswarm: {
accuracy: 100,
basePower: 95,
category: "Physical",
desc: "Has a 20% chance to cause the target to flinch.",
shortDesc: "20% chance to flinch.",
id: "buzzingoftheswarm",
name: "Buzzing of the Swarm",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {protect: 1, mirror: 1, sound: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Bug Buzz', source);
},
secondary: {
chance: 20,
volatileStatus: 'flinch',
},
target: "normal",
type: "Bug",
},
// Bhris Brown
finalimpact: {
basePower: 85,
accuracy: 100,
category: "Physical",
desc: "This move summons Rain Dance and boosts the user's Defense by one stage.",
shortDesc: "User's Def +1. Summons Rain Dance.",
id: "finalimpact",
name: "Final Impact",
isNonstandard: "Custom",
pp: 5,
priority: 0,
flags: {mirror: 1, protect: 1, contact: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Meteor Mash', target);
},
onAfterMoveSecondarySelf() {
this.field.setWeather('raindance');
},
secondary: {
chance: 100,
self: {
boosts: {
def: 1,
},
},
},
target: "normal",
type: "Fighting",
},
// biggie
foodrush: {
accuracy: 100,
basePower: 100,
category: "Physical",
desc: "If both the user and the target have not fainted, the target is forced to switch out to a random non-fained ally. This effect fails if the target used Ingrain previously, has the Suction Cups ability, or is behind a Substitute.",
shortDesc: "Forces the target to switch to a random ally.",
id: "foodrush",
name: "Food Rush",
isNonstandard: "Custom",
pp: 10,
priority: -6,
flags: {protect: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Stockpile', source);
this.add('-anim', source, 'Spit Up', target);
},
forceSwitch: true,
secondary: null,
target: "normal",
type: "Normal",
},
// Bimp
triviaroom: {
accuracy: true,
basePower: 0,
category: "Status",
desc: "For 5 turns, the user is immune to Ground-type moves and the effects of Arena Trap, and the Speed of every Pokemon is recalculated for the purposes of determining turn order: every Pokemon's Speed is considered to be 10000 - its normal Speed, and if this value is greater than 8191, 8192 is subtracted from it. The effects of Ingrain, Smack Down, and Thousand Arrows do not cause this move to fail, but they still ground the user, as does Iron Ball. This move does not fail if the user is under the effect of Magnet Rise or this move, but it does not extend the duration. This move fails if the user is not Bimp.",
shortDesc: "Bimp: 5 turns: slower Pokemon move first, user levitates.",
id: "triviaroom",
name: "Trivia Room",
isNonstandard: "Custom",
pp: 5,
priority: -7,
flags: {},
onTryMove() {
this.attrLastMove('[still]');
},
onTryHit(target, source) {
if (source.name !== 'Bimp') {
this.add('-fail', source);
this.hint("Only Bimp can use Trivia Room.");
return null;
}
},
onPrepareHit(target, source) {
this.add('-anim', source, "Trick Room", source);
},
pseudoWeather: 'triviaroom',
effect: {
duration: 5,
durationCallback(source, effect) {
if (source && source.hasAbility('persistent')) {
this.add('-activate', source, 'ability: Persistent', effect);
return 7;
}
return 5;
},
onStart(target, source) {
this.add('-fieldstart', 'move: Trivia Room', '[of] ' + source);
this.add('-message', `${source.name} is levitating due to its big trivia brain!`);
},
onRestart(target, source) {
this.field.removePseudoWeather('triviaroom');
},
// Speed modification is changed in Pokemon.getActionSpeed() in mods/seasonal/scripts.js
// Levitation is handled in Pokemon.isGrounded in mods/seasonal/scripts.js
onResidualOrder: 23,
onEnd() {
this.add('-fieldend', 'move: Trivia Room');
this.add('-message', `Certain Pokemon are no longer levitating.`);
},
},
secondary: null,
target: "self",
type: "Psychic",
},
// bobochan
thousandcircuitoverload: {
accuracy: 100,
basePower: 90,
category: "Physical",
desc: "If the target is a Ground-type and is immune to Electric due to its typing, this move deals neutral damage regardless of other types, and the target loses its type-based immunity to Electric.",
shortDesc: "First hit neutral on Ground; removes its immunity.",
id: "thousandcircuitoverload",
name: "Thousand Circuit Overload",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {protect: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Plasma Fists', target);
},
onEffectiveness(typeMod, target, type, move) {
if (move.type !== 'Electric') return;
if (!target) return; // avoid crashing when called from a chat plugin
if (!target.runImmunity('Electric')) {
if (target.hasType('Ground')) return 0;
}
},
volatileStatus: 'thousandcircuitoverload',
effect: {
noCopy: true,
onStart(pokemon) {
this.add('-start', pokemon, 'Thousand Circuit Overload');
},
onNegateImmunity(pokemon, type) {
if (pokemon.hasType('Ground') && type === 'Electric') return false;
},
},
ignoreImmunity: {'Electric': true},
secondary: null,
target: "normal",
type: "Electric",
},
// Brandon
blusterywinds: {
accuracy: 100,
basePower: 60,
category: "Special",
desc: "Removes Reflect, Light Screen, Aurora Veil, Safeguard, Mist, Spikes, Toxic Spikes, Stealth Rock, and Sticky Web from both sides, and it removes any active weather condition or Terrain.",
shortDesc: "Removes all field conditions and hazards.",
id: "blusterywinds",
name: "Blustery Winds",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {protect: 1, mirror: 1, authentic: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Defog", target);
},
onHit(target, source, move) {
let removeAll = ['reflect', 'lightscreen', 'auroraveil', 'safeguard', 'mist', 'spikes', 'toxicspikes', 'stealthrock', 'stickyweb'];
let silentRemove = ['reflect', 'lightscreen', 'auroraveil', 'safeguard', 'mist'];
for (const sideCondition of removeAll) {
if (target.side.removeSideCondition(sideCondition)) {
if (!(silentRemove.includes(sideCondition))) this.add('-sideend', target.side, this.getEffect(sideCondition).name, '[from] move: Blustery Winds', '[of] ' + source);
}
if (source.side.removeSideCondition(sideCondition)) {
if (!(silentRemove.includes(sideCondition))) this.add('-sideend', source.side, this.getEffect(sideCondition).name, '[from] move: Blustery Winds', '[of] ' + source);
}
}
this.field.clearWeather();
this.field.clearTerrain();
},
secondary: null,
target: "normal",
type: "Flying",
},
// bumbadadabum
wondertrade: {
accuracy: true,
category: "Status",
desc: "Replaces every non-fainted member of the user's team with a Super Staff Bros. Brawl set that is randomly selected from all sets, except those with the move Wonder Trade. Remaining HP and PP percentages, as well as status conditions, are transferred onto the replacement sets This move fails if it's used by a Pokemon that does not originally know this move. This move fails if the user is not bumbadadabum.",
shortDesc: "Replaces user's team with random StaffBros. sets.",
id: "wondertrade",
name: "Wonder Trade",
isNonstandard: "Custom",
pp: 2,
noPPBoosts: true,
priority: 0,
flags: {},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Amnesia', source);
this.add('-anim', source, 'Double Team', source);
},
onTryHit(target, source) {
if (source.name !== 'bumbadadabum') {
this.add('-fail', source);
this.hint("Only bumbadadabum can use Wonder Trade.");
return null;
}
},
onHit(target, source) {
// Store percent of HP left, percent of PP left, and status for each pokemon on the user's team
let carryOver = [];
let currentTeam = source.side.pokemon;
for (let pokemon of currentTeam) {
carryOver.push({
hp: pokemon.hp / pokemon.maxhp,
status: pokemon.status,
statusData: pokemon.statusData,
pp: pokemon.moveSlots.slice().map(m => {
return m.pp / m.maxpp;
}),
});
// Handle pokemon with less than 4 moves
while (carryOver[carryOver.length - 1].pp.length < 4) {
carryOver[carryOver.length - 1].pp.push(1);
}
}
// Generate a new team
let team = this.teamGenerator.getTeam({name: source.side.name});
// Overwrite un-fainted pokemon other than the user
for (let i = 0; i < currentTeam.length; i++) {
if (currentTeam[i].fainted || !currentTeam[i].hp || currentTeam[i].position === source.position) continue;
let set = team.shift();
let oldSet = carryOver[i];
// @ts-ignore
if (set.name === 'bumbadadabum') {
// No way am I allowing 2 of this mon on one team
set = team.shift();
}
// Bit of a hack so client doesn't crash when formeChange is called for the new pokemon
let effect = this.effect;
this.effect = /** @type {Effect} */ ({id: ''});
// @ts-ignore
let pokemon = new Pokemon(set, source.side);
this.effect = effect;
pokemon.hp = Math.floor(pokemon.maxhp * oldSet.hp) || 1;
pokemon.status = oldSet.status;
if (oldSet.statusData) pokemon.statusData = oldSet.statusData;
for (const [j, moveSlot] of pokemon.moveSlots.entries()) {
moveSlot.pp = Math.floor(moveSlot.maxpp * oldSet.pp[j]);
}
pokemon.position = currentTeam[i].position;
currentTeam[i] = pokemon;
}
this.add('message', `${source.name} wonder traded ${source.side.name}'s team away!`);
},
target: "self",
type: "Psychic",
},
// cant say
aesthetislash: {
accuracy: 100,
basePower: 100,
category: "Physical",
desc: "Summons Grassy Terrain. If the user is an Aegislash, it changes forme to Aegislash-Blade, attacks, then goes back to its base forme.",
shortDesc: "Summons Grassy Terrain. Aegislash transforms.",
id: "aesthetislash",
name: "a e s t h e t i s l a s h",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {protect: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Geomancy', source);
this.add('-anim', source, 'Swords Dance', source);
this.add('-anim', source, 'Bloom Doom', target);
},
onAfterMoveSecondarySelf() {
this.field.setTerrain('grassyterrain');
},
onAfterMove(pokemon) {
if (pokemon.template.baseSpecies !== 'Aegislash' || pokemon.transformed) return;
if (pokemon.template.species !== 'Aegislash') pokemon.formeChange('Aegislash');
},
target: "normal",
type: "Steel",
},
// cc
restartingrouter: {
accuracy: true,
category: "Status",
desc: "Raises the user's Special Attack by 2 stages and its Speed by 1 stage.",
shortDesc: "Raises the user's Sp. Atk by 2 and Speed by 1.",
id: "restartingrouter",
name: "Restarting Router",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {mirror: 1, snatch: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Charge', source);
},
boosts: {spa: 2, spe: 1},
secondary: null,
target: "self",
type: "Electric",
},
// Ceteris
bringerofdarkness: {
accuracy: true,
category: "Status",
desc: "Has a 50% chance to cause the target to fall asleep. Sets one layer of Spikes on the opponent's side of the field and boosts a random stat of the user by one stage, excluding accuracy and evasion, that is not already at maximum.",
shortDesc: "50% chance to sleep. Sets 1 Spike. Boosts a stat.",
id: "bringerofdarkness",
name: "Bringer of Darkness",
isNonstandard: "Custom",
pp: 5,
priority: 0,
flags: {reflectable: 1, mirror: 1, snatch: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Dark Void", target);
},
onHit(target, source, move) {
this.add('-anim', source, "Spikes", target);
target.side.addSideCondition('spikes');
let stats = [];
for (let stat in source.boosts) {
// @ts-ignore
if (stat !== 'accuracy' && stat !== 'evasion' && source.boosts[stat] < 6) {
stats.push(stat);
}
}
if (stats.length) {
let randomStat = this.sample(stats);
/** @type {{[stat: string]: number}} */
let boost = {};
boost[randomStat] = 1;
this.boost(boost, source);
}
},
secondary: {
chance: 50,
status: 'slp',
},
target: "normal",
type: "Dark",
},
// Cerberax
blimpcrash: {
accuracy: true,
basePower: 165,
category: "Physical",
desc: "80% Accuracy if target is grounded. The user and the target will be grounded, and the user will take 1/2 of the damage inflicted as recoil.",
shortDesc: "80 Acc vs grounded, grounds both sides, 1/2 recoil.",
id: "blimpcrash",
name: "Blimp Crash",
isNonstandard: "Custom",
pp: 5,
priority: 0,
flags: {mirror: 1, protect: 1, contact: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onModifyMove(move, source, target) {
if (target.isGrounded()) {
move.accuracy = 80;
}
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Head Smash', target);
this.add('-anim', source, 'Earthquake', target);
},
onHit(target, source) {
target.addVolatile('smackdown');
source.addVolatile('smackdown');
},
secondary: null,
recoil: [1, 2],
target: "normal",
type: "Flying",
},
// chaos
forcewin: {
accuracy: 100,
basePower: 0,
category: "Status",
desc: "Confuses the target and subjects it to the effects of Taunt, Torment, Heal Block, and Embargo.",
shortDesc: "Ensures domination of the opponent.",
id: "forcewin",
name: "Forcewin",
isNonstandard: "Custom",
pp: 15,
priority: 0,
flags: {protect: 1, reflectable: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Entrainment", target);
this.add('-anim', source, "Lock On", target);
},
onHit(target, source) {
target.addVolatile('taunt', source);
target.addVolatile('embargo', source);
target.addVolatile('torment', source);
target.addVolatile('confusion', source);
target.addVolatile('healblock', source);
this.add(`c|~chaos|/forcewin chaos`);
if (this.random(1000) === 420) {
// Should almost never happen, but will be hilarious when it does.
// Basically, roll a 1000 sided die, if it lands on 420 forcibly give the user's trainer the win
this.add(`c|~chaos|Actually`);
this.add(`c|~chaos|/forcewin ${source.side.name}`);
this.win(source.side);
}
},
secondary: null,
target: "normal",
type: "???",
},
// Chloe
beskyttelsesnet: {
accuracy: true,
category: "Status",
desc: "The user faints and sets Reflect, Light Screen, and Safeguard.",
shortDesc: "User faints; sets screens/Safeguard for 5 turns.",
id: "beskyttelsesnet",
name: "beskyttelsesnet",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {mirror: 1, snatch: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Geomancy', source);
this.add('-anim', source, 'Memento', target);
},
onHit(target, source) {
source.side.addSideCondition('lightscreen', source);
source.side.addSideCondition('reflect', source);
source.side.addSideCondition('safeguard', source);
},
selfdestruct: "ifHit",
secondary: null,
target: "self",
type: "Dark",
},
// Cleo
lovingembrace: {
accuracy: 100,
basePower: 80,
category: "Special",
desc: "This move has a 50% chance to infatuate the target.",
shortDesc: "This move has a 50% chance to infatuate the target.",
id: "lovingembrace",
name: "Loving Embrace",
isNonstandard: "Custom",
pp: 25,
priority: 0,
flags: {protect: 1, mirror: 1, contact: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Wrap", target);
this.add('-anim', source, "Liquidation", target);
this.add('-anim', source, "Surf", target);
},
secondary: {
chance: 50,
volatileStatus: 'attract',
},
target: "normal",
type: "Water",
},
// deg
luciddreams: {
accuracy: 75,
category: "Status",
desc: "The foe falls asleep and is inflicted with the effects of Nightmare and Leech Seed. The user loses 1/2 of their maximum HP unless this move had no effect.",
shortDesc: "Loses 1/2 HP. Foe: sleep, Nightmare, Leech Seed.",
id: "luciddreams",
name: "Lucid Dreams",
isNonstandard: "Custom",
pp: 5,
priority: 0,
flags: {mirror: 1, snatch: 1, reflectable: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Dark Void', target);
this.add('-anim', source, 'Night Shade', target);
},
onHit(target, source, move) {
let hadEffect = false;
if (target.trySetStatus('slp')) hadEffect = true;
if (target.addVolatile('nightmare')) hadEffect = true;
if (!target.hasType('Grass')) {
if (target.addVolatile('leechseed')) hadEffect = true;
}
if (!hadEffect) {
this.add('-fail', target);
} else {
this.damage(source.maxhp / 2, source, source, 'recoil');
}
},
secondary: null,
target: "normal",
type: "Ghost",
},
// DragonWhale
earthsblessing: {
accuracy: true,
basePower: 0,
category: "Status",
desc: "Sets Gravity, raises the user's Attack by 2 stages, and cure's the user's burn, paralysis, or poison. Fails if Gravity is already in effect.",
shortDesc: "Sets Gravity, raises Attack by 2, cures status.",
id: "earthsblessing",
name: "Earth's Blessing",
isNonstandard: "Custom",
pp: 5,
priority: 0,
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Swords Dance', source);
this.add('-anim', source, 'Wood Hammer', source);
},
onHit(pokemon, move) {
if (this.field.pseudoWeather.gravity) return false;
this.boost({atk: 2}, pokemon, pokemon, this.getActiveMove('EarthsBlessing'));
this.field.addPseudoWeather('gravity');
if (['', 'slp', 'frz'].includes(pokemon.status)) return;
pokemon.cureStatus();
},
flags: {mirror: 1, snatch: 1},
secondary: null,
target: "self",
type: "Ground",
zMoveEffect: 'healhalf',
},
// duck
holyduck: {
accuracy: 95,
basePower: 90,
category: "Physical",
desc: "If this attack hits, the effects of Reflect, Light Screen, and Aurora Veil end on the target's side of the field before damage is calculated.",
shortDesc: "Destroys screens, unless the target is immune.",
id: "holyduck",
name: "Holy Duck!",
isNonstandard: "Custom",
pp: 5,
priority: 1,
flags: {mirror: 1, protect: 1, contact: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Extreme Speed', target);
this.add('-anim', source, 'Feather Dance', target);
},
onTryHit(pokemon) {
if (pokemon.runImmunity('Normal')) {
pokemon.side.removeSideCondition('reflect');
pokemon.side.removeSideCondition('lightscreen');
pokemon.side.removeSideCondition('auroraveil');
}
},
secondary: null,
target: "normal",
type: "Normal",
},
// E4 Flint
fangofthefireking: {
accuracy: 90,
basePower: 0,
damage: 111,
category: "Physical",
desc: "Deals 111 HP of damage and burns the target. If the target already has a status ailment, it is replaced with a burn. Fails if the target is a Fire-type or if the user is not a Fire-type.",
shortDesc: "Dmg=111HP; replace status w/burn; fail if foe=Fire.",
id: "fangofthefireking",
name: "Fang of the Fire King",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {mirror: 1, protect: 1, bite: 1},
onTryMove(pokemon, target, move) {
this.attrLastMove('[still]');
if (!pokemon.hasType('Fire') || target.hasType('Fire')) {
this.add('-fail', pokemon, 'move: Fang of the Fire King');
return null;
}
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Crunch', target);
this.add('-anim', target, 'Searing Shot', target);
},
onHit(target, source) {
target.setStatus('brn', source, null, true);
// Cringy message
if (this.random(5) === 1) this.add(`c|@E4 Flint|here's a __taste__ of my __firepower__ XD`);
},
secondary: null,
target: "normal",
type: "Fire",
},
// explodingdaisies
doom: {
basePower: 100,
accuracy: 100,
category: "Special",
desc: "Summons Sunny Day after doing damage.",
shortDesc: "Summons Sunny Day after doing damage.",
id: "doom",
name: "DOOM!",
isNonstandard: "Custom",
pp: 5,
priority: 0,
flags: {mirror: 1, protect: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Eruption', target);
this.add('-anim', source, 'Sunny Day', source);
},
onAfterMoveSecondarySelf() {
this.field.setWeather('sunnyday');
},
secondary: null,
target: "normal",
type: "Fire",
},
// Eien
ancestralpower: {
accuracy: true,
category: "Status",
desc: "The user's Attack and Special Attack are raised by one, it transforms into a different Pokemon, and it uses a move dependent on the Pokemon; Celebi (Future Sight), Jirachi (Doom Desire), Manaphy (Tail Glow), Shaymin (Seed Flare), or Victini (V-Create). Reverts to Mew and loses the initial raises of 1 stage to Attack and Special Attack at the end of the turn.",
shortDesc: " For turn: transforms, boosts, uses linked move.",
id: "ancestralpower",
name: "Ancestral Power",
isNonstandard: "Custom",
pp: 5,
priority: 0,
flags: {protect: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onHit(target, source, move) {
let baseForme = source.template.id;
/** @type {{[forme: string]: string}} */
let formes = {
celebi: 'Future Sight',
jirachi: 'Doom Desire',
manaphy: 'Tail Glow',
shaymin: 'Seed Flare',
victini: 'V-create',
};
let forme = Object.keys(formes)[this.random(5)];
source.formeChange(forme, this.getAbility('psychicsurge'), true);
this.boost({atk: 1, spa: 1}, source, source, move);
this.useMove(formes[forme], source, target);
this.boost({atk: -1, spa: -1}, source, source, move);
source.formeChange(baseForme, this.getAbility('psychicsurge'), true);
},
secondary: null,
target: "normal",
type: "Psychic",
},
// eternally
quack: {
accuracy: true,
category: "Status",
desc: "Boosts the user's Defense, Special Defense, and Speed by 1 stage.",
shortDesc: "Raises the user's Def, Sp. Def, and Spe by 1.",
id: "quack",
name: "Quack",
isNonstandard: "Custom",
pp: 5,
priority: 0,
flags: {mirror: 1, snatch: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Feather Dance', source);
this.add('-anim', source, 'Aqua Ring', source);
},
boosts: {def: 1, spd: 1, spe: 1},
secondary: null,
target: "self",
type: "Flying",
},
// EV
evoblast: {
accuracy: 100,
basePower: 80,
category: "Special",
desc: "This move's type changes to match the user's primary type. This move is a physical attack if the user's Attack stat is greater than its Special Attack stat; otherwise, it is a special attack.",
shortDesc: "Shares user's type. Physical if user's Atk > Sp. Atk.",
id: "evoblast",
name: "Evoblast",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {mirror: 1, protect: 1},
onModifyMove(move, pokemon, target) {
move.type = pokemon.types[0];
if (pokemon.getStat('atk', false, true) > pokemon.getStat('spa', false, true)) move.category = 'Physical';
},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source, move) {
this.add('-anim', source, 'Extreme Evoboost', source);
switch (move.type) {
case 'Fire':
this.add('-anim', source, 'Flamethrower', target);
break;
case 'Electric':
this.add('-anim', source, 'Thunderbolt', target);
break;
case 'Water':
this.add('-anim', source, 'Bubblebeam', target);
break;
case 'Psychic':
this.add('-anim', source, 'Psybeam', target);
break;
case 'Dark':
this.add('-anim', source, 'Dark Pulse', target);
break;
case 'Grass':
this.add('-anim', source, 'Solar Beam', target);
break;
case 'Ice':
this.add('-anim', source, 'Ice Beam', target);
break;
case 'Fairy':
this.add('-anim', source, 'Dazzling Gleam', target);
break;
}
},
onAfterMoveSecondarySelf(pokemon) {
let stat = ['atk', 'def', 'spa', 'spd', 'spe', 'accuracy'][this.random(6)];
/** @type {{[stat: string]: number}} */
let boost = {};
boost[stat] = 1;
this.boost(boost, pokemon);
},
secondary: null,
target: "normal",
type: "Normal",
},
// False
frck: {
accuracy: true,
basePower: 0,
category: "Physical",
desc: "Does not check accuracy. KOes the foe. User faints afterwards if move hits.",
shortDesc: "KOes foe. Always hits. User faints after on success.",
id: "frck",
name: "fr*ck",
isNonstandard: "Custom",
pp: 6,
noPPBoosts: true,
priority: 0,
flags: {protect: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-activate', source, 'move: Celebrate');
this.add('-anim', source, 'Searing Sunraze Smash', target);
this.add('-anim', source, 'Explosion', target);
},
onHit(target, source) {
target.faint();
source.faint();
},
secondary: null,
target: "normal",
type: "???",
},
// FOMG
rickrollout: {
accuracy: true,
basePower: 140,
category: "Physical",
desc: "Raises the user's Speed by 2 stages and has a 30% chance to confuse the target.",
shortDesc: "Raises Speed by 2; 30% chance to confuse target.",
id: "rickrollout",
name: "Rickrollout",
isNonstandard: "Custom",
pp: 1,
priority: 0,
flags: {},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Rock Polish', source);
this.add('-anim', source, 'Let\'s Snuggle Forever', target);
},
onHit() {
let messages = ["SPL players don't want you to know about this secret",
"North American player reveals the concerning secret how to make money with pokemon that will crack you up",
"10 amazing facts about Zarel you have never heard of",
"Veteran player shared his best team with a beginner - here's what happened after",
"Use these 3 simple methods to gain 200+ rating in 10 minutes"][this.random(5)];
this.add(`raw|<a href="https://www.youtube.com/watch?v=oHg5SJYRHA0"><b>${messages}</b></a>`);
},
self: {
boosts: {
spe: 2,
},
},
secondary: {
chance: 30,
volatileStatus: 'confusion',
},
isZ: "astleyiumz",
target: "normal",
type: "Rock",
},
// Forrce
purplepills: {
accuracy: true,
basePower: 0,
category: "Status",
desc: "The user gains a random typing and 3 moves based on that typing (2 special moves and 1 status move). The user's attacks deal damage based off the user's Special Defense. If used again, returns the user to its original moveset and typing. This move fails if the user is not Forrce.",
shortDesc: "Forrce: Gains 3 random moves and typing.",
id: "purplepills",
name: "Purple Pills",
isNonstandard: "Custom",
pp: 15,
priority: 0,
flags: {},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Swallow", source);
},
onTryHit(target, source) {
if (source.name !== 'Forrce') {
this.add('-fail', source);
this.hint("Only Forrce can use Purple Pills.");
return null;
}
},
volatileStatus: 'purplepills',
effect: {
noCopy: true,
onStart(pokemon) {
this.add('-start', pokemon, 'Purple Pills', '[silent]');
this.add('-message', `${pokemon.name} swallowed some pills!`);
const allTypes = ['Normal', 'Fire', 'Fighting', 'Water', 'Flying', 'Grass', 'Poison', 'Electric', 'Ground', 'Psychic', 'Rock', 'Ice', 'Bug', 'Dragon', 'Ghost', 'Dark', 'Steel', 'Fairy'];
const type1 = allTypes[this.random(18)];
const type2 = allTypes[this.random(18)];
if (type1 === type2) {
pokemon.types = [type1];
this.add('-start', pokemon, 'typechange', `${type1}`);
} else {
pokemon.types = [type1, type2];
this.add('-start', pokemon, 'typechange', `${type1}/${type2}`);
}
// track percentages to keep purple pills from resetting pp
pokemon.m.ppPercentages = pokemon.moveSlots.map(m =>
m.pp / m.maxpp
);
// Get all possible moves sorted for convience in coding
let newMovep = [];
let statMove = [], offMove1 = [], offMove2 = [];
for (const id in this.data.Movedex) {
const move = this.data.Movedex[id];
if (id !== move.id) continue;
if (move.isZ || move.isNonstandard || !move.isViable || move.id === 'batonpass') continue;
if (move.type && !pokemon.types.includes(move.type)) continue;
// Time to sort!
if (move.category === 'Status') statMove.push(move.id);
if (move.category === 'Special') {
if (type1 === type2) {
offMove1.push(move.id);
offMove2.push(move.id);
} else {
if (move.type === type1) {
offMove1.push(move.id);
} else if (move.type === type2) {
offMove2.push(move.id);
}
}
}
}
const move1 = offMove1[this.random(offMove1.length)];
offMove2 = offMove2.filter(move => move !== move1);
if (!offMove2.length) offMove2 = ['revelationdance'];
const move2 = offMove2[this.random(offMove2.length)];
newMovep.push(move1);
newMovep.push(move2);
newMovep.push(!statMove.length ? 'moonlight' : statMove[this.random(statMove.length)]);
newMovep.push('purplepills');
// Replace Moveset
pokemon.moveSlots = [];
for (const [i, moveid] of newMovep.entries()) {
const move = this.getMove(moveid);
if (!move.id) continue;
pokemon.moveSlots.push({
move: move.name,
id: move.id,
// hacky way to reduce purple pill's PP
pp: Math.floor(((move.noPPBoosts || move.isZ) ? move.pp : move.pp * 8 / 5) * (pokemon.m.ppPercentages ? pokemon.m.ppPercentages[i] : 1)),
maxpp: ((move.noPPBoosts || move.isZ) ? move.pp : move.pp * 8 / 5),
target: move.target,
disabled: false,
used: false,
virtual: true,
});
pokemon.moves.push(move.id);
}
},
onModifySpAPriority: 1,
onModifySpA(spa, pokemon) {
return pokemon.getStat('spd');
},
onRestart(pokemon) {
this.add('-message', `${pokemon.name} feels better!`);
delete pokemon.volatiles['purplepills'];
this.add('-end', pokemon, 'Purple Pills', '[silent]');
pokemon.types = ['Psychic'];
this.add('-start', pokemon, 'typechange', 'Psychic');
// track percentages to keep purple pills from resetting pp
pokemon.m.ppPercentages = pokemon.moveSlots.slice().map(m => {
return m.pp / m.maxpp;
});
// Update movepool
let newMovep = ['moonlight', 'heartswap', 'batonpass', 'purplepills'];
pokemon.moveSlots = [];
for (const [i, moveid] of newMovep.entries()) {
let move = this.getMove(moveid);
if (!move.id) continue;
pokemon.moveSlots.push({
move: move.name,
id: move.id,
// hacky way to reduce purple pill's PP
pp: Math.floor(((move.noPPBoosts || move.isZ) ? move.pp : move.pp * 8 / 5) * (pokemon.m.ppPercentages ? pokemon.m.ppPercentages[i] : 1)),
maxpp: ((move.noPPBoosts || move.isZ) ? move.pp : move.pp * 8 / 5),
target: move.target,
disabled: false,
used: false,
virtual: true,
});
pokemon.moves.push(move.id);
}
},
},
secondary: null,
target: "self",
type: "Poison",
},
// grimAuxiliatrix
paintrain: {
accuracy: 100,
basePower: 0,
basePowerCallback(pokemon, target) {
let targetWeight = target.getWeight();
let pokemonWeight = pokemon.getWeight();
if (pokemonWeight > targetWeight * 5) {
return 120;
}
if (pokemonWeight > targetWeight * 4) {
return 100;
}
if (pokemonWeight > targetWeight * 3) {
return 80;
}
if (pokemonWeight > targetWeight * 2) {
return 60;
}
return 40;
},
category: "Physical",
desc: "The power of this move depends on (user's weight / target's weight), rounded down. Power is equal to 120 if the result is 5 or more, 100 if 4, 80 if 3, 60 if 2, and 40 if 1 or less. Damage doubles and no accuracy check is done if the target has used Minimize while active. The user recovers 1/2 the HP lost by the target, rounded half up. If Big Root is held by the user, the HP recovered is 1.3x normal, rounded half down.",
shortDesc: "Stronger if user is heavier; Heals 50% of damage.",
id: "paintrain",
name: "Pain Train",
isNonstandard: "Custom",
pp: 10,
flags: {contact: 1, protect: 1, mirror: 1, heal: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Meteor Mash', target);
},
drain: [1, 2],
secondary: null,
target: "normal",
type: "Steel",
},
// Hippopotas
hazardpass: {
accuracy: 100,
category: "Status",
pp: 20,
desc: "The user sets 2 of Stealth Rock, Spikes (1 layer), Toxic Spikes (1 layer), and Sticky Web on the foe's side of the field and then switches out.",
shortDesc: "Sets 2 random hazards, then switches out.",
id: "hazardpass",
name: "Hazard Pass",
isNonstandard: "Custom",
flags: {reflectable: 1, mirror: 1, authentic: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onHitSide(target, source) {
// All possible hazards, and their maximum possible layer count
/** @type {{[key: string]: number}} */
let hazards = {stealthrock: 1, spikes: 3, toxicspikes: 2, stickyweb: 1};
// Check how many layers of each hazard can still be added to the foe's side
if (target.getSideCondition('stealthrock')) delete hazards.stealthrock;
if (target.getSideCondition('spikes')) {
hazards.spikes -= target.sideConditions['spikes'].layers;
if (!hazards.spikes) delete hazards.spikes;
}
if (target.getSideCondition('toxicspikes')) {
hazards.toxicspikes -= target.sideConditions['toxicspikes'].layers;
if (!hazards.toxicspikes) delete hazards.toxicspikes;
}
if (target.getSideCondition('stickyweb')) delete hazards.stickyweb;
// Create a list of hazards not yet at their maximum layer count
let hazardTypes = Object.keys(hazards);
// If there are no possible hazards, don't do anything
if (!hazardTypes.length) return false;
// Pick a random hazard, and set it
let hazard1 = this.sample(hazardTypes);
// Theoretically, this should always work
this.add('-anim', source, this.getMove(hazard1).name, target);
target.addSideCondition(hazard1, source, this.effect);
// If that was the last possible layer of that hazard, remove it from our list of possible hazards
if (hazards[hazard1] === 1) {
hazardTypes.splice(hazardTypes.indexOf(hazard1), 1);
// If there are no more hazards we can set, end early on a success
if (!hazardTypes.length) return true;
}
// Set the last hazard and animate the switch
let hazard2 = this.sample(hazardTypes);
this.add('-anim', source, this.getMove(hazard2).name, target);
target.addSideCondition(hazard2, source, this.effect);
this.add('-anim', source, "Baton Pass", target);
},
selfSwitch: true,
secondary: null,
target: "foeSide",
type: "Normal",
zMoveBoost: {def: 1},
},
// Hipster Sigilyph
mainstreamshock: {
accuracy: 100,
basePower: 100,
category: "Special",
desc: "This move's type effectiveness against Dark is changed to be super effective no matter what this move's type is.",
shortDesc: "Super effective on Dark.",
id: "mainstreamshock",
name: "Mainstream Shock",
isNonstandard: "Custom",
pp: 5,
priority: 0,
flags: {protect: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Psystrike", target);
},
ignoreImmunity: {'Psychic': true},
onEffectiveness(typeMod, target, type) {
if (type === 'Dark') return 1;
},
secondary: null,
target: "normal",
type: "Psychic",
},
// HoeenHero
scriptedterrain: {
accuracy: 100,
category: "Status",
desc: "Sets Scripted Terrain for 5 turns. The power of Bug type moves is boosted by 1.5, and there is a 5% chance for every move used to become Glitch Out instead. At the end of a turn, every Pokemon has a 5% chance to transform into a Missingno. with 3 random moves and Glitch Out. Switching out will restore the Pokemon to its normal state. This terrain affects floating Pokemon.",
shortDesc: "5 turns: +Bug power, glitchy effects.",
id: "scriptedterrain",
name: "Scripted Terrain",
isNonstandard: "Custom",
pp: 5,
priority: 0,
flags: {nonsky: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Calm Mind', source);
this.add('-anim', source, 'Geomancy', source);
},
terrain: 'scriptedterrain',
effect: {
duration: 5,
durationCallback(source, effect) {
if (source && source.hasItem('terrainextender')) {
return 8;
}
return 5;
},
onBasePower(basePower, attacker, defender, move) {
if (move.type === 'Bug') {
this.debug('scripted terrain boost');
return this.chainModify(1.5);
}
},
onTryHitPriority: 4,
onTryHit(target, source, effect) {
if (!effect || effect.id === 'glitchout' || source.volatiles['glitchout']) return;
if (this.random(20) === 1) {
this.add('message', `${source.name}'s move was glitched by the Scripted Terrain!`);
this.useMove('Glitch Out', source, source.side.foe.active[0]);
return null;
}
},
onStart(battle, source, effect) {
if (effect && effect.effectType === 'Ability') {
this.add('-fieldstart', 'move: Scripted Terrain', '[from] ability: ' + effect, '[of] ' + source);
} else {
this.add('-fieldstart', 'move: Scripted Terrain');
}
},
onResidualOrder: 21,
onResidualSubOrder: 2,
onResidual() {
this.eachEvent('Terrain');
},
onTerrain(pokemon) {
if (pokemon.template.id === 'missingno') return;
if (pokemon.fainted || !pokemon.hp) return;
if (this.random(20) === 1) {
this.debug('Scripted terrain corrupt');
this.add('message', `${pokemon.name} was corrupted by a bug in the scripted terrain!`);
// generate a movepool
let moves = [];
let pool = this.shuffle(Object.keys(this.data.Movedex));
let metronome = this.getMove('metronome');
for (let i of pool) {
let move = this.getMove(i);
if (i !== move.id) continue;
if (move.isZ || move.isNonstandard) continue;
if (metronome.noMetronome && metronome.noMetronome.includes(move.id)) continue;
if (this.getMove(i).gen > this.gen) continue;
moves.push(move);
if (moves.length >= 3) break;
}
moves.push('glitchout');
pokemon.formeChange('missingno');
pokemon.moveSlots = [];
for (let moveid of moves) {
let move = this.getMove(moveid);
if (!move.id) continue;
pokemon.moveSlots.push({
move: move.name,
id: move.id,
pp: 5,
maxpp: 5,
target: move.target,
disabled: false,
used: false,
virtual: true,
});
pokemon.moves.push(move.id);
}
}
},
onEnd() {
this.add('-fieldend', 'move: Scripted Terrain');
},
},
secondary: null,
target: "self",
type: "Psychic",
},
// Used by HoeenHero's terrain
glitchout: {
accuracy: true,
category: "Status",
desc: "A random move is selected for use, other than After You, Assist, Baneful Bunker, Beak Blast, Belch, Bestow, Celebrate, Chatter, Copycat, Counter, Covet, Crafty Shield, Destiny Bond, Detect, Diamond Storm, Endure, Feint, Fleur Cannon, Focus Punch, Follow Me, Freeze Shock, Helping Hand, Hold Hands, Hyperspace Hole, Ice Burn, Instruct, King's Shield, Light of Ruin, Mat Block, Me First, Metronome, Mimic, Mind Blown, Mirror Coat, Mirror Move, Nature Power, Photon Geyser, Plasma Fists, Protect, Quash, Quick Guard, Rage Powder, Relic Song, Secret Sword, Shell Trap, Sketch, Sleep Talk, Snarl, Snatch, Snore, Spectral Thief, Spiky Shield, Spotlight, Steam Eruption, Struggle, Switcheroo, Techno Blast, Thief, Thousand Arrows, Thousand Waves, Transform, Trick, Trump Card, V-create, or Wide Guard. The selected move's Base Power is increased by 20.",
shortDesc: "Uses a random move with Base Power +20.",
id: "glitchout",
name: "Glitch Out",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {},
noMetronome: ['afteryou', 'assist', 'banefulbunker', 'beakblast', 'belch', 'bestow', 'celebrate', 'chatter', 'copycat', 'counter', 'covet', 'craftyshield', 'destinybond', 'detect', 'diamondstorm', 'dragonascent', 'endure', 'feint', 'fleurcannon', 'focuspunch', 'followme', 'freezeshock', 'helpinghand', 'holdhands', 'hyperspacefury', 'hyperspacehole', 'iceburn', 'instruct', 'kingsshield', 'lightofruin', 'matblock', 'mefirst', 'metronome', 'mimic', 'mindblown', 'mirrorcoat', 'mirrormove', 'naturepower', 'originpulse', 'photongeyser', 'plasmafists', 'precipiceblades', 'protect', 'quash', 'quickguard', 'ragepowder', 'relicsong', 'secretsword', 'shelltrap', 'sketch', 'sleeptalk', 'snarl', 'snatch', 'snore', 'spectralthief', 'spikyshield', 'spotlight', 'steameruption', 'struggle', 'switcheroo', 'technoblast', 'thief', 'thousandarrows', 'thousandwaves', 'transform', 'trick', 'trumpcard', 'vcreate', 'wideguard'],
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Bug Buzz', source);
this.add('-anim', source, 'Metronome', source);
source.addVolatile('glitchout');
},
onHit(target, source, effect) {
let moves = [];
for (let i in this.data.Movedex) {
let move = this.data.Movedex[i];
if (i !== move.id) continue;
if (move.isZ || move.isNonstandard) continue;
if (effect.noMetronome && effect.noMetronome.includes(move.id)) continue;
if (this.getMove(i).gen > this.gen) continue;
moves.push(move);
}
let randomMove = '';
if (moves.length) {
moves.sort((a, b) => a.num - b.num);
randomMove = this.sample(moves).id;
}
if (!randomMove) {
return false;
}
this.useMove(randomMove, target);
},
secondary: null,
target: "self",
type: "Bug",
},
// Hubriz
flowertornado: {
accuracy: 90,
basePower: 95,
category: "Special",
desc: "Has a 20% chance to either poison the target or cause it to fall asleep.",
shortDesc: "20% chance to either poison or sleep target.",
id: "flowertornado",
name: "Flower Tornado",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {protect: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Petal Blizzard", target);
this.add('-anim', source, "Leaf Tornado", target);
},
secondary: {
chance: 20,
onHit(target, source) {
let result = this.random(2);
if (result === 0) {
target.trySetStatus('psn', source);
} else {
target.trySetStatus('slp', source);
}
},
},
target: "normal",
type: "Grass",
},
// Hurl
hurl: {
accuracy: 100,
basePower: 90,
category: "Physical",
desc: "Sets a layer of Toxic Spikes.",
shortDesc: "Sets a layer of Toxic Spikes.",
id: "hurl",
name: "Hurl",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {protect: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Gunk Shot', target);
},
onAfterMoveSecondarySelf(pokemon) {
pokemon.side.foe.addSideCondition('toxicspikes');
},
secondary: null,
target: "normal",
type: "Poison",
},
// imagi
delayedpromise: {
accuracy: 100,
basePower: 0,
category: "Status",
desc: "This move bypasses Baneful Bunker, Crafty Shield, Detect, King's Shield, Mat Block, Protect, Quick Guard, Substitute, Spiky Shield, and Wide Guard. The target's stat stages are set to 0, and the target's Speed is lowered by 1 after stats are reset. 75% chance to put the target to sleep.",
shortDesc: "Foe: Resets stats; -1 Speed; 75% chance to sleep.",
id: "delayedpromise",
name: "Delayed Promise",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {authentic: 1, snatch: 1, reflectable: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Wish', source);
this.add('-anim', source, 'Spite', target);
},
onHit(target, source) {
target.clearBoosts();
this.add('-clearboost', target);
this.boost({spe: -1}, target, source);
},
secondary: {
status: 'slp',
chance: 75,
},
target: "normal",
type: "Psychic",
},
// imas
boi: {
accuracy: 100,
basePower: 120,
category: "Physical",
desc: "The user takes recoil damage equal to 33% the HP lost by the target, rounded half up, but not less than 1 HP.",
shortDesc: "Has 33% recoil.",
id: "boi",
name: "B O I",
isNonstandard: "Custom",
pp: 15,
priority: 0,
flags: {contact: 1, protect: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Supersonic Skystrike', target);
},
recoil: [33, 100],
secondary: null,
target: "normal",
type: "Flying",
},
// Iyarito
vbora: {
accuracy: true,
category: "Status",
desc: "Cures the user's party of all status conditions, then poisons the user.",
shortDesc: "Cures party's statuses, then poisons self.",
id: "vbora",
name: "Víbora",
isNonstandard: "Custom",
pp: 5,
flags: {mirror: 1, snatch: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Acid Armor', source);
},
onHit(pokemon, source, move) {
//this.add('-activate', source, 'move: Víbora');
let success = false;
for (const ally of pokemon.side.pokemon) {
if (ally.cureStatus()) success = true;
}
if (pokemon.setStatus('psn', pokemon)) success = true;
return success;
},
secondary: null,
target: "allyTeam",
type: "Poison",
},
// jdarden
wyvernswail: {
accuracy: 100,
basePower: 60,
category: "Special",
desc: "If both the user and the target have not fainted, the target is forced to switch out and be replaced with a random unfainted ally. This effect fails if the target used Ingrain previously, has the Suction Cups Ability, or this move hit a substitute.",
shortDesc: "Forces the target to switch to a random ally.",
id: "wyvernswail",
name: "Wyvern's Wail",
isNonstandard: "Custom",
pp: 15,
priority: -6,
flags: {protect: 1, mirror: 1, sound: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Whirlwind', target);
},
forceSwitch: true,
target: "normal",
type: "Flying",
},
// Kaiju Bunny
bestialstrike: {
accuracy: 100,
basePower: 150,
basePowerCallback(pokemon, target, move) {
return move.basePower * pokemon.hp / pokemon.maxhp;
},
category: "Physical",
desc: "Power is equal to (user's current HP * 150 / user's maximum HP), rounded down, but not less than 1.",
shortDesc: "Less power as user's HP decreases.",
id: "bestialstrike",
name: "Bestial Strike",
isNonstandard: "Custom",
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Outrage', target);
},
pp: 5,
priority: 0,
flags: {protect: 1, mirror: 1, contact: 1},
secondary: null,
target: "normal",
type: "Flying",
},
// kalalokki
maelstrm: {
accuracy: 85,
basePower: 100,
category: "Special",
desc: "Prevents the target from switching for four or five turns (seven turns if the user is holding Grip Claw). Causes damage to the target equal to 1/8 of its maximum HP (1/6 if the user is holding Binding Band), rounded down, at the end of each turn during effect. Both of these effects persist for their normal duration even if the user switches out or faints. The target can still switch out if it is holding Shed Shell or uses Baton Pass, Parting Shot, U-turn, or Volt Switch. The effect ends if the target leaves the field or uses Rapid Spin or Substitute successfully. This effect is not stackable or reset by using this or another binding move.",
shortDesc: "Traps/damages for 4-5 turns, even if user returns.",
id: "maelstrm",
name: "Maelström",
isNonstandard: "Custom",
pp: 5,
priority: 0,
flags: {protect: 1, mirror: 1},
volatileStatus: 'maelstrm',
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Dark Void', target);
this.add('-anim', source, 'Surf', target);
},
effect: {
duration: 5,
durationCallback(target, source) {
if (source.hasItem('gripclaw')) {
this.debug('maelstrm grip claw duration boost');
return 8;
}
return this.random(5, 7);
},
onStart() {
this.add('-message', 'It became trapped in an enormous maelström!');
},
onResidualOrder: 11,
onResidual(pokemon) {
if (this.effectData.source.hasItem('bindingband')) {
this.debug('maelstrm binding band damage boost');
this.damage(pokemon.maxhp / 6);
} else {
this.damage(pokemon.maxhp / 8);
}
},
onEnd() {
this.add('-message', 'The maelström dissipated.');
},
onTrapPokemon(pokemon) {
pokemon.tryTrap();
},
},
secondary: null,
target: "normal",
type: "Water",
},
// Kay
inkzooka: {
accuracy: 100,
basePower: 80,
category: "Physical",
desc: "Lowers the user's Defense, Special Defense, and Speed by 1 stage.",
shortDesc: "Lowers the user's Def, Sp. Def, and Spe by 1.",
id: "inkzooka",
name: "Inkzooka",
isNonstandard: "Custom",
pp: 5,
priority: 0,
flags: {protect: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Never Ending Nightmare', target);
},
self: {
boosts: {
def: -1,
spd: -1,
spe: -1,
},
},
secondary: null,
target: "normal",
type: "Psychic",
},
// KingSwordYT
dragonwarriortouch: {
accuracy: 100,
basePower: 70,
category: "Physical",
desc: "The user recovers 1/2 the HP lost by the target, rounded half up. Raises the user's Attack by 1 stage.",
shortDesc: "User recovers 50% of the damage dealt; Atk +1.",
id: "dragonwarriortouch",
name: "Dragon Warrior Touch",
isNonstandard: "Custom",
pp: 5,
priority: 0,
flags: {protect: 1, mirror: 1, punch: 1, contact: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Outrage', target);
this.add('-anim', source, 'Drain Punch', target);
},
self: {
boosts: {
atk: 1,
},
},
drain: [1, 2],
target: "normal",
type: "Fighting",
},
// Level 51
nextlevelstrats: {
accuracy: true,
category: "Status",
desc: "The user gains 5 levels when using this move, which persist upon switching out.",
shortDesc: "User gains 5 levels.",
id: "nextlevelstrats",
name: "Next Level Strats",
isNonstandard: "Custom",
pp: 5,
priority: 0,
flags: {snatch: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Nasty Plot", target);
},
onHit(pokemon) {
const template = pokemon.template;
// @ts-ignore
pokemon.level += 5;
pokemon.set.level = pokemon.level;
pokemon.formeChange(template);
pokemon.details = template.species + (pokemon.level === 100 ? '' : ', L' + pokemon.level) + (pokemon.gender === '' ? '' : ', ' + pokemon.gender) + (pokemon.set.shiny ? ', shiny' : '');
this.add('detailschange', pokemon, pokemon.details);
const newHP = Math.floor(Math.floor(2 * template.baseStats['hp'] + pokemon.set.ivs['hp'] + Math.floor(pokemon.set.evs['hp'] / 4) + 100) * pokemon.level / 100 + 10);
pokemon.hp = newHP - (pokemon.maxhp - pokemon.hp);
pokemon.maxhp = newHP;
this.add('-heal', pokemon, pokemon.getHealth, '[silent]');
this.add('-message', `${pokemon.name} advanced 5 levels! It is now level ${pokemon.level}!`);
},
secondary: null,
target: "self",
type: "Normal",
},
// LifeisDANK
barfight: {
accuracy: 100,
basePower: 10,
category: "Physical",
desc: "Raises both the user's and the target's Attack by 3 stages, lowers the Defense of both by 3 stages, confuses both Pokemon, and has a 100% chance to cause the target to flinch.",
shortDesc: "+3 Atk, -3 Def, confusion to user & target. Priority.",
id: "barfight",
name: "Bar Fight",
isNonstandard: "Custom",
pp: 10,
priority: 3,
flags: {protect: 1, mirror: 1, contact: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Fake Out", target);
this.add('-anim', source, "Feather Dance", target);
return this.runEvent('StallMove', source);
},
onHit(target, source) {
source.addVolatile('stall');
this.boost({atk: 3, def: -3}, target);
this.boost({atk: 3, def: -3}, source);
target.addVolatile('confusion');
source.addVolatile('confusion');
target.addVolatile('flinch');
},
secondary: null,
target: "normal",
type: "Flying",
},
// Lionyx
letitgo: {
accuracy: 95,
basePower: 110,
category: "Special",
desc: "Summons hail. Has a 15% chance to lower the target's Special Defense, and a 5% chance to freeze it.",
shortDesc: "Summons hail; 15% to lower SpD, 5% to freeze.",
id: "letitgo",
name: "Let it Go",
isNonstandard: "Custom",
pp: 5,
priority: 0,
flags: {protect: 1, mirror: 1, sound: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Ice Beam", target);
this.add('-anim', source, "Subzero Slammer", target);
this.add('-anim', source, "Hyper Voice", target);
},
secondaries: [
{
chance: 5,
status: 'frz',
}, {
chance: 15,
boosts: {
spd: -1,
},
},
],
onAfterMoveSecondarySelf() {
this.field.setWeather('hail');
},
target: "normal",
type: "Ice",
},
// Lost Seso
shuffleramendance: {
accuracy: 100,
basePower: 80,
category: "Special",
desc: "This move's type effectiveness is inverted, meaning that it's super effective on Water-types but not very effective on Grass-types, and so forth. 20% chance to paralyze the target.",
shortDesc: "Type effectiveness is inverted; 20% par.",
id: "shuffleramendance",
name: "Shuffle Ramen Dance",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {protect: 1, mirror: 1, dance: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, 'Outrage', target);
},
onEffectiveness(typeMod, target) {
return -typeMod;
},
secondary: {
status: 'par',
chance: 20,
},
target: "normal",
type: "Fire",
zMovePower: 160,
},
// MacChaeger
naptime: {
accuracy: true,
category: "Status",
desc: "The user falls asleep for the next turn, restoring 50% of its HP and curing itself of any major status condition. If the user falls asleep in this way, all other active Pokemon that are not asleep or frozen also try to use Nap Time. Fails if the user has full HP, if the user is already asleep, or if another effect is preventing sleep.",
shortDesc: "Active Pokemon sleep 1 turn, restoring HP/status.",
id: "naptime",
name: "Nap Time",
isNonstandard: "Custom",
pp: 5,
priority: 0,
flags: {snatch: 1, heal: 1},
onTryMove(pokemon) {
this.attrLastMove('[still]');
if (pokemon.hp < pokemon.maxhp && pokemon.status !== 'slp' && !pokemon.hasAbility('comatose')) return;
this.add('-fail', pokemon);
this.hint("Nap Time fails if the user has full health, is already asleep, or has Comatose.");
return null;
},
onPrepareHit(target, source) {
this.add('-anim', source, "Rest", target);
this.add('-anim', source, "Aromatic Mist", target);
},
onHit(target, source, move) {
let napWeather = this.field.pseudoWeather['naptime'];
// Trigger sleep clause if not the original user
if (!target.setStatus('slp', napWeather.source, move)) return false;
target.statusData.time = 2;
target.statusData.startTime = 2;
this.heal(target.maxhp / 2); // Aesthetic only as the healing happens after you fall asleep in-game
this.add('-status', target, 'slp', '[from] move: Rest');
if (napWeather.source === target) {
for (const curMon of this.getAllActive()) {
if (curMon === source) continue;
if (curMon.status !== 'slp' && curMon.status !== 'frz' && !curMon.hasAbility('comatose')) {
this.add('-anim', source, "Yawn", curMon);
this.useMove(move, curMon, curMon, move);
}
}
}
this.field.removePseudoWeather('naptime');
},
pseudoWeather: 'naptime',
effect: {
duration: 1,
},
target: "self",
type: "Fairy",
zMoveEffect: 'clearnegativeboosts',
},
// MajorBowman
blazeofglory: {
accuracy: true,
basePower: 0,
damageCallback(pokemon, target) {
let damage = pokemon.hp;
pokemon.faint();
if (target.volatiles['banefulbunker'] || target.volatiles['kingsshield'] || target.side.sideConditions['matblock'] || target.volatiles['protect'] || target.volatiles['spikyshield'] || target.volatiles['lilypadshield']) {
this.add('-zbroken', target);
return Math.floor(damage / 4);
}
return damage;
},
category: "Physical",
desc: "The user's HP is restored to maximum, and the user then faints. The target then takes damage equal to the amount of HP the user lost. This move does not check accuracy.",
shortDesc: "Does damage equal to user's max. HP. User faints.",
id: "blazeofglory",
name: "Blaze of Glory",
isNonstandard: "Custom",
pp: 1,
priority: 0,
flags: {},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Recover", source);
this.heal(source.maxhp, source, source, this.getActiveMove('Blaze of Glory'));
this.add('-anim', source, "Final Gambit", target);
},
selfdestruct: "ifHit",
isZ: "victiniumz",
secondary: null,
target: "normal",
type: "Fire",
},
// martha
crystalboost: {
accuracy: 90,
basePower: 75,
category: "Special",
desc: "Has a 50% chance to raise the user's Special Attack by 1 stage.",
shortDesc: "50% chance to raise the user's Sp. Atk. by 1.",
id: "crystalboost",
name: "Crystal Boost",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {protect: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Power Gem", target);
},
secondary: {
chance: 50,
self: {
boosts: {
spa: 1,
},
},
},
target: "normal",
type: "Rock",
},
// Marty
typeanalysis: {
accuracy: true,
category: "Status",
desc: "If the user is a Silvally, its item becomes a random Memory whose type matches one of the target's weaknesses, it changes forme, and it uses Multi-Attack. This move and its effects ignore the Abilities of other Pokemon. Fails if the target has no weaknesses or if the user's species is not Silvally.",
shortDesc: "Changes user/move type to a weakness of target.",
id: "typeanalysis",
name: "Type Analysis",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {authentic: 1, protect: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Conversion", source);
},
onHit(target, source) {
if (source.baseTemplate.baseSpecies !== 'Silvally') return false;
let targetTypes = target.getTypes(true).filter(type => type !== '???');
if (!targetTypes.length) {
if (target.addedType) {
targetTypes = ['Normal'];
} else {
return false;
}
}
let weaknesses = [];
for (let type in this.data.TypeChart) {
let typeMod = this.getEffectiveness(type, targetTypes);
if (typeMod > 0 && this.getImmunity(type, target)) weaknesses.push(type);
}
if (!weaknesses.length) {
return false;
}
let randomType = this.sample(weaknesses);
source.setItem(randomType + 'memory');
this.add('-item', source, source.getItem(), '[from] move: Type Analysis');
let template = this.getTemplate('Silvally-' + randomType);
source.formeChange(template, this.getAbility('rkssystem'), true);
let move = this.getActiveMove('multiattack');
move.basePower = 80;
this.useMove(move, source, target);
},
secondary: null,
target: "normal",
type: "Normal",
zMoveEffect: 'heal',
},
// Meicoo
scavengesu: {
accuracy: true,
basePower: 0,
category: "Status",
desc: "Lowers the user's Attack and Special Attack by two stages, and then swaps all of its stat changes with the target.",
shortDesc: "Harshly lowers own Atk/SpA; swaps stats with opp.",
id: "scavengesu",
name: "/scavenges u",
isNonstandard: "Custom",
pp: 5,
priority: 0,
flags: {mirror: 1, protect: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Imprison", source);
this.add('-anim', source, "Miracle Eye", target);
},
onHit(target, source) {
this.boost({atk: -2, spa: -2}, source, source, this.getActiveMove('/scavenges u'));
let targetBoosts = {};
let sourceBoosts = {};
for (let i in target.boosts) {
// @ts-ignore
targetBoosts[i] = target.boosts[i];
// @ts-ignore
sourceBoosts[i] = source.boosts[i];
}
target.setBoost(sourceBoosts);
source.setBoost(targetBoosts);
this.add(`c|%Meicoo|cool quiz`);
this.add('-swapboost', source, target, '[from] move: /scavenges u');
},
secondary: null,
target: "normal",
type: "Psychic",
},
// Megazard
tippingover: {
accuracy: 100,
basePower: 20,
basePowerCallback(pokemon, target, move) {
return move.basePower + 20 * pokemon.positiveBoosts();
},
category: "Physical",
desc: "Power rises by 20 for each of the user's positive stat stage changes. The user loses any defensive boosts not from Stockpile.",
shortDesc: "+20 power per boost. Removes non-Stockpile boosts.",
id: "tippingover",
name: "Tipping Over",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {protect: 1, mirror: 1, contact: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Dragon Hammer", target);
this.add('-anim', target, "Earthquake", target);
},
onHit(target, source, move) {
let stockpileLayers = 0;
if (source.volatiles['stockpile']) stockpileLayers = source.volatiles['stockpile'].layers;
let boosts = {};
if (source.boosts.def > stockpileLayers) boosts.def = stockpileLayers - source.boosts.def;
if (source.boosts.spd > stockpileLayers) boosts.spd = stockpileLayers - source.boosts.spd;
if (boosts.def || boosts.spd) this.boost(boosts, source, source, move);
},
secondary: null,
target: "normal",
type: "???",
},
// MicktheSpud
cyclonespin: {
accuracy: 100,
basePower: 90,
category: "Physical",
desc: "If this move is successful and the user has not fainted, the effects of Leech Seed and binding moves end for the user, and all hazards are removed from the user's side of the field.",
shortDesc: "Frees user from hazards/partial trap/Leech Seed.",
id: "cyclonespin",
name: "Cyclone Spin",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {mirror: 1, protect: 1, contact: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Rapid Spin", target);
},
self: {
onHit(pokemon) {
if (pokemon.hp && pokemon.removeVolatile('leechseed')) {
this.add('-end', pokemon, 'Leech Seed', '[from] move: Cyclone Spin', '[of] ' + pokemon);
}
let sideConditions = ['spikes', 'toxicspikes', 'stealthrock', 'stickyweb'];
for (const condition of sideConditions) {
if (pokemon.hp && pokemon.side.removeSideCondition(condition)) {
this.add('-sideend', pokemon.side, this.getEffect(condition).name, '[from] move: Cyclone Spin', '[of] ' + pokemon);
}
}
if (pokemon.hp && pokemon.volatiles['partiallytrapped']) {
pokemon.removeVolatile('partiallytrapped');
}
},
},
secondary: null,
target: "normal",
type: "Fighting",
},
// Mitsuki
pythonivy: {
accuracy: 95,
basePower: 110,
category: "Special",
desc: "Lowers the user's Special Attack, Special Defense, and Speed by 1 stage.",
shortDesc: "Lowers the user's Sp. Atk, Sp. Def. and Spe by 1.",
id: "pythonivy",
name: "Python Ivy",
isNonstandard: "Custom",
pp: 5,
priority: 0,
flags: {protect: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Leaf Tornado", target);
this.add('-anim', source, "Leaf Storm", target);
},
self: {
boosts: {
spa: -1,
spd: -1,
spe: -1,
},
},
secondary: null,
target: "normal",
type: "Grass",
},
// moo
proteinshake: {
accuracy: true,
category: "Status",
desc: "The user's Attack, Defense, and Speed are boosted by 1 stage. The user also gains 100kg of weight.",
shortDesc: "+1 Atk, Def, and Spe. User gains 100kg.",
id: "proteinshake",
name: "Protein Shake",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {snatch: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Milk Drink", source);
},
volatileStatus: 'proteinshake',
effect: {
onStart(pokemon) {
this.effectData.multiplier = 1;
this.add('-start', pokemon, 'Protein Shake', '[silent]');
},
onRestart(pokemon) {
this.effectData.multiplier++;
this.add('-start', pokemon, 'Protein Shake', '[silent]');
},
onModifyWeightPriority: 1,
onModifyWeight(weight, pokemon) {
if (this.effectData.multiplier) {
weight += this.effectData.multiplier * 100;
return weight;
}
},
},
boosts: {atk: 1, def: 1, spe: 1},
secondary: null,
target: "self",
type: "Normal",
},
// Morfent
e: {
accuracy: true,
category: "Status",
desc: "Sets Trick Room for 5 turns and raises the user's Attack by 1 stage.",
shortDesc: "User Attack +1; sets Trick Room.",
id: "e",
name: "E",
isNonstandard: "Custom",
pp: 5,
priority: -6,
onModifyMove(move) {
if (!this.field.pseudoWeather.trickroom) {
move.pseudoWeather = 'trickroom';
}
},
flags: {snatch: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Recover", source);
this.add('-anim', source, "Nasty Plot", source);
},
boosts: {
atk: 1,
},
secondary: null,
target: "self",
type: "Ghost",
},
// Used for nui's ability
prismaticterrain: {
accuracy: true,
category: "Status",
desc: "For 5 turns, the terrain becomes Prismatic Terrain. During the effect, the power of Ice-type attacks is multiplied by 0.5, even if the user is not grounded. Hazards are removed and cannot be set while Prismatic Terrain is active. Fails if the current terrain is Prismatic Terrain.",
shortDesc: "5 turns. No hazards,-Ice power even if floating.",
id: "prismaticterrain",
name: "Prismatic Terrain",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {},
terrain: 'prismaticterrain',
effect: {
duration: 5,
durationCallback(source, effect) {
if (source && source.hasItem('terrainextender')) {
return 8;
}
return 5;
},
onTryMove(target, source, move) {
let hazardMoves = ['reflect', 'lightscreen', 'auroraveil', 'safeguard', 'mist', 'spikes', 'toxicspikes', 'stealthrock', 'stickyweb', 'hazardpass', 'beskyttelsesnet', 'bringerofdarkness', 'soulbend', 'smokebomb', 'hurl'];
if (hazardMoves.includes(move.id)) {
this.add('-message', `Prismatic Terrain prevented ${move.name} from completing!`);
return false;
}
},
onBasePower(basePower, attacker, defender, move) {
if (move.type === 'Ice') {
this.debug('prismatic terrain weaken');
return this.chainModify(0.5);
}
},
onStart(battle, source, effect) {
if (effect && effect.effectType === 'Ability') {
this.add('-fieldstart', 'move: Prismatic Terrain', '[from] ability: ' + effect, '[of] ' + source);
} else {
this.add('-fieldstart', 'move: Prismatic Terrain');
}
let removeAll = ['reflect', 'lightscreen', 'auroraveil', 'safeguard', 'mist', 'spikes', 'toxicspikes', 'stealthrock', 'stickyweb'];
let silentRemove = ['reflect', 'lightscreen', 'auroraveil', 'safeguard', 'mist'];
for (const sideCondition of removeAll) {
if (source.side.foe.removeSideCondition(sideCondition)) {
if (!(silentRemove.includes(sideCondition))) this.add('-sideend', source.side.foe, this.getEffect(sideCondition).name, '[from] move: Prismatic Terrain', '[of] ' + source);
}
if (source.side.removeSideCondition(sideCondition)) {
if (!(silentRemove.includes(sideCondition))) this.add('-sideend', source.side, this.getEffect(sideCondition).name, '[from] move: Prismatic Terrain', '[of] ' + source);
}
}
},
onResidualOrder: 21,
onResidualSubOrder: 2,
onEnd() {
this.add('-fieldend', 'move: Prismatic Terrain');
},
},
secondary: null,
target: "self",
type: "Fairy",
},
// nui
pyramidingsong: {
accuracy: 100,
category: "Status",
desc: "If the target has not fainted, both the user and the target are forced to switch out and be replaced with a chosen unfainted ally. The target's replacement has its Speed lowered by 1 stage. Fails if either Pokemon is under the effect of Ingrain or Suction Cups.",
shortDesc: "Both Pokemon switch. Opp. replacement: Spe -1.",
id: "pyramidingsong",
name: "Pyramiding Song",
isNonstandard: "Custom",
pp: 20,
priority: -6,
flags: {mirror: 1, protect: 1, authentic: 1, sound: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Freeze Dry", target);
this.add('-anim', source, "Mist", target);
},
onTryHit(target, source, move) {
target.side.addSlotCondition(target, 'pyramidingsong');
},
onHit(target, source, move) {
if (this.runEvent('DragOut', source, target, move)) {
source.forceSwitchFlag = true;
}
},
effect: {
duration: 1,
onSwitchIn(pokemon) {
this.boost({spe: -1}, pokemon, pokemon.side.foe.active[0], this.getActiveMove('pyramidingsong'));
},
},
forceSwitch: true,
secondary: null,
target: "normal",
type: "Water",
zMoveEffect: "boostreplacement",
},
// OM
omboom: {
accuracy: 95,
basePower: 110,
category: "Physical",
desc: "Has a 50% chance to raise the user's Speed by 2 stages.",
shortDesc: "Has 50% chance to raise the user's Speed by 2.",
id: "omboom",
name: "OM Boom",
isNonstandard: "Custom",
pp: 15,
priority: 0,
flags: {mirror: 1, protect: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Fire Lash", target);
this.add('-anim', source, "Heat Crash", target);
},
onHit() {
this.add(`c|@OM|Bang Bang`);
},
secondary: {
chance: 50,
self: {
boosts: {
spe: 2,
},
},
},
target: "normal",
type: "Fire",
},
// Osiris
nightmarch: {
basePower: 60,
basePowerCallback(pokemon, target, move) {
let faintedmons = 0;
for (const ally of pokemon.side.pokemon) {
if (ally.fainted || !ally.hp) faintedmons += 20;
}
for (const foes of target.side.pokemon) {
if (foes.fainted || !foes.hp) faintedmons += 20;
}
return move.basePower + faintedmons;
},
accuracy: 100,
category: "Physical",
desc: "Power is equal to 60+(20*X), where X is the total number of fainted Pokemon on both the user's team and on the opponent's team.",
shortDesc: "+20 power for each fainted ally or foe.",
id: "nightmarch",
name: "Night March",
isNonstandard: "Custom",
pp: 5,
flags: {protect: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Nightmare", target);
this.add('-anim', source, "Moongeist Beam", target);
this.add('-anim', source, "Stomping Tantrum", target);
},
secondary: null,
target: "normal",
type: "Ghost",
},
// Overneat
totalleech: {
accuracy: 100,
basePower: 70,
category: "Special",
desc: "The user recovers 1/2 the HP lost by the target, rounded half up. If Big Root is held by the user, the HP recovered is 1.3x normal, rounded half down.",
shortDesc: "User recovers 50% of the damage dealt.",
id: "totalleech",
name: "Total Leech",
isNonstandard: "Custom",
pp: 5,
priority: 0,
flags: {contact: 1, protect: 1, mirror: 1, heal: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Leech Life", target);
},
drain: [1, 2],
secondary: null,
target: "normal",
type: "Fairy",
},
// Pablo
jailshell: {
accuracy: 90,
basePower: 90,
category: "Special",
desc: "This move has a 50% change to paralyze the target and prevents the target from switching out or using any moves that the user also knows while the user is active.",
shortDesc: "50% chance to paralyze. Traps and imprisons.",
id: "jailshell",
name: "Jail Shell",
isNonstandard: "Custom",
pp: 5,
priority: 0,
flags: {protect: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Anchor Shot", target);
},
onHit(target, source, move) {
if (source.isActive) target.addVolatile('trapped', source, move, 'trapper');
source.addVolatile('imprison', source, move);
},
secondary: {
chance: 50,
status: 'par',
},
target: "normal",
type: "Normal",
},
// Paradise
corrosivetoxic: {
accuracy: true,
category: "Status",
desc: "Badly poisons the target, even if they are Poison-type or Steel-type. This move does not check accuracy.",
shortDesc: "Badly poisons the target, regardless of type.",
id: "corrosivetoxic",
name: "Corrosive Toxic",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {protect: 1, reflectable: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Toxic", target);
},
onTryHit(target, source, move) {
// hacky way of forcing toxic to effect poison / steel types without corrosion usage
if (target.volatiles['substitute'] && !move.infiltrates) return;
if (target.hasType('Steel') || target.hasType('Poison')) {
if (target.status) return;
let status = this.getEffect(move.status);
target.status = status.id;
target.statusData = {id: status.id, target: target, source: source, stage: 0};
this.add('-status', target, target.status);
move.status = undefined;
}
},
status: 'tox',
secondary: null,
target: "normal",
type: "Poison",
},
// pluviometer
grammarhammer: {
accuracy: 100,
basePower: 90,
category: "Special",
desc: "100% chance to burn the target.",
shortDesc: "100% chance to burn the target.",
id: "grammarhammer",
name: "Grammar Hammer",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {contact: 1, protect: 1, mirror: 1, punch: 1},
onPrepareHit(target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Hammer Arm", target);
},
onHit(target, source) {
if (target.name === 'HoeenHero') {
this.add(`c|@pluviometer|HoennHero*`);
this.add(`c|&HoeenHero|I can speel`);
}
},
secondary: {
chance: 100,
status: 'brn',
},
target: "normal",
type: "Ghost",
},
// ptoad
lilypadshield: {
accuracy: true,
basePower: 0,
category: "Status",
desc: "The user is protected from most moves made by other Pokemon during this turn, and if a Pokemon makes contact with the user, the user restores 1/4 of its maximum HP, rounded half up. This move has a 1/X chance of being successful, where X starts at 1 and doubles each time this move is successfully used. X resets to 1 if this move fails, if the user's last move used is not Baneful Bunker, Detect, Endure, King's Shield, Protect, Quick Guard, Spiky Shield, Wide Guard, or this move, or if it was one of those moves and the user's protection was broken. Fails if the user moves last this turn.",
shortDesc: "Protects from moves. Contact: restores 25% HP.",
id: "lilypadshield",
name: "Lilypad Shield",
isNonstandard: "Custom",
pp: 10,
priority: 4,
flags: {heal: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Spiky Shield", source);
},
stallingMove: true,
volatileStatus: 'lilypadshield',
onTryHit(target, source, move) {
return !!this.willAct() && this.runEvent('StallMove', target);
},
onHit(pokemon) {
pokemon.addVolatile('stall');
},
effect: {
duration: 1,
onStart(target) {
this.add('-singleturn', target, 'move: Protect');
},
onTryHitPriority: 3,
onTryHit(target, source, move) {
if (!move.flags['protect']) {
if (move.isZ) move.zBreakProtect(target);
return;
}
this.add('-activate', target, 'move: Protect');
let lockedmove = source.getVolatile('lockedmove');
if (lockedmove) {
// Outrage counter is reset
if (source.volatiles['lockedmove'].duration === 2) {
delete source.volatiles['lockedmove'];
}
}
if (move.flags['contact']) {
this.heal(target.maxhp / 4, target, target);
}
return null;
},
onHit(target, source, move) {
if (move.isZPowered && move.flags['contact']) {
this.heal(target.maxhp / 4, target, target);
}
},
},
secondary: null,
target: "self",
type: "Grass",
},
// Psynergy
resolve: {
accuracy: true,
basePower: 0,
category: "Status",
desc: "Raises the user's Speed by 1 stage. Gives Focus Energy",
shortDesc: "Raises user's Speed by 1; Focus Energy.",
id: "resolve",
name: "Resolve",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {snatch: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Acupressure", source);
this.add('-anim', source, "Flare Blitz", source);
},
onHit(target, source) {
source.addVolatile('focusenergy', source);
},
boosts: {
spe: 1,
},
target: "self",
type: "Fighting",
},
// Quite Quiet
literallycheating: {
accuracy: true,
category: "Status",
desc: "For seven turns, any Pokemon that has one of their stats boosted through any manner loses all PP on the last move they used.",
shortDesc: "7 turns: boosting stat: lose all PP from last move.",
id: "literallycheating",
name: "Literally Cheating",
isNonstandard: "Custom",
pp: 5,
priority: 0,
flags: {},
onPrepareHit(target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Genesis Supernova", source);
},
pseudoWeather: 'literallycheating',
effect: {
duration: 7,
onBoost(boost, target, source, effect) {
let positiveBoost = false;
let values = Object.values(boost);
for (let i of values) {
if (i !== undefined && i > 0) {
positiveBoost = true;
break;
}
}
if (!positiveBoost || !target.lastMove) return;
for (const moveSlot of target.moveSlots) {
if (moveSlot.id === target.lastMove.id) {
target.deductPP(moveSlot.id, moveSlot.pp);
}
}
this.add('-activate', target, 'move: Literally Cheating', target.lastMove.name, target.lastMove.pp);
this.add('-message', `${target.name} lost all PP for the move ${target.lastMove.name}!`);
},
onStart(battle, source, effect) {
this.add('-fieldstart', 'move: Literally Cheating');
},
onResidualOrder: 21,
onResidualSubOrder: 2,
onEnd() {
this.add('-fieldend', 'move: Literally Cheating');
},
},
secondary: null,
target: "all",
type: "Ghost",
},
// Rory Mercury
switchoff: {
accuracy: 100,
basePower: 60,
category: "Physical",
desc: "Before doing damage, the target's stat boosts are inverted. Ignores Ground-type immunity. The user switches out after damaging the target.",
shortDesc: "Hits Ground. Inverts target's boosts, then switches.",
id: "switchoff",
name: "Switch Off",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {mirror: 1, protect: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Topsy-Turvy", target);
this.add('-anim', source, "Zing Zap", target);
},
onTryHit(target, source, move) {
let success = false;
for (let i in target.boosts) {
// @ts-ignore
if (target.boosts[i] === 0) continue;
// @ts-ignore
target.boosts[i] = -target.boosts[i];
success = true;
}
if (!success) return;
this.add('-invertboost', target, '[from] move: Switch Off');
},
ignoreImmunity: {'Electric': true},
selfSwitch: true,
secondary: null,
target: "normal",
type: "Electric",
},
// Saburo
soulbend: {
accuracy: true,
basePower: 0,
category: "Status",
desc: "Raises the user's Attack and Speed by 1 stage. Has a 10% chance to summon either Reflect or Light Screen.",
shortDesc: "Atk, Spe +1; 10% chance to set one screen.",
id: "soulbend",
name: "Soulbend",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {snatch: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Refresh", source);
this.add('-anim', source, "Geomancy", source);
},
boosts: {
atk: 1,
spe: 1,
},
secondary: {
chance: 10,
onHit(target, source) {
let result = this.random(2);
if (result === 0) {
source.side.addSideCondition('reflect', source);
} else {
source.side.addSideCondition('lightscreen', source);
}
},
},
target: "self",
type: "Psychic",
},
// SamJo
thicc: {
accuracy: true,
basePower: 0,
category: "Status",
desc: "Raises the user's Attack and accuracy by 1 stage.",
shortDesc: "Raises the user's Attack and accuracy by 1.",
id: "thicc",
name: "Thicc",
isNonstandard: "Custom",
pp: 15,
priority: 0,
flags: {snatch: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Hone Claws", source);
},
boosts: {
atk: 1,
accuracy: 1,
},
secondary: null,
target: "self",
type: "Ice",
},
// SamJo Z-Move
extrathicc: {
accuracy: true,
basePower: 0,
category: "Status",
desc: "Raises the user's Attack and accuracy by 1 stage. Summons Hail and Aurora Veil.",
shortDesc: "User's atk and acc +1. Sets Hail and Aurora Veil.",
id: "extrathicc",
name: "Extra T h i c c",
isNonstandard: "Custom",
pp: 1,
priority: 0,
flags: {},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Hone Claws", source);
this.add('-anim', source, "Extreme Evoboost", source);
this.add('-anim', source, "Blizzard", source);
},
onHit(target, source) {
this.field.setWeather('hail');
if (this.field.isWeather('hail')) source.side.addSideCondition('auroraveil', source);
this.add('-message', source.name + ' became extra thicc!');
},
boosts: {
atk: 1,
accuracy: 1,
},
isZ: "thicciniumz",
secondary: null,
target: "self",
type: "Ice",
},
// Scotteh
geomagneticstorm: {
accuracy: 100,
basePower: 140,
category: "Special",
desc: "No additional effect.",
shortDesc: "No additional effect.",
id: "geomagneticstorm",
name: "Geomagnetic Storm",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {protect: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Discharge", target);
},
secondary: null,
target: "allAdjacent",
type: "Electric",
},
// Shiba
goinda: {
accuracy: true,
basePower: 0,
category: "Status",
desc: "Raises the user's Attack by 2 stages and Speed by 1 stage.",
shortDesc: "Raises the user's Attack by 2 and Speed by 1.",
id: "goinda",
name: "GO INDA",
isNonstandard: "Custom",
pp: 5,
priority: 0,
flags: {snatch: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Swords Dance", source);
this.add('-anim', source, "Sacred Fire", source);
},
boosts: {
atk: 2,
spe: 1,
},
target: "self",
type: "Flying",
},
// Slowbroth
alienwave: {
accuracy: true,
basePower: 0,
category: "Status",
desc: "For 5 turns, slower Pokemon move first. Psychic-type attacks can hit if the target is a Dark-type.",
shortDesc: "Creates Trick Room; 5 turns: Psychic hits Dark.",
id: "alienwave",
name: "Alien Wave",
isNonstandard: "Custom",
pp: 10,
priority: -7,
flags: {},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Telekinesis", source);
this.add('-anim', source, "Trick Room", source);
},
pseudoWeather: 'alienwave',
effect: {
duration: 5,
onStart(target, source) {
this.add('-fieldstart', 'move: Alien Wave');
this.add('-message', `Psychic-type attacks can hit Dark-type Pokemon!`);
},
onNegateImmunity(pokemon, type) {
if (pokemon.hasType('Dark') && type === 'Psychic') return false;
},
// Speed modification is changed in Pokemon.getActionSpeed() in mods/seasonal/scripts.js
onResidualOrder: 23,
onEnd() {
this.add('-fieldend', 'move: Alien Wave');
this.add('-message', `Psychic-type attacks can no longer hit Dark-type Pokemon.`);
},
},
secondary: null,
target: "all",
type: "Normal",
},
// Snaquaza
fakeclaim: {
accuracy: true,
category: "Physical",
basePower: 1,
desc: "The user creates a substitute to take its place in battle. This substitute is a Pokemon selected from a broad set of Random Battle-eligible Pokemon able to learn the move chosen as this move's base move. Upon the substitutes creation, this Pokemon's ability is suppressed until it switches out. The substitute Pokemon is generated with a Random Battle moveset with maximum PP that is added (except for duplicates) to the user's moveset; these additions are removed when this substitute is no longer active. The substitute uses its species's base stats, types, ability, and weight but retains the user's max HP, stat stages, gender, level, status conditions, trapping, binding, and pseudo-statuses such as confusion. Its HP is 100% of the user's maximum HP. When this substitute falls to zero HP, it breaks, and the user reverts to the state in which it used this move. This substitute absorbs indirect damage and authentic moves but does not reset the counter of bad poison when broken and cannot be transfered through Baton Pass. Transforming into this substitute will not fail. If the user switches out while the substitute is up, the substitute will be removed and the user will revert to the state in which it used this move. This move's properties are based on the move Fake Claim is inheriting from.",
shortDesc: "Uses a Random Battle Pokemon as a Substitute.",
id: "fakeclaim",
name: "Fake Claim",
isNonstandard: "Custom",
pp: 1,
priority: 0,
flags: {},
onModifyMove(move) {
// @ts-ignore Hack for Snaquaza's Z move
move.type = move.baseMove ? move.baseMove.type : move.type;
// @ts-ignore Hack for Snaquaza's Z move
move.basePower = move.baseMove ? move.baseMove.basePower : move.basePower;
// @ts-ignore Hack for Snaquaza's Z move
move.category = move.baseMove ? move.baseMove.category : move.category;
// @ts-ignore Hack for Snaquaza's Z move
this.claimMove = move.baseMove;
},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source, move) {
let zmove = this.getMove(this.zMoveTable[move.type]);
this.add('-anim', source, zmove.name, target);
this.add('-anim', source, "Transform", source);
},
onAfterMoveSecondarySelf(pokemon, move) {
/** @type {{[move: string]: string[]}} */
let claims = {
bravebird: ['Braviary', 'Crobat', 'Decidueye', 'Dodrio', 'Farfetch\'d', 'Golbat', 'Mandibuzz', 'Pidgeot', 'Skarmory', 'Staraptor', 'Swanna', 'Swellow', 'Talonflame', 'Tapu Koko', 'Toucannon'],
superpower: ['Absol', 'Aggron', 'Armaldo', 'Avalugg', 'Azumarill', 'Barbaracle', 'Basculin', 'Beartic', 'Bewear', 'Bibarel', 'Bouffalant', 'Braviary', 'Breloom', 'Buzzwole', 'Cacturne', 'Carracosta', 'Celesteela', 'Chesnaught', 'Cobalion', 'Conkeldurr', 'Crabominable', 'Crawdaunt', 'Darmanitan', 'Diggersby', 'Donphan', 'Dragonite', 'Drampa', 'Druddigon', 'Durant', 'Eelektross', 'Emboar', 'Exeggutor-Alola', 'Feraligatr', 'Flareon', 'Flygon', 'Gigalith', 'Gogoat', 'Golem', 'Golurk', 'Goodra', 'Granbull', 'Gurdurr', 'Hariyama', 'Hawlucha', 'Haxorus', 'Heatmor', 'Hippowdon', 'Hitmonlee', 'Hydreigon', 'Incineroar', 'Kabutops', 'Keldeo', 'Kingler', 'Komala', 'Kommo-o', 'Krookodile', 'Landorus-Therian', 'Lurantis', 'Luxray', 'Machamp', 'Malamar', 'Mamoswine', 'Mew', 'Mudsdale', 'Nidoking', 'Nidoqueen', 'Pangoro', 'Passimian', 'Piloswine', 'Pinsir', 'Rampardos', 'Regice', 'Regigigas', 'Regirock', 'Registeel', 'Reuniclus', 'Rhydon', 'Rhyperior', 'Samurott', 'Sawk', 'Scizor', 'Scolipede', 'Simipour', 'Simisage', 'Simisear', 'Smeargle', 'Snorlax', 'Spinda', 'Stakataka', 'Stoutland', 'Swampert', 'Tapu Bulu', 'Terrakion', 'Throh', 'Thundurus', 'Torkoal', 'Tornadus', 'Torterra', 'Tyranitar', 'Tyrantrum', 'Ursaring', 'Virizion', 'Zeraora'],
suckerpunch: ['Absol', 'Arbok', 'Ariados', 'Banette', 'Bisharp', 'Cacturne', 'Celebi', 'Corsola', 'Decidueye', 'Delcatty', 'Drifblim', 'Druddigon', 'Dugtrio', 'Dusknoir', 'Electrode', 'Emboar', 'Froslass', 'Furfrou', 'Furret', 'Galvantula', 'Gengar', 'Girafarig', 'Golem', 'Golisopod', 'Heatmor', 'Hitmonlee', 'Hitmontop', 'Houndoom', 'Huntail', 'Kangaskhan', 'Kecleon', 'Komala', 'Lanturn', 'Latias', 'Liepard', 'Lycanroc', 'Maractus', 'Mawile', 'Meowstic', 'Mew', 'Mightyena', 'Mismagius', 'Nidoking', 'Nidoqueen', 'Purugly', 'Raticate', 'Rotom', 'Sableye', 'Seviper', 'Shiftry', 'Skuntank', 'Slaking', 'Smeargle', 'Spinda', 'Spiritomb', 'Stantler', 'Sudowoodo', 'Toxicroak', 'Umbreon', 'Victreebel', 'Wormadam', 'Xatu'],
flamethrower: ['Absol', 'Aerodactyl', 'Aggron', 'Altaria', 'Arcanine', 'Audino', 'Azelf', 'Bastiodon', 'Blacephalon', 'Blissey', 'Camerupt', 'Castform', 'Celesteela', 'Chandelure', 'Chansey', 'Charizard', 'Clefable', 'Clefairy', 'Darmanitan', 'Delphox', 'Dragonite', 'Drampa', 'Druddigon', 'Dunsparce', 'Eelektross', 'Electivire', 'Emboar', 'Entei', 'Exeggutor-Alola', 'Exploud', 'Flareon', 'Flygon', 'Furret', 'Garchomp', 'Golem', 'Goodra', 'Gourgeist', 'Granbull', 'Guzzlord', 'Gyarados', 'Heatmor', 'Heatran', 'Houndoom', 'Hydreigon', 'Incineroar', 'Infernape', 'Kangaskhan', 'Kecleon', 'Kommo-o', 'Lickilicky', 'Machamp', 'Magcargo', 'Magmortar', 'Malamar', 'Manectric', 'Marowak', 'Mawile', 'Mew', 'Moltres', 'Muk', 'Nidoking', 'Nidoqueen', 'Ninetales', 'Noivern', 'Octillery', 'Pyroar', 'Rampardos', 'Rapidash', 'Rhydon', 'Rhyperior', 'Salamence', 'Salazzle', 'Seviper', 'Silvally', 'Simisear', 'Skuntank', 'Slaking', 'Slowbro', 'Slowking', 'Slurpuff', 'Smeargle', 'Snorlax', 'Solrock', 'Talonflame', 'Tauros', 'Togekiss', 'Torkoal', 'Turtonator', 'Typhlosion', 'Tyranitar', 'Watchog', 'Weezing', 'Wigglytuff', 'Zangoose'],
thunderbolt: ['Absol', 'Aggron', 'Ambipom', 'Ampharos', 'Aromatisse', 'Audino', 'Aurorus', 'Azelf', 'Banette', 'Bastiodon', 'Beheeyem', 'Bibarel', 'Blissey', 'Castform', 'Chansey', 'Cinccino', 'Clefable', 'Clefairy', 'Dedenne', 'Delcatty', 'Dragalge', 'Dragonite', 'Drampa', 'Drifblim', 'Dunsparce', 'Eelektross', 'Electivire', 'Electrode', 'Emolga', 'Ferroseed', 'Ferrothorn', 'Froslass', 'Furret', 'Gallade', 'Galvantula', 'Garbodor', 'Gardevoir', 'Gengar', 'Girafarig', 'Golem-Alola', 'Golurk', 'Goodra', 'Gothitelle', 'Granbull', 'Gyarados', 'Heliolisk', 'Illumise', 'Jirachi', 'Jolteon', 'Kangaskhan', 'Kecleon', 'Klinklang', 'Lanturn', 'Lapras', 'Latias', 'Latios', 'Lickilicky', 'Linoone', 'Lopunny', 'Luxray', 'Magearna', 'Magmortar', 'Magneton', 'Magnezone', 'Malamar', 'Manectric', 'Marowak-Alola', 'Marowak-Alola-Totem', 'Meloetta', 'Meowstic', 'Mesprit', 'Mew', 'Miltank', 'Mimikyu', 'Minun', 'Mismagius', 'Mr. Mime', 'Muk', 'Nidoking', 'Nidoqueen', 'Nihilego', 'Oranguru', 'Pachirisu', 'Persian', 'Plusle', 'Porygon-Z', 'Porygon2', 'Primeape', 'Probopass', 'Purugly', 'Raichu', 'Raikou', 'Rampardos', 'Raticate', 'Regice', 'Regigigas', 'Regirock', 'Registeel', 'Rhydon', 'Rhyperior', 'Rotom', 'Silvally', 'Slaking', 'Slurpuff', 'Smeargle', 'Snorlax', 'Stantler', 'Starmie', 'Stoutland', 'Stunfisk', 'Tapu Koko', 'Tapu Lele', 'Tauros', 'Thundurus', 'Togedemaru', 'Tyranitar', 'Uxie', 'Vikavolt', 'Volbeat', 'Watchog', 'Weezing', 'Wigglytuff', 'Xurkitree', 'Zangoose', 'Zapdos', 'Zebstrika', 'Zeraora'],
icebeam: ['Abomasnow', 'Absol', 'Aggron', 'Alomomola', 'Altaria', 'Araquanid', 'Articuno', 'Audino', 'Aurorus', 'Avalugg', 'Azumarill', 'Barbaracle', 'Basculin', 'Bastiodon', 'Beartic', 'Bibarel', 'Blastoise', 'Blissey', 'Bruxish', 'Carracosta', 'Castform', 'Chansey', 'Clawitzer', 'Claydol', 'Clefable', 'Clefairy', 'Cloyster', 'Corsola', 'Crabominable', 'Crawdaunt', 'Cresselia', 'Cryogonal', 'Delcatty', 'Delibird', 'Dewgong', 'Dragonite', 'Drampa', 'Dunsparce', 'Dusknoir', 'Empoleon', 'Exploud', 'Feraligatr', 'Floatzel', 'Froslass', 'Furret', 'Gastrodon', 'Glaceon', 'Glalie', 'Golduck', 'Golisopod', 'Golurk', 'Goodra', 'Gorebyss', 'Greninja', 'Gyarados', 'Huntail', 'Jellicent', 'Jynx', 'Kabutops', 'Kangaskhan', 'Kecleon', 'Kingdra', 'Kingler', 'Kyurem', 'Lanturn', 'Lapras', 'Latias', 'Latios', 'Lickilicky', 'Linoone', 'Lopunny', 'Ludicolo', 'Lumineon', 'Lunatone', 'Luvdisc', 'Magearna', 'Mamoswine', 'Manaphy', 'Mantine', 'Marowak', 'Masquerain', 'Mawile', 'Mesprit', 'Mew', 'Milotic', 'Miltank', 'Nidoking', 'Nidoqueen', 'Ninetales-Alola', 'Octillery', 'Omastar', 'Pelipper', 'Phione', 'Piloswine', 'Politoed', 'Poliwrath', 'Porygon-Z', 'Porygon2', 'Primarina', 'Quagsire', 'Qwilfish', 'Rampardos', 'Raticate', 'Regice', 'Relicanth', 'Rhydon', 'Rhyperior', 'Samurott', 'Seaking', 'Sharpedo', 'Sigilyph', 'Silvally', 'Simipour', 'Slaking', 'Slowbro', 'Slowking', 'Smeargle', 'Sneasel', 'Snorlax', 'Starmie', 'Suicune', 'Swalot', 'Swampert', 'Swanna', 'Tapu Fini', 'Tauros', 'Tentacruel', 'Toxapex', 'Tyranitar', 'Vanilluxe', 'Vaporeon', 'Wailord', 'Walrein', 'Weavile', 'Whiscash', 'Wigglytuff', 'Wishiwashi', 'Zangoose'],
};
// @ts-ignore Hack for Snaquaza's Z move
const baseMove = this.claimMove ? this.claimMove.id : 'bravebird';
const pool = claims[baseMove];
if (!pool) throw new Error(`SSB: Unable to find fake claim movepool for the move: "${baseMove}".`); // Should never happen
const claim = claims[baseMove][this.random(pool.length)];
// Generate new set
const generator = new RandomStaffBrosTeams('gen7randombattle', this.prng);
let set = generator.randomSet(claim);
// Suppress Ability now to prevent starting new abilities when transforming
pokemon.addVolatile('gastroacid', pokemon);
// Tranform into it
pokemon.formeChange(set.species);
for (let newMove of set.moves) {
let moveTemplate = this.getMove(newMove);
if (pokemon.moves.includes(moveTemplate.id)) continue;
pokemon.moveSlots.push({
move: moveTemplate.name,
id: moveTemplate.id,
pp: ((moveTemplate.noPPBoosts || moveTemplate.isZ) ? moveTemplate.pp : moveTemplate.pp * 8 / 5),
maxpp: ((moveTemplate.noPPBoosts || moveTemplate.isZ) ? moveTemplate.pp : moveTemplate.pp * 8 / 5),
target: moveTemplate.target,
disabled: false,
disabledSource: '',
used: false,
});
}
// Update HP
// @ts-ignore Hack for Snaquaza's Z Move
pokemon.m.claimHP = pokemon.hp;
pokemon.heal(pokemon.maxhp - pokemon.hp, pokemon);
this.add('-heal', pokemon, pokemon.getHealth, '[silent]');
this.add('message', `${pokemon.name} claims to be a ${set.species}!`);
},
isZ: "fakeclaimiumz",
secondary: null,
target: "normal",
type: "Dark",
},
// SpaceBass
armyofmushrooms: {
accuracy: true,
basePower: 0,
category: "Status",
desc: "Before the turn starts, this Pokemon boosts its Defense and Special Defense by one stage and uses Powder on the target. When this move hits, this Pokemon uses Sleep Powder and Leech Seed. This move's priority is -1 and cannot be boosted by Prankster.",
shortDesc: "+1 Def/SpD, Powder, Leech Seed, Sleep Powder.",
id: "armyofmushrooms",
name: "Army of Mushrooms",
isNonstandard: "Custom",
pp: 10,
priority: -1,
flags: {snatch: 1},
onTryMove() {
this.attrLastMove('[still]');
},
beforeTurnCallback(pokemon) {
if (pokemon.status === 'slp' || pokemon.status === 'frz') return;
this.boost({def: 1, spd: 1}, pokemon, pokemon, this.getEffect('mushroom army'));
this.useMove("powder", pokemon);
},
onHit(pokemon) {
this.useMove("sleeppowder", pokemon);
this.useMove("leechseed", pokemon);
},
secondary: null,
target: "self",
type: "Grass",
},
// SunGodVolcarona
scorchingglobalvortex: {
accuracy: true,
basePower: 200,
category: "Special",
desc: "Burns the target. Ignores abilities.",
shortDesc: "Burns the target. Ignores abilities.",
id: "scorchingglobalvortex",
name: "Scorching Global Vortex",
isNonstandard: "Custom",
pp: 1,
priority: 0,
flags: {},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Searing Sunraze Smash", target);
},
onHit(target, source) {
target.trySetStatus('brn', source);
},
ignoreAbility: true,
isZ: "volcaroniumz",
target: "normal",
type: "Fire",
},
// Teclis
zekken: {
accuracy: true,
basePower: 0,
category: "Status",
desc: "Raises the user's Attack by 2 stages and its Speed by 1 stage.",
shortDesc: "Raises the user's Attack by 2 and Speed by 1.",
id: "zekken",
name: "Zekken",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {snatch: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Swords Dance", source);
},
boosts: {
atk: 2,
spe: 1,
},
secondary: null,
target: "self",
type: "Fairy",
},
// tennisace
groundsurge: {
accuracy: 100,
basePower: 95,
category: "Special",
desc: "This move's type effectiveness against Ground is changed to be super effective no matter what this move's type is.",
shortDesc: "Super effective on Ground.",
id: "groundsurge",
name: "Ground Surge",
isNonstandard: "Custom",
pp: 15,
priority: 0,
flags: {protect: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Thunder", target);
this.add('-anim', source, "Fissure", target);
},
ignoreImmunity: {'Electric': true},
onEffectiveness(typeMod, target, type) {
if (type === 'Ground') return 1;
},
secondary: null,
target: "normal",
type: "Electric",
},
// Teremiare
rotate: {
accuracy: 100,
category: "Status",
desc: "The user's replacement will switch out after using their move on the next turn if the replacement's move is successful.",
shortDesc: "User's replacement will switch after using its move.",
id: "rotate",
name: "Rotate",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {snatch: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Celebrate", target);
},
sideCondition: "rotate",
effect: {
duration: 2,
onStart(source) {
this.add('-message', `${source.active[0].name}'s replacement is going to switch out next turn!`);
},
onModifyMove(move) {
move.selfSwitch = true;
},
onBeforeMove(source, move) {
this.add('-message', `${source.name} is preparing to switch out!`);
},
},
selfSwitch: true,
secondary: null,
target: "self",
type: "Normal",
},
// The Immortal
ultrasucc: {
accuracy: true,
basePower: 140,
category: "Physical",
desc: "Has a 100% chance to raise the user's Speed by 1 stage.",
shortDesc: "100% chance to raise the user's Speed by 1.",
id: "ultrasucc",
name: "Ultra Succ",
isNonstandard: "Custom",
pp: 1,
priority: 0,
flags: {},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Dragon Ascent", target);
},
secondary: {
chance: 100,
self: {
boosts: {
spe: 1,
},
},
},
isZ: "buzzniumz",
target: "normal",
type: "Fighting",
},
// The Leprechaun
gyroballin: {
accuracy: 100,
basePower: 0,
basePowerCallback(pokemon, target) {
let power = (Math.floor(25 * target.getStat('spe') / pokemon.getStat('spe')) || 1);
if (power > 150) power = 150;
this.debug('' + power + ' bp');
return power;
},
category: "Physical",
desc: "Base Power is equal to (25 * target's current Speed / user's current Speed) + 1, rounded down, but not more than 150. If the user's current Speed is 0, this move's power is 1. Summons Trick Room unless Trick Room is already active.",
shortDesc: "More power if slower; sets Trick Room.",
id: "gyroballin",
name: "Gyro Ballin'",
isNonstandard: "Custom",
pp: 5,
priority: 0,
flags: {bullet: 1, contact: 1, protect: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Gyro Ball", target);
},
onAfterMoveSecondarySelf(pokemon) {
if (!this.field.pseudoWeather.trickroom) {
this.field.addPseudoWeather('trickroom', pokemon);
}
this.add('-fieldactivate', 'move: Pay Day'); // Coins are scattered on the ground
},
secondary: null,
target: "normal",
type: "Steel",
zMovePower: 160,
contestType: "Cool",
},
// Tiksi
devolutionwave: {
accuracy: true,
basePower: 25,
category: "Physical",
desc: "This move hits 5 times. After the first hit, the target is either badly poisoned or paralyzed. After the second hit, the user swaps abilities with the target, or the target gains the Water type. After the third hit, Stealth Rock or one layer of Spikes is added to the opponent's side of the field. After the fourth hit, Grassy Terrain or Misty Terrain is summoned. After the fifth hit, the user's Attack or Defense is raised by 1.",
shortDesc: "Hits 5 times with various effects on each hit.",
id: "devolutionwave",
name: "Devolution Wave",
isNonstandard: "Custom",
pp: 1,
priority: 0,
flags: {},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Psywave", target);
},
multihit: 5,
onAfterHit(target, source, move) {
// @ts-ignore hack for tiksi's move
if (!move.curHits) move.curHits = 1;
let option = this.random(2);
this.add('-anim', source, 'Rock Throw', target);
// @ts-ignore hack for tiksi's move
switch (move.curHits) {
case 1:
if (option) {
target.trySetStatus('tox', source);
} else {
target.trySetStatus('par', source);
}
break;
case 2:
if (option) {
let bannedAbilities = ['battlebond', 'comatose', 'disguise', 'illusion', 'multitype', 'powerconstruct', 'rkssystem', 'schooling', 'shieldsdown', 'stancechange', 'wonderguard'];
if (bannedAbilities.includes(target.ability) || bannedAbilities.includes(source.ability)) {
this.add('-fail', target, 'move: Skill Swap');
break;
}
let targetAbility = this.getAbility(target.ability);
let sourceAbility = this.getAbility(source.ability);
if (target.side === source.side) {
this.add('-activate', source, 'move: Skill Swap', '', '', '[of] ' + target);
} else {
this.add('-activate', source, 'move: Skill Swap', targetAbility, sourceAbility, '[of] ' + target);
}
this.singleEvent('End', sourceAbility, source.abilityData, source);
this.singleEvent('End', targetAbility, target.abilityData, target);
if (targetAbility.id !== sourceAbility.id) {
source.ability = targetAbility.id;
target.ability = sourceAbility.id;
source.abilityData = {id: toId(source.ability), target: source};
target.abilityData = {id: toId(target.ability), target: target};
}
this.singleEvent('Start', targetAbility, source.abilityData, source);
this.singleEvent('Start', sourceAbility, target.abilityData, target);
} else {
if (!target.setType('Water')) {
this.add('-fail', target, 'move: Soak');
} else {
this.add('-start', target, 'typechange', 'Water');
}
}
break;
case 3:
if (option) {
target.side.addSideCondition('stealthrock');
} else {
target.side.addSideCondition('spikes');
}
break;
case 4:
if (option) {
this.field.setTerrain('grassyterrain', source);
} else {
this.field.setTerrain('mistyterrain', source);
}
break;
case 5:
if (option) {
this.boost({atk: 1}, source);
} else {
this.boost({def: 1}, source);
}
break;
}
// @ts-ignore hack for tiksi's move
move.curHits++;
},
isZ: "tiksiumz",
secondary: null,
target: "normal",
type: "Rock",
},
// torkool
smokebomb: {
accuracy: true,
category: "Status",
desc: "Moves all hazards that are on the user's side of the field to the foe's side of the field. Sets Stealth Rock on the foe's side, after which the user switches out.",
shortDesc: "Hazards -> foe side. Set SR. User switches out.",
id: "smokebomb",
name: "Smoke Bomb",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {snatch: 1, mirror: 1, reflectable: 1, authentic: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Smokescreen", target);
this.add('-anim', source, "Parting Shot", target);
},
onHit(target, source) {
const sideConditions = {'spikes': 1, 'toxicspikes': 1, 'stealthrock': 1, 'stickyweb': 1};
for (let i in sideConditions) {
let layers = source.side.sideConditions[i] ? (source.side.sideConditions[i].layers || 1) : 1;
if (source.side.removeSideCondition(i)) {
this.add('-sideend', source.side, this.getEffect(i).name, '[from] move: Smoke Bomb', '[of] ' + source);
for (layers; layers > 0; layers--) target.side.addSideCondition(i, source);
}
}
target.side.addSideCondition('stealthrock');
},
selfSwitch: true,
secondary: null,
target: "normal",
type: "Fire",
},
// Trickster
minisingularity: {
accuracy: 55,
basePower: 0,
basePowerCallback(pokemon, target) {
let targetWeight = target.getWeight();
if (targetWeight >= 200) {
this.debug('120 bp');
return 120;
}
if (targetWeight >= 100) {
this.debug('100 bp');
return 100;
}
if (targetWeight >= 50) {
this.debug('80 bp');
return 80;
}
if (targetWeight >= 25) {
this.debug('60 bp');
return 60;
}
if (targetWeight >= 10) {
this.debug('40 bp');
return 40;
}
this.debug('20 bp');
return 20;
},
category: "Special",
desc: "This move's Base Power is 20 if the target weighs less than 10 kg, 40 if its weight is less than 25 kg, 60 if its weight is less than 50 kg, 80 if its weight is less than 100 kg, 100 if its weight is less than 200 kg, and 120 if its weight is greater than or equal to 200 kg. After doing damage, the target's item is replaced with an Iron Ball, and the target's weight is doubled.",
shortDesc: "BP:weight; increases foe weight; foe item=Iron Ball.",
id: "minisingularity",
name: "Mini Singularity",
isNonstandard: "Custom",
pp: 5,
priority: 0,
flags: {protect: 1, mirror: 1},
volatileStatus: "minisingularity",
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Spacial Rend", target);
this.add('-anim', source, "Flash", target);
},
onAfterHit(target, source) {
if (source.hp) {
let item = target.takeItem();
if (!target.item) {
if (item) this.add('-enditem', target, item.name, '[from] move: Mini Singularity', '[of] ' + source);
target.setItem('ironball');
this.add('-message', target.name + ' obtained an Iron Ball.');
}
}
},
effect: {
noCopy: true,
onStart(pokemon) {
this.add('-message', pokemon.name + '\'s weight has doubled.');
},
onModifyWeight(weight) {
return weight * 2;
},
},
secondary: null,
target: "normal",
type: "Psychic",
},
// UnleashOurPassion
continuous1v1: {
accuracy: 90,
basePower: 120,
category: "Special",
desc: "Fully restores the user's HP if this move knocks out the target.",
shortDesc: "Fully restores user's HP if this move KOes the target.",
id: "continuous1v1",
name: "Continuous 1v1",
isNonstandard: "Custom",
pp: 15,
priority: 0,
flags: {protect: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Discharge", target);
this.add('-anim', source, "First Impression", target);
},
onAfterMoveSecondarySelf(pokemon, target, move) {
if (!target || target.fainted || target.hp <= 0) this.heal(pokemon.maxhp, pokemon, pokemon, move);
},
secondary: null,
target: "normal",
type: "Electric",
},
// urkerab
holyorders: {
accuracy: true,
basePower: 0,
category: "Status",
desc: "Summons two of Attack Order, Defense Order, and Heal Order at random to combine for some assortment of the following effects: has a Base Power of 90 and a higher chance for a critical hit, raises the user's Defense and Special Defense by 1 stage, and heals the user by half of its maximum HP, rounded half up.",
shortDesc: "Summons two of Attack, Defense, and Heal Order.",
id: "holyorders",
name: "Holy Orders",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {snatch: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onHit(target, source) {
let orders = ["healorder", "defendorder", "attackorder"];
this.shuffle(orders);
for (const [i, order] of orders.entries()) {
if (i > 1) return;
let target = order === "attackorder" ? source.side.foe.active[0] : source;
this.useMove(order, source, target);
}
},
secondary: null,
target: "self",
type: "Bug",
},
// Uselesscrab
revampedsuspectphilosophy: {
basePower: 160,
accuracy: true,
category: "Physical",
desc: "No additional effect.",
shortDesc: "No additional effect.",
id: "revampedsuspectphilosophy",
name: "Revamped Suspect Philosophy",
isNonstandard: "Custom",
pp: 1,
priority: 0,
flags: {},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Subzero Slammer", target);
this.add('-anim', source, "Tectonic Rage", target);
},
secondary: null,
isZ: "nichiumz",
target: "normal",
type: "Ground",
},
// Volco
explosivedrain: {
basePower: 90,
accuracy: 100,
category: "Special",
desc: "The user recovers half the HP lost by the target, rounded half up. If Big Root is held, the user recovers 1.3x the normal amount of HP, rounded half down.",
shortDesc: "User recovers 50% of the damage dealt.",
id: "explosivedrain",
name: "Explosive Drain",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {protect: 1, mirror: 1, heal: 1},
drain: [1, 2],
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Fire Blast", target);
this.add('-anim', source, "Giga Drain", target);
},
secondary: null,
target: "normal",
type: "Fire",
},
// Xayah
stunningdance: {
accuracy: 100,
basePower: 95,
category: "Special",
desc: "Has a 20% chance to make the target flinch and a 100% chance to paralyze the target. Prevents the target from switching out. The target can still switch out if it is holding Shed Shell or uses Baton Pass, Parting Shot, U-turn, or Volt Switch. If the target leaves the field using Baton Pass, the replacement will remain trapped. The effect ends if the user leaves the field.",
shortDesc: "20% to flinch; 100% to paralyze; traps target.",
id: "stunningdance",
name: "Stunning Dance",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {protect: 1, mirror: 1, dance: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Revelation Dance", source);
this.add('-anim', source, "Air Slash", target);
this.add('-anim', source, "Air Slash", target);
},
onHit(target, source, move) {
if (source.isActive) target.addVolatile('trapped', source, move, 'trapper');
},
secondaries: [
{
chance: 20,
volatileStatus: 'flinch',
},
{
chance: 100,
status: 'par',
},
],
zMovePower: 175,
target: "normal",
type: "Flying",
},
// XpRienzo ☑◡☑
blehflame: {
accuracy: 100,
basePower: 80,
category: "Special",
desc: "Has a 10% chance to raise all of the user's stats by 1 stage.",
shortDesc: "10% chance to raise all stats by 1 (not acc/eva).",
id: "blehflame",
name: "Bleh Flame",
isNonstandard: "Custom",
pp: 5,
priority: 0,
flags: {protect: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Flame Charge", target);
this.add('-anim', source, "Overheat", target);
},
secondary: {
chance: 10,
self: {
boosts: {
atk: 1,
def: 1,
spa: 1,
spd: 1,
spe: 1,
},
},
},
target: "normal",
type: "Fire",
},
// Yuki
cutieescape: {
accuracy: true,
category: "Status",
desc: "The user is replaced with another Pokemon in its party. The opponent is confused, trapped, and infatuated regardless of the replacement's gender. This move fails unless the user already took damage this turn.",
shortDesc: "If hit; switches out + confuses, traps, infatuates.",
id: "cutieescape",
name: "Cutie Escape",
isNonstandard: "Custom",
pp: 10,
priority: -6,
flags: {mirror: 1},
beforeTurnCallback(pokemon) {
pokemon.addVolatile('cutieescape');
this.add('-message', `${pokemon.name} is preparing to flee!`);
},
beforeMoveCallback(pokemon) {
if (!pokemon.volatiles['cutieescape'] || !pokemon.volatiles['cutieescape'].tookDamage) {
this.add('-fail', pokemon, 'move: Cutie Escape');
this.hint("Cutie Escape only works when Yuki is hit in the same turn the move is used.");
return true;
}
},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Baton Pass", source);
},
onHit(target, source) {
target.addVolatile('confusion');
target.addVolatile('cutietrap');
},
effect: {
duration: 1,
onStart(pokemon) {
this.add('-singleturn', pokemon, 'move: Cutie Escape');
},
onHit(pokemon, source, move) {
if (move.category !== 'Status') {
pokemon.volatiles['cutieescape'].tookDamage = true;
}
},
},
selfSwitch: true,
target: "normal",
type: "Fairy",
},
// Zarel
relicsongdance: {
accuracy: 100,
basePower: 60,
multihit: 2,
category: "Special",
desc: "Hits twice and ignores type immunities. Before the second hit, the user switches to its Pirouette forme, and this move's second hit deals physical Fighting-type damage. After the second hit, the user reverts to its Aria forme. Fails unless the user is Meloetta.",
shortDesc: "One hit each from user's Aria and Pirouette formes.",
id: "relicsongdance",
name: "Relic Song Dance",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {protect: 1, mirror: 1, sound: 1, authentic: 1},
ignoreImmunity: true,
onTryMove() {
this.attrLastMove('[still]');
},
onTryHit(target, pokemon) {
if (pokemon.name !== 'Zarel') {
this.add('-fail', pokemon);
this.hint("Only Zarel can use Relic Song Dance.");
return null;
}
this.attrLastMove('[still]');
let move = pokemon.template.speciesid === 'meloettapirouette' ? 'Brick Break' : 'Relic Song';
this.add('-anim', pokemon, move, target);
},
onHit(target, pokemon, move) {
if (pokemon.template.speciesid === 'meloettapirouette') {
pokemon.formeChange('Meloetta');
} else if (pokemon.formeChange('Meloetta-Pirouette')) {
move.category = 'Physical';
move.type = 'Fighting';
}
},
onAfterMove(pokemon) {
// Ensure Meloetta goes back to standard form after using the move
if (pokemon.template.speciesid === 'meloettapirouette') {
pokemon.formeChange('Meloetta');
}
this.hint("Zarel still has the Serene Grace ability.");
},
effect: {
duration: 1,
onAfterMoveSecondarySelf(pokemon, target, move) {
if (pokemon.template.speciesid === 'meloettapirouette') {
pokemon.formeChange('Meloetta');
} else {
pokemon.formeChange('Meloetta-Pirouette');
}
pokemon.removeVolatile('relicsong');
},
},
target: "allAdjacentFoes",
type: "Psychic",
},
// Zyg
mylife: {
accuracy: true,
category: "Status",
desc: "Badly poisons all Pokemon on the field.",
shortDesc: "Badly poisons all Pokemon on the field.",
id: "mylife",
name: "My Life",
isNonstandard: "Custom",
pp: 10,
priority: 0,
flags: {protect: 1, mirror: 1},
onTryMove() {
this.attrLastMove('[still]');
},
onPrepareHit(target, source) {
this.add('-anim', source, "Toxic", target);
},
onHit(target, source) {
let success = false;
if (target.trySetStatus('tox', source)) success = true;
if (source.trySetStatus('tox', source)) success = true;
return success;
},
secondary: null,
target: "normal",
type: "Poison",
},
// Modified Moves \\
// Purple Pills is immune to taunt
"taunt": {
inherit: true,
volatileStatus: 'taunt',
effect: {
duration: 3,
onStart(target) {
if (target.activeTurns && !this.willMove(target)) {
this.effectData.duration++;
}
this.add('-start', target, 'move: Taunt');
},
onResidualOrder: 12,
onEnd(target) {
this.add('-end', target, 'move: Taunt');
},
onDisableMove(pokemon) {
for (const moveSlot of pokemon.moveSlots) {
if (this.getMove(moveSlot.id).category === 'Status' && this.getMove(moveSlot.id).id !== 'purplepills') {
pokemon.disableMove(moveSlot.id);
}
}
},
onBeforeMovePriority: 5,
onBeforeMove(attacker, defender, move) {
if (!move.isZ && move.category === 'Status' && move.id !== 'purplepills') {
this.add('cant', attacker, 'move: Taunt', move);
return false;
}
},
},
},
};
exports.BattleMovedex = BattleMovedex;
| 32.952863 | 1,639 | 0.644928 |
6fccaa29565d5447411c8ae0fc7a935a8324caef | 2,526 | js | JavaScript | lib/main.js | Poolitzer/notifier-action | d28b85e921efb8603d16a47df85392707342668b | [
"MIT"
] | null | null | null | lib/main.js | Poolitzer/notifier-action | d28b85e921efb8603d16a47df85392707342668b | [
"MIT"
] | null | null | null | lib/main.js | Poolitzer/notifier-action | d28b85e921efb8603d16a47df85392707342668b | [
"MIT"
] | null | null | null | "use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const core = __importStar(require("@actions/core"));
const github = __importStar(require("@actions/github"));
function run() {
return __awaiter(this, void 0, void 0, function* () {
try {
const notifyMessage = core.getInput('notify-message', { required: true });
const repoToken = core.getInput('repo-token', { required: true });
const issue = github.context.issue;
if (github.context.payload.repository) {
}
else {
console.log('No pull request, skipping');
return;
}
const client = new github.GitHub(repoToken);
const comments = yield client.pulls.listReviews({
owner: issue.owner,
repo: issue.repo,
pull_number: issue.number
});
for (let entry of comments['data']) {
if (entry['user']['id'] == 41898282) {
if (entry['body'] == notifyMessage) {
console.log('Already commented, skipping');
return;
}
}
}
;
yield client.pulls.createReview({
owner: issue.owner,
repo: issue.repo,
pull_number: issue.number,
body: notifyMessage,
event: 'COMMENT'
});
}
catch (error) {
core.setFailed(error.message);
throw error;
}
});
}
exports.run = run;
run();
| 40.095238 | 151 | 0.530879 |
6fcda8eeb01d3b897280ed9517413dacc3e8adac | 473 | js | JavaScript | app/components/LocalDbManager.js | lis355/ksl | e34259ca49068def0b8b72397bacd1831129f9b6 | [
"MIT"
] | null | null | null | app/components/LocalDbManager.js | lis355/ksl | e34259ca49068def0b8b72397bacd1831129f9b6 | [
"MIT"
] | null | null | null | app/components/LocalDbManager.js | lis355/ksl | e34259ca49068def0b8b72397bacd1831129f9b6 | [
"MIT"
] | null | null | null | const low = require("lowdb");
const FileSync = require("lowdb/adapters/FileSync");
const DB_FILE_NAME = "db.json";
module.exports = class LocalDbManager extends ndapp.ApplicationComponent {
async initialize() {
await super.initialize();
const dbFileName = app.userDataManager.userDataPath(DB_FILE_NAME);
const adapter = new FileSync(dbFileName);
this.db = low(adapter);
this.db
.defaultsDeep({
cache: {}
})
.write();
}
};
| 21.5 | 75 | 0.67019 |
6fcde55b95d7f1a6f7582692bd61d27e285ed90f | 1,520 | js | JavaScript | src/Subheader/Subheader.react.js | Brucbbro/react-native-material-ui | 0ca39f7a1eeab9214051fc9f46fd2f4cc86f8221 | [
"MIT"
] | 1 | 2018-03-18T06:01:54.000Z | 2018-03-18T06:01:54.000Z | src/Subheader/Subheader.react.js | Brucbbro/react-native-material-ui | 0ca39f7a1eeab9214051fc9f46fd2f4cc86f8221 | [
"MIT"
] | null | null | null | src/Subheader/Subheader.react.js | Brucbbro/react-native-material-ui | 0ca39f7a1eeab9214051fc9f46fd2f4cc86f8221 | [
"MIT"
] | 2 | 2018-02-15T18:32:54.000Z | 2019-05-17T19:42:51.000Z | /* eslint-disable import/no-unresolved, import/extensions */
import { View, Text } from 'react-native';
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
/* eslint-enable import/no-unresolved, import/extensions */
import { ViewPropTypes } from '../utils';
const propTypes = {
text: PropTypes.string.isRequired,
inset: PropTypes.bool,
lines: PropTypes.number,
style: PropTypes.shape({
contaienr: ViewPropTypes.style,
text: Text.propTypes.style,
}),
};
const defaultProps = {
style: {},
inset: false,
lines: 1,
};
const contextTypes = {
uiTheme: PropTypes.object.isRequired,
};
function getStyles(props, context) {
const { subheader } = context.uiTheme;
return {
container: [
subheader.container,
{ paddingLeft: props.inset ? 72 : 16 },
props.style.container,
],
text: [
subheader.text,
props.style.text,
],
};
}
class Subheader extends PureComponent {
render() {
const { text, lines } = this.props;
const styles = getStyles(this.props, this.context);
return (
<View style={styles.container} >
<Text numberOfLines={lines} style={styles.text}>
{text}
</Text>
</View>
);
}
}
Subheader.propTypes = propTypes;
Subheader.defaultProps = defaultProps;
Subheader.contextTypes = contextTypes;
export default Subheader;
| 24.126984 | 64 | 0.598026 |
6fce05cc82bbaa3a5a2772b22ccf48ffef2c11cf | 579 | js | JavaScript | lib/css-modules.js | fastcms/stylelint-config | cb7b3b295a0b8027e7e659f50a2a3950a4f522c6 | [
"MIT"
] | null | null | null | lib/css-modules.js | fastcms/stylelint-config | cb7b3b295a0b8027e7e659f50a2a3950a4f522c6 | [
"MIT"
] | 3 | 2021-06-16T15:16:57.000Z | 2021-10-20T06:03:31.000Z | lib/css-modules.js | fastcms/stylelint-config | cb7b3b295a0b8027e7e659f50a2a3950a4f522c6 | [
"MIT"
] | null | null | null | /**
* @type {import("stylelint").Configuration}
*/
module.exports = {
rules: {
'selector-pseudo-class-no-unknown': [
true,
{
ignorePseudoClasses: ['export', 'import', 'global', 'local', 'external'],
},
],
'property-no-unknown': [
true,
{
ignoreProperties: ['composes', 'compose-with'],
ignoreSelectors: [':export', /^:import/],
},
],
'at-rule-no-unknown': [
true,
{
ignoreAtRules: ['apply', 'responsive', 'screen', 'tailwind', 'value', 'variants'],
},
],
},
};
| 19.965517 | 90 | 0.499136 |
6fce1dd937ad3c33967a8fa8a062d97ab424a3c2 | 8,918 | js | JavaScript | build-system/tasks/prepend-global/index.js | deekshithraop/amphtml | 08a6c76cdcdf343fb25d6f11435228fcc8a02d55 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2020-04-23T04:46:42.000Z | 2021-02-27T18:18:52.000Z | build-system/tasks/prepend-global/index.js | deekshithraop/amphtml | 08a6c76cdcdf343fb25d6f11435228fcc8a02d55 | [
"ECL-2.0",
"Apache-2.0"
] | 7 | 2021-01-23T07:30:44.000Z | 2022-03-02T10:06:32.000Z | build-system/tasks/prepend-global/index.js | deekshithraop/amphtml | 08a6c76cdcdf343fb25d6f11435228fcc8a02d55 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-08-12T14:53:01.000Z | 2019-08-12T14:53:01.000Z | /**
* Copyright 2016 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const argv = require('minimist')(process.argv.slice(2));
const BBPromise = require('bluebird');
const childProcess = require('child_process');
const exec = BBPromise.promisify(childProcess.exec);
const colors = require('ansi-colors');
const fs = BBPromise.promisifyAll(require('fs'));
const log = require('fancy-log');
const path = require('path');
const {isTravisBuild} = require('../../travis');
const {red, cyan} = colors;
/**
* Returns the number of AMP_CONFIG matches in the given config string.
*
* @param {string} str
* @return {number}
*/
function numConfigs(str) {
const re = /\/\*AMP_CONFIG\*\//g;
const matches = str.match(re);
return matches == null ? 0 : matches.length;
}
/**
* Checks that only 1 AMP_CONFIG should exist after append.
*
* @param {string} str
*/
function sanityCheck(str) {
const numMatches = numConfigs(str);
if (numMatches != 1) {
throw new Error(
'Found ' + numMatches + ' AMP_CONFIG(s) before write. Aborting!'
);
}
}
/**
* @param {string} filename File containing the config
* @param {string=} opt_localBranch Whether to use the local branch version
* @param {string=} opt_branch If not the local branch, which branch to use
* @return {!Promise}
*/
function checkoutBranchConfigs(filename, opt_localBranch, opt_branch) {
if (opt_localBranch) {
return Promise.resolve();
}
const branch = opt_branch || 'origin/master';
// One bad path here will fail the whole operation.
return exec(`git checkout ${branch} ${filename}`).catch(function(e) {
// This means the files don't exist in master. Assume that it exists
// in the current branch.
if (/did not match any file/.test(e.message)) {
return;
}
throw e;
});
}
/**
* @param {string} configString String containing the AMP config
* @param {string} fileString String containing the AMP runtime
* @return {string}
*/
function prependConfig(configString, fileString) {
return (
`self.AMP_CONFIG||(self.AMP_CONFIG=${configString});` +
`/*AMP_CONFIG*/${fileString}`
);
}
/**
* @param {string} filename Destination filename
* @param {string} fileString String to write
* @param {boolean=} opt_dryrun If true, print the contents without writing them
* @return {!Promise}
*/
function writeTarget(filename, fileString, opt_dryrun) {
if (opt_dryrun) {
log(cyan(`overwriting: ${filename}`));
log(fileString);
return Promise.resolve();
}
return fs.writeFileAsync(filename, fileString);
}
/**
* @param {string|boolean} value
* @param {string} defaultValue
* @return {string}
*/
function valueOrDefault(value, defaultValue) {
if (typeof value === 'string') {
return value;
}
return defaultValue;
}
/**
* @param {string} config Prod or canary
* @param {string} target File containing the AMP runtime (amp.js or v0.js)
* @param {string} filename File containing the (prod or canary) config
* @param {boolean=} opt_localDev Whether to enable local development
* @param {boolean=} opt_localBranch Whether to use the local branch version
* @param {string=} opt_branch If not the local branch, which branch to use
* @param {boolean=} opt_fortesting Whether to force getMode().test to be true
* @return {!Promise}
*/
function applyConfig(
config,
target,
filename,
opt_localDev,
opt_localBranch,
opt_branch,
opt_fortesting
) {
return checkoutBranchConfigs(filename, opt_localBranch, opt_branch)
.then(() => {
return Promise.all([
fs.readFileAsync(filename),
fs.readFileAsync(target),
]);
})
.then(files => {
let configJson;
try {
configJson = JSON.parse(files[0].toString());
} catch (e) {
log(red(`Error parsing config file: ${filename}`));
throw e;
}
if (opt_localDev) {
configJson = enableLocalDev(config, target, configJson);
}
if (opt_fortesting) {
configJson = Object.assign({test: true}, configJson);
}
const targetString = files[1].toString();
const configString = JSON.stringify(configJson);
return prependConfig(configString, targetString);
})
.then(fileString => {
sanityCheck(fileString);
return writeTarget(target, fileString, argv.dryrun);
})
.then(() => {
if (!isTravisBuild()) {
const details =
'(' +
cyan(config) +
(opt_localDev ? ', ' + cyan('localDev') : '') +
(opt_fortesting ? ', ' + cyan('test') : '') +
')';
log('Applied AMP config', details, 'to', cyan(path.basename(target)));
}
});
}
/**
* @param {string} config Prod or canary
* @param {string} target File containing the AMP runtime (amp.js or v0.js)
* @param {string} configJson The json object in which to enable local dev
* @return {string}
*/
function enableLocalDev(config, target, configJson) {
let LOCAL_DEV_AMP_CONFIG = {localDev: true};
const TESTING_HOST = process.env.AMP_TESTING_HOST;
if (typeof TESTING_HOST == 'string') {
const TESTING_HOST_FULL_URL = TESTING_HOST.match(/^https?:\/\//)
? TESTING_HOST
: 'http://' + TESTING_HOST;
const TESTING_HOST_NO_PROTOCOL = TESTING_HOST.replace(/^https?:\/\//, '');
LOCAL_DEV_AMP_CONFIG = Object.assign(LOCAL_DEV_AMP_CONFIG, {
thirdPartyUrl: TESTING_HOST_FULL_URL,
thirdPartyFrameHost: TESTING_HOST_NO_PROTOCOL,
thirdPartyFrameRegex: TESTING_HOST_NO_PROTOCOL,
});
if (!isTravisBuild()) {
log(
'Set',
cyan('TESTING_HOST'),
'to',
cyan(TESTING_HOST),
'in',
cyan(target)
);
}
}
return Object.assign(LOCAL_DEV_AMP_CONFIG, configJson);
}
/**
* @param {string} target Target file from which to remove the AMP config
* @return {!Promise}
*/
function removeConfig(target) {
return fs.readFileAsync(target).then(file => {
let contents = file.toString();
if (numConfigs(contents) == 0) {
return Promise.resolve();
}
sanityCheck(contents);
const config = /self\.AMP_CONFIG\|\|\(self\.AMP_CONFIG=.*?\/\*AMP_CONFIG\*\//;
contents = contents.replace(config, '');
return writeTarget(target, contents, argv.dryrun).then(() => {
if (!isTravisBuild()) {
log('Removed existing config from', cyan(target));
}
});
});
}
async function prependGlobal() {
const TESTING_HOST = process.env.AMP_TESTING_HOST;
const target = argv.target || TESTING_HOST;
if (!target) {
log(red('Missing --target.'));
return;
}
if (argv.remove) {
return removeConfig(target);
}
if (!(argv.prod || argv.canary)) {
log(red('One of --prod or --canary should be provided.'));
return;
}
let filename = '';
// Prod by default.
const config = argv.canary ? 'canary' : 'prod';
if (argv.canary) {
filename = valueOrDefault(
argv.canary,
'build-system/global-configs/canary-config.json'
);
} else {
filename = valueOrDefault(
argv.prod,
'build-system/global-configs/prod-config.json'
);
}
return removeConfig(target).then(() => {
return applyConfig(
config,
target,
filename,
argv.local_dev,
argv.local_branch,
argv.branch,
argv.fortesting
);
});
}
module.exports = {
applyConfig,
checkoutBranchConfigs,
numConfigs,
prependConfig,
prependGlobal,
removeConfig,
sanityCheck,
valueOrDefault,
writeTarget,
};
prependGlobal.description = 'Prepends a json config to a target file';
prependGlobal.flags = {
'target': ' The file to prepend the json config to.',
'canary':
' Prepend the default canary config. ' +
'Takes in an optional value for a custom canary config source.',
'prod':
' Prepend the default prod config. ' +
'Takes in an optional value for a custom prod config source.',
'local_dev': ' Enables runtime to be used for local development.',
'branch':
' Switch to a git branch to get config source from. ' +
'Uses master by default.',
'local_branch':
" Don't switch branches and use the config from the local branch.",
'fortesting': ' Force the config to return true for getMode().test',
'remove':
' Removes previously prepended json config from the target ' +
'file (if present).',
};
| 28.675241 | 82 | 0.653622 |
6fce5c6bc9d1338667446c832ef2858df21a8e91 | 1,126 | js | JavaScript | src/js/options.js | WagnerDeQueiroz/chrome.ipcamviewer | 6f41c0cf017a2da148ee62f75bb5a8ae0811dfb0 | [
"MIT"
] | 15 | 2018-02-14T17:39:04.000Z | 2022-02-07T19:51:26.000Z | src/js/options.js | WagnerDeQueiroz/chrome.ipcamviewer | 6f41c0cf017a2da148ee62f75bb5a8ae0811dfb0 | [
"MIT"
] | 15 | 2018-04-03T17:35:20.000Z | 2022-02-18T03:25:28.000Z | src/js/options.js | WagnerDeQueiroz/chrome.ipcamviewer | 6f41c0cf017a2da148ee62f75bb5a8ae0811dfb0 | [
"MIT"
] | 9 | 2018-02-14T17:39:05.000Z | 2021-09-08T21:18:14.000Z | import './../img/icon16.png';
import './../img/icon48.png';
import './../img/icon128.png';
import Vue from 'vue';
import VueRouter from 'vue-router';
import App from './../components/App.vue';
import Fullscreen from './../components/Fullscreen.vue';
import Settings from './../components/Settings.vue';
import Multiview from './../components/Multiview.vue';
chrome.storage.sync.get(['connections'], result => {
if (result && result.connections) {
localStorage.setItem('connections', JSON.stringify(result.connections));
} else {
const connectionsString = localStorage.getItem('connections');
if (!connectionsString) {
localStorage.setItem('connections', JSON.stringify([]));
}
}
});
Vue.use(VueRouter);
const routes = [
{ path: '/multiview', name: 'multiview', component: Multiview, meta: { uri: 'multiview' } },
{ path: '/', name: 'settings', component: Settings, meta: { uri: 'settings' } },
{ path: '*', name: 'fullscreen', component: Fullscreen, meta: { uri: 'fullscreen' } }
];
const router = new VueRouter({
routes
});
new Vue({
el: '#app',
router,
render: h => h(App)
});
| 28.871795 | 94 | 0.653641 |
6fceae94d694e67c00500f536f1bd91607ffa571 | 704 | js | JavaScript | resources/assets/js/stores/PositionStore/mutations.js | thel5coder/jumbara9jatim | 9cb85119b505dd19ac486b81bdffa21e989a62fc | [
"MIT"
] | null | null | null | resources/assets/js/stores/PositionStore/mutations.js | thel5coder/jumbara9jatim | 9cb85119b505dd19ac486b81bdffa21e989a62fc | [
"MIT"
] | 1 | 2021-01-05T08:19:47.000Z | 2021-01-05T08:19:47.000Z | resources/assets/js/stores/PositionStore/mutations.js | thel5coder/jumbara9jatim | 9cb85119b505dd19ac486b81bdffa21e989a62fc | [
"MIT"
] | null | null | null | import * as types from '../mutation-types';
export default {
[types.BROWSE](state, { data }) {
state.positions = data;
},
[types.READ](state,{index,data}){
if(index == null){
state.position = data
}else{
state.position = state.positions[index]
}
},
[types.EDIT](state,{index,data}){
state.positions[index].positionId = data.positionId
state.positions[index].positionName = data.positionName
state.positions[index].isActive = data.isActive
},
[types.ADD](state,{data}){
state.positions.push(data)
},
[types.DELETE](state,{index}){
state.positions.splice(index,1)
}
};
| 27.076923 | 63 | 0.576705 |
6fcf1f89f6ea66b497d2cfecb912d2ffe0a45bdd | 125 | js | JavaScript | src/example.spec.js | csterritt/react_golden_layout_example | 48bb6e8d0efdff2b095e44a2b0aa53ef23aff183 | [
"MIT"
] | 9 | 2016-04-05T08:13:00.000Z | 2021-08-10T05:48:40.000Z | src/example.spec.js | csterritt/react_golden_layout_example | 48bb6e8d0efdff2b095e44a2b0aa53ef23aff183 | [
"MIT"
] | null | null | null | src/example.spec.js | csterritt/react_golden_layout_example | 48bb6e8d0efdff2b095e44a2b0aa53ef23aff183 | [
"MIT"
] | 3 | 2016-06-15T09:07:40.000Z | 2018-06-17T07:30:09.000Z | import expect from 'expect';
describe('example', () => {
it('should work', () => {
expect(1 + 1).toEqual(2);
})
});
| 15.625 | 29 | 0.52 |
6fd0863b465e91e38f05e9b2b847719fe8d2c3ad | 3,145 | js | JavaScript | lib/decode/lldp_tlv.js | tkokada/node_htip_dev | 63a1c1d141ad4be49fde20fff4d192d35a2b24bf | [
"MIT"
] | null | null | null | lib/decode/lldp_tlv.js | tkokada/node_htip_dev | 63a1c1d141ad4be49fde20fff4d192d35a2b24bf | [
"MIT"
] | null | null | null | lib/decode/lldp_tlv.js | tkokada/node_htip_dev | 63a1c1d141ad4be49fde20fff4d192d35a2b24bf | [
"MIT"
] | null | null | null | // tkokada modified
var EthernetAddr = require("./ethernet_addr");
var HtipTlv = require("./htip_tlv");
var ChassisIdTlv = function(raw_packet, offset, len) {
if (!(this instanceof ChassisIdTlv)) {
return new ChassisIdTlv(raw_packet, offset);
}
this.subtype = raw_packet.readUInt8(offset);
// Currently, the chassis id is assumed as 6 octets MAC address.
if (this.subtype === 4 && len === 7) {
var ether = new EthernetAddr(raw_packet, offset + 1);
this.chassisid = ether.toString();
} else {
this.chassisid = null;
}
};
ChassisIdTlv.prototype.toString = function () {
return "subtype: " + this.subtype + ", chassis id: " + this.chassisid;
};
var PortIdTlv = function(raw_packet, offset, len) {
if (!(this instanceof PortIdTlv)) {
return new PortIdTlv(raw_packet, offset);
}
this.subtype = raw_packet.readUInt8(offset);
// Currently, the data is assumed as 6 octets MAC address.
if (this.subtype === 3 && len === 7) {
var ether = new EthernetAddr(raw_packet, offset + 1);
this.portid = ether.toString();
} else {
this.portid = raw_packet.toString("ascii", offset + 1, offset + len);
}
};
PortIdTlv.prototype.toString = function () {
return "subtype: " + this.subtype + ", port id: " + this.portid;
};
var TtlTlv = function(raw_packet, offset, len) {
if (!(this instanceof TtlTlv)) {
return new TtlTlv(raw_packet, offset);
}
if (len !== 2) {
console.log("TTL TLV should have two octets value.");
}
this.ttl = raw_packet.readUInt16BE(offset);
};
TtlTlv.prototype.toString = function () {
return "ttl: " + this.ttl;
};
var PortDescTlv = function(raw_packet, offset, len) {
if (!(this instanceof PortDescTlv)) {
return new PortDescTlv(raw_packet, offset);
}
this.portdesc = raw_packet.toString("ascii", offset, offset + len);
};
PortDescTlv.prototype.toString = function () {
return "port desc: " + this.portdesc;
};
var Tlv = function(raw_packet, offset) {
if (!(this instanceof Tlv)) {
return new Tlv(raw_packet, offset);
}
this.tlv_type = raw_packet.readUInt8(offset) >>> 1;
this.tlv_length = raw_packet.readUInt16BE(offset) & 511;
switch (this.tlv_type) {
case 0x00: // End Of LLDPDU
this.payload = null;
break;
case 0x01: // Chassis ID
this.payload = new ChassisIdTlv(raw_packet, offset + 2, this.tlv_length);
break;
case 0x02: // Port ID
this.payload = new PortIdTlv(raw_packet, offset + 2, this.tlv_length);
break;
case 0x03: // Time to Live
this.payload = new TtlTlv(raw_packet, offset + 2, this.tlv_length);
break;
case 0x04: // Port Description
this.payload = new PortDescTlv(raw_packet, offset + 2, this.tlv_length);
break;
case 0x7f: // Organazation specific
this.payload = new HtipTlv(raw_packet, offset + 2, this.tlv_length);
break;
default:
console.log("node_pcap: LLDP() - Don't know how to decode TLV type " + this.tlv_type);
}
};
Tlv.prototype.toString = function () {
return "tlv_type: " + this.tlv_type + ", tlv_len: " + this.tlv_length + "payload: " + this.payload;
};
module.exports = Tlv;
| 30.833333 | 103 | 0.655962 |
6fd0b5ec8a8cbeb9f1be77a5d6cf5cee1440dc32 | 477 | js | JavaScript | test/CashableUniswapAaveStrategy.test.js | GoldenSylph/cashable-factory | d088eee81c48fb3d1ec340867ed666a0cfede21c | [
"MIT"
] | null | null | null | test/CashableUniswapAaveStrategy.test.js | GoldenSylph/cashable-factory | d088eee81c48fb3d1ec340867ed666a0cfede21c | [
"MIT"
] | null | null | null | test/CashableUniswapAaveStrategy.test.js | GoldenSylph/cashable-factory | d088eee81c48fb3d1ec340867ed666a0cfede21c | [
"MIT"
] | null | null | null | /* eslint no-unused-vars: 0 */
/* eslint eqeqeq: 0 */
const { expect, assert } = require('chai');
const {
BN,
constants,
expectEvent,
expectRevert,
ether,
time
} = require('@openzeppelin/test-helpers');
const { ZERO_ADDRESS } = constants;
const { ZERO, ONE, getMockTokenPrepared, processEventArgs, checkSetter } = require('./utils/common.js');
const MockContract = artifacts.require("MockContract");
contract('CashableUniswapAaveStrategy', (accounts) => {
});
| 21.681818 | 104 | 0.69392 |
6fd2487b481a7ded5fd2f7273d34dbe359312b76 | 895 | js | JavaScript | src/flashes/service.js | youka-project/youka-client | 08a5a8cf00191746fd4de9a5bb1eaa3b64612b04 | [
"MIT"
] | null | null | null | src/flashes/service.js | youka-project/youka-client | 08a5a8cf00191746fd4de9a5bb1eaa3b64612b04 | [
"MIT"
] | 7 | 2015-04-10T15:31:24.000Z | 2015-04-11T14:55:51.000Z | src/flashes/service.js | youka-project/youka-client | 08a5a8cf00191746fd4de9a5bb1eaa3b64612b04 | [
"MIT"
] | null | null | null | import Service from '../common/service';
import Collection from './collection';
import CollectionView from './collection-view';
export default Service.extend({
channelName: 'flashes',
initialize(options) {
this.container = options.container;
this.collection = new Collection();
this.start();
},
onStart() {
this._showFlashesView();
this._bindChannelCommands();
},
onStop() {
this.channel.stopComplying();
},
add(flash) {
this.collection.add(flash);
},
remove(flash) {
var model = this.collection.findWhere(flash);
if (model) {
model.destroy();
}
},
_showFlashesView() {
this.view = new CollectionView({
collection: this.collection
});
this.container.show(this.view);
},
_bindChannelCommands() {
this.channel.comply({
add : this.add,
remove : this.remove
}, this);
}
});
| 18.645833 | 49 | 0.623464 |
6fd2c69bdca59f1331e26b35c594e35674f0c6a4 | 158 | js | JavaScript | postcss.config.js | wuzhanfly/filescan-frontend | 07dd9bf9a265ae1b7e73332e95c252c6e7e57bb2 | [
"Apache-2.0",
"MIT"
] | null | null | null | postcss.config.js | wuzhanfly/filescan-frontend | 07dd9bf9a265ae1b7e73332e95c252c6e7e57bb2 | [
"Apache-2.0",
"MIT"
] | null | null | null | postcss.config.js | wuzhanfly/filescan-frontend | 07dd9bf9a265ae1b7e73332e95c252c6e7e57bb2 | [
"Apache-2.0",
"MIT"
] | null | null | null | module.exports = {
plugins: {
autoprefixer: {},
"postcss-px-to-viewport": {
viewportWidth: 1920,
minPixelValue: 2
}
}
};
| 15.8 | 32 | 0.518987 |
6fd31510e313c2e7e226b4257f11f0737f516cb3 | 8,301 | js | JavaScript | site2/website/pages/en/download.js | joefk/pulsar | 4b820cdcafe2e6af7f051242127b41dc4c0ec714 | [
"Apache-2.0"
] | null | null | null | site2/website/pages/en/download.js | joefk/pulsar | 4b820cdcafe2e6af7f051242127b41dc4c0ec714 | [
"Apache-2.0"
] | 1 | 2020-07-18T23:23:51.000Z | 2020-07-18T23:23:51.000Z | site2/website/pages/en/download.js | joefk/pulsar | 4b820cdcafe2e6af7f051242127b41dc4c0ec714 | [
"Apache-2.0"
] | null | null | null | const React = require('react');
const CompLibrary = require('../../core/CompLibrary');
const MarkdownBlock = CompLibrary.MarkdownBlock; /* Used to read markdown */
const Container = CompLibrary.Container;
const GridBlock = CompLibrary.GridBlock;
const CWD = process.cwd();
const translate = require('../../server/translate.js').translate;
const siteConfig = require(`${CWD}/siteConfig.js`);
const releases = require(`${CWD}/releases.json`);
function getLatestArchiveMirrorUrl(version, type) {
return `https://www.apache.org/dyn/mirrors/mirrors.cgi?action=download&filename=pulsar/pulsar-${version}/apache-pulsar-${version}-${type}.tar.gz`
}
function distUrl(version, type) {
return `https://www.apache.org/dist/pulsar/pulsar-${version}/apache-pulsar-${version}-${type}.tar.gz`
}
function archiveUrl(version, type) {
return `https://archive.apache.org/dist/pulsar/pulsar-${version}/apache-pulsar-${version}-${type}.tar.gz`
}
class Download extends React.Component {
render() {
const latestVersion = releases[0];
const latestArchiveMirrorUrl = getLatestArchiveMirrorUrl(latestVersion, 'bin');
const latestSrcArchiveMirrorUrl = getLatestArchiveMirrorUrl(latestVersion, 'src');
const latestArchiveUrl = distUrl(latestVersion, 'bin');
const latestSrcArchiveUrl = distUrl(latestVersion, 'src')
const releaseInfo = releases.map(version => {
return {
version: version,
binArchiveUrl: archiveUrl(version, 'bin'),
srcArchiveUrl: archiveUrl(version, 'src')
}
});
return (
<div className="pageContainer">
<Container className="mainContainer documentContainer postContainer">
<div className="post">
<header className="postHeader">
<h1><translate>Apache Pulsar downloads</translate></h1>
<hr />
</header>
<h2 id="latest"><translate>Current version (Stable)</translate> {latestVersion}</h2>
<table className="versions" style={{width:'100%'}}>
<thead>
<tr>
<th><translate>Release</translate></th>
<th><translate>Link</translate></th>
<th><translate>Crypto files</translate></th>
</tr>
</thead>
<tbody>
<tr key={'binary'}>
<th><translate>Binary</translate></th>
<td>
<a href={latestArchiveMirrorUrl}>apache-pulsar-{latestVersion}-bin.tar.gz</a>
</td>
<td>
<a href={`${latestArchiveUrl}.asc`}>asc</a>,
<a href={`${latestArchiveUrl}.sha512`}>sha512</a>
</td>
</tr>
<tr key={'source'}>
<th><translate>Source</translate></th>
<td>
<a href={latestSrcArchiveMirrorUrl}>apache-pulsar-{latestVersion}-src.tar.gz</a>
</td>
<td>
<a href={`${latestSrcArchiveUrl}.asc`}>asc</a>,
<a href={`${latestSrcArchiveUrl}.sha512`}>sha512</a>
</td>
</tr>
</tbody>
</table>
<h2><translate>Release Integrity</translate></h2>
<MarkdownBlock>
You must [verify](https://www.apache.org/info/verification.html) the integrity of the downloaded files.
We provide OpenPGP signatures for every release file. This signature should be matched against the
[KEYS](https://www.apache.org/dist/incubator/pulsar/KEYS) file which contains the OpenPGP keys of
Pulsar's Release Managers. We also provide `SHA-512` checksums for every release file.
After you download the file, you should calculate a checksum for your download, and make sure it is
the same as ours.
</MarkdownBlock>
<h2><translate>Release notes</translate></h2>
<div>
<p>
<a href={`${siteConfig.baseUrl}${this.props.language}/release-notes`}>Release notes</a> for all Pulsar's versions
</p>
</div>
<h2><translate>Getting started</translate></h2>
<div>
<p>
<translate>
Once you've downloaded a Pulsar release, instructions on getting up and running with a standalone cluster
that you can run on your laptop can be found in the{' '}
</translate>
<a href={`${siteConfig.baseUrl}docs/${this.props.language}/standalone`}><translate>Run Pulsar locally</translate></a> <translate>tutorial</translate>.
</p>
</div>
<p>
<translate>
If you need to connect to an existing Pulsar cluster or instance using an officially supported client,
see the client docs for these languages:
</translate>
</p>
<table className="clients">
<thead>
<tr>
<th><translate>Client guide</translate></th>
<th><translate>API docs</translate></th>
</tr>
</thead>
<tbody>
<tr key={'java'}>
<td><a href={`${siteConfig.baseUrl}docs/${this.props.language}/client-libraries-java`}><translate>The Pulsar java client</translate></a></td>
<td><translate>The Pulsar java client</translate></td>
</tr>
<tr key={'go'}>
<td><a href={`${siteConfig.baseUrl}docs/${this.props.language}/client-libraries-go`}><translate>The Pulsar go client</translate></a></td>
<td><translate>The Pulsar go client</translate></td>
</tr>
<tr key={'python'}>
<td><a href={`${siteConfig.baseUrl}docs/${this.props.language}/client-libraries-python`}><translate>The Pulsar python client</translate></a></td>
<td><translate>The Pulsar python client</translate></td>
</tr>
<tr key={'cpp'}>
<td><a href={`${siteConfig.baseUrl}docs/${this.props.language}/client-libraries-cpp`}><translate>The Pulsar C++ client</translate></a></td>
<td><translate>The Pulsar C++ client</translate></td>
</tr>
</tbody>
</table>
<h2 id="archive"><translate>Older releases</translate></h2>
<table className="versions">
<thead>
<tr>
<th><translate>Release</translate></th>
<th><translate>Binary</translate></th>
<th><translate>Source</translate></th>
<th><translate>Release notes</translate></th>
</tr>
</thead>
<tbody>
{releaseInfo.map(
info =>
info.version !== latestVersion && (
<tr key={info.version}>
<th>{info.version}</th>
<td>
<a href={info.binArchiveUrl}>apache-pulsar-{info.version}-bin-tar.gz</a>
(<a href={`${info.binArchiveUrl}.asc`}>asc</a>,
<a href={`${info.binArchiveUrl}.sha512`}>sha512</a>)
</td>
<td>
<a href={info.srcArchiveUrl}>apache-pulsar-{info.version}-bin-tar.gz</a>
(<a href={`${info.srcArchiveUrl}.asc`}>asc</a>
<a href={`${info.srcArchiveUrl}.sha512`}>sha512</a>)
</td>
<td>
<a href={`${siteConfig.baseUrl}${this.props.language}/release-notes#${info.version}`}><translate>Release Notes</translate></a>
</td>
</tr>
)
)}
</tbody>
</table>
</div>
</Container>
</div>
);
}
}
module.exports = Download;
| 43.920635 | 166 | 0.519937 |
6fd3af93eca64eb2ec6344ac5772a1199af3b4b3 | 10,801 | js | JavaScript | include/javascripts/cb_base.js | dixy/Connectix-Boards | 7a4206754765276d2de12a0e03fd0757fbc8782e | [
"Unlicense"
] | 1 | 2015-08-20T17:45:01.000Z | 2015-08-20T17:45:01.000Z | include/javascripts/cb_base.js | dixy/Connectix-Boards | 7a4206754765276d2de12a0e03fd0757fbc8782e | [
"Unlicense"
] | 2 | 2019-12-21T21:03:09.000Z | 2019-12-21T21:10:49.000Z | include/javascripts/cb_base.js | dixy/Connectix-Boards | 7a4206754765276d2de12a0e03fd0757fbc8782e | [
"Unlicense"
] | null | null | null | /**
* Connectix Boards 1.0, free interactive php bulletin boards.
* Copyright (C) 2005-2010 Jasienski Martin.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You can find a copy of the GNU General Public License at
* <http://www.connectix-boards.org/license.txt>.
*/
var cb_stylecookiename = "cb_style";
var cb_hiddenfidscookiename = "cb_hidfids";
var Mozilla = (navigator.userAgent.toLowerCase().indexOf('gecko')!=-1) ? true : false;
/* LECTURE ET ECRITURE DE COOKIES */
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
} else expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name,tag) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length,c.length);
}
return null;
}
/* AJOUT DE FONCTIONS DE SUPPRESSION ET DE VERIFICATION D'APPARTENANCE A LA CLASSE ARRAY */
Array.prototype.remove = function(s){
for (i=0;i<this.length;i++){
if(s==this[i]) this.splice(i, 1);
}
}
Array.prototype.inArray = function(s){
for (i=0;i<this.length;i++){
if (s==this[i]) return true;
}
return false;
}
/* POUR RECUPERER TOUS LES ELEMENTS D'UNE MEME CLASSE CSS */
document.getElementsByClassName = function(cl) {
var retnode = [];
var elem = this.getElementsByTagName('*');
for (var i = 0; i < elem.length; i++) {
if (elem[i].className == cl) retnode.push(elem[i]);
}
return retnode;
};
document.getElementsByClassFormat = function(cl) {
var retnode = [];
var elem = this.getElementsByTagName('*');
var match = new RegExp(cl,'g');
for (var i = 0; i < elem.length; i++) {
if (match.test(elem[i].className)) retnode.push(elem[i]);
}
return retnode;
};
/* POUR INSERER UN NOEUD APRES UN AUTRE NOEUD */
function insertAfter (node, refNode) {
if (refNode.parentNode.lastChild == refNode)
refNode.parentNode.appendChild(node);
else
refNode.parentNode.insertBefore(node,refNode.nextSibling);
}
/* FONCTION POUR MONTRER OU CACHER DES ELEMENTS (par id) */
function hideAndShow(field) {
var elem = document.getElementById(field);
elem.style.display = (elem.style.display == 'none') ? '' : 'none';
}
/* FONCTION POUR MONTRER OU CACHER DES ELEMENTS (par class) */
function hideAndShowC(field) {
var class_elems = document.getElementsByClassName(field);
for (var i=0; i<class_elems.length; i++)
class_elems[i].style.display = (class_elems[i].style.display == 'none') ? '' : 'none';
}
/* FONCTIONS POUR AFFICHER OU CACHER DES FORUMS (avec mémoire par cookies) */
var hiddenfids = (hiddencookie = readCookie(cb_hiddenfidscookiename)) ? hiddencookie.split(',') : new Array();
function hideAndShowF(fid) {
hideAndShow('forum'+fid+'_tb');
hideAndShow('forum'+fid+'_th');
hideAndShow('forum'+fid+'_tf');
var state = document.getElementById('forum'+fid+'_tb').style.display;
if (state == 'none') hiddenfids.push(fid);
else hiddenfids.remove(fid);
}
function checkF (fid) {
if (hiddenfids.inArray(fid)) {
hideAndShow('forum'+fid+'_tb');
hideAndShow('forum'+fid+'_th');
hideAndShow('forum'+fid+'_tf');
}
}
/* FONCTION DE CONFIRMATION AUTOMATIQUE DE FORMULAIRE */
function fast_list (select_goal) {
if (select_goal == 'showtopicgroup') {
box = document.getElementById('showtopicgroup');
location.href = document.getElementById('quick_redirect_form').action+'?showtopicgroup='+box.options[box.selectedIndex].value;
} else if (select_goal == 'mod_disp') {
document.getElementById('tg_displace').click();
} else if (select_goal == 'skin') {
document.getElementById('skin_select_submit').click();
}
}
/* FONCTION QUI SELECTIONNE TOUT LE CONTENU D'UN CHAMP */
function selectAll (field) {
field.focus();
if (Mozilla) {
field.setSelectionRange(0,field.value.length);
} else if (document.selection) {
var range = document.selection.createRange();
range.moveStart('character',-range.offsetLeft);
range.moveEnd('character',field.value.length);
range.select();
}
field.focus();
}
/* FONCTION ADMIN POUR LA SELECTION DES DROITS DES GROUPES */
function authfunc ( type , tgid ) {
if (document.getElementById(type+'_'+tgid).checked) {
if (type == 'see' || type=='reply') document.getElementById('create_'+tgid).checked = true;
if (type == 'see') document.getElementById('reply_'+tgid).checked = true;
} else {
if (type == 'create' || type=='reply') document.getElementById('see_'+tgid).checked = false;
if (type == 'create') document.getElementById('reply_'+tgid).checked = false;
}
}
/* FONCTIONS ADMIN POUR LA GESTION DES DROITS DE MODERATION */
function groupCl (grid,tgid) {
var newstate = (document.getElementById("gr" + tgid + "-" + grid).checked) ? true : false;
var checkbox = document.getElementsByClassName("u" + tgid + "-" + grid);
for (var i=0; i<checkbox.length; i++) checkbox[i].checked = newstate;
setColors(grid,tgid,newstate);
}
function userCl (uid,grid,tgid) {
if (!document.getElementById("u" + tgid + "-" + grid + "-" + uid).checked) {
document.getElementById("gr" + tgid + "-" + grid).checked = false;
setColors(grid,tgid,false);
}
}
function setColors (grid,tgid,checked) {
document.getElementById("cr" + tgid + "-" + grid).className = (checked)?'modgroupch':'modgroup';
var checkbox = document.getElementsByClassName("u" + tgid + "-" + grid);
for (var i=0; i<checkbox.length; i++) {
document.getElementById(checkbox[i].id.replace('u','c')).className = (checked)?'modusergr':'';
}
}
/* INVERSE LA SELECTION POUR UN TABLEAU DE CHECKBOX */
function invertselection (field) {
var checkbox = document.getElementsByName(field);
for (var i=0; i<checkbox.length;i++) {
if (checkbox[i].type == 'checkbox') {
checkbox[i].checked = (checkbox[i].checked) ? false : true;
}
}
}
/* MESSAGE D'AVERTISSEMENT PERSONNALISE */
var alertOpened = false;
function cbAlert (fmessage,finput) {
if (alertOpened) removeAlert();
var cbalert = document.createElement('div');
cbalert.id = 'cbalert';
cbalert.innerHTML =
'<form onsubmit="return false;">'+
'<p id="alert_message">'+fmessage+'</p>'+
(finput?'<p id="alert_input"><input type="text" id="alert_field" name="alert_field" value="'+finput+'" onkeyup="if(event.keyCode==13) removeAlert();" /></p>':'')+
'<p id="alert_submit">'+
'<input type="button" name="prompt_ok" id="prompt_ok" value="'+lang['ok']+'" onclick="removeAlert();" onkeyup="if(event.keyCode==13) removeAlert();" />'+
'</p>'+
'</form>';
document.getElementsByTagName('body')[0].appendChild(cbalert);
cbalert.focus();
document.getElementById('prompt_ok').focus();
if (finput)
selectAll(document.getElementById('alert_field'));
alertOpened = true;
}
function removeAlert() {
var cbalert = document.getElementById('cbalert');
cbalert.style.display = "none";
cbalert.innerHTML = "";
cbalert.id = null;
cbalert = null;
alertOpened = false;
}
/* GESTION DU STYLESWITCHER */
function setActiveStyleSheet(title) {
var i, a, main;
for (i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if (a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title"))
a.disabled = (a.getAttribute("title") == title) ? false : true;
}
}
function getActiveStyleSheet() {
var i, a;
for (i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if (a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled)
return a.getAttribute("title");
}
return null;
}
function getPreferredStyleSheet() {
var i, a;
for (i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if (a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("rel").indexOf("alt") == -1 && a.getAttribute("title"))
return a.getAttribute("title");
}
return null;
}
/* FONCTIONS POUR LE FORMULAIRE DE CONNEXION RAPIDE */
var fc_username_clicked = false;
var fc_password_clicked = false;
function fc_username () {
if (!fc_username_clicked) {
document.getElementById("fcf_login").value = "";
fc_username_clicked = true;
}
}
function fc_password () {
if (!fc_password_clicked) {
document.getElementById("fcf_password").value = "";
fc_password_clicked = true;
}
}
/* CHOSES A FAIRE AU CHARGEMENT DE LA PAGE */
window.onload = function (e) {
var stylecookie = readCookie(cb_stylecookiename);
var size = document.getElementsByTagName("link").length;
var title = getPreferredStyleSheet();
for (j=0; j<size ; j++) {
if (document.getElementsByTagName("link")[j].getAttribute("title") == stylecookie)
title = stylecookie;
}
initAnchors();
if (Mozilla) setActiveStyleSheet(title);
}
/* CHOSES A FAIRE AU DECHARGEMENT DE LA PAGE */
window.onunload = function (e) {
createCookie(cb_stylecookiename, getActiveStyleSheet(), 365);
createCookie(cb_hiddenfidscookiename, hiddenfids.join(','), 365);
}
/* FONCTIONS D'ENCODAGE */
function utf8_encode ( argString ) {
// Encodes an ISO-8859-1 string to UTF-8
//
// version: 909.322
// discuss at: http://phpjs.org/functions/utf8_encode
// + original by: Webtoolkit.info (http://www.webtoolkit.info/)
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: sowberry
// + tweaked by: Jack
// + bugfixed by: Onno Marsman
// + improved by: Yves Sucaet
// + bugfixed by: Onno Marsman
// + bugfixed by: Ulrich
// * example 1: utf8_encode('Kevin van Zonneveld');
// * returns 1: 'Kevin van Zonneveld'
var string = (argString+''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");
var utftext = "";
var start, end;
var stringl = 0;
start = end = 0;
stringl = string.length;
for (var n = 0; n < stringl; n++) {
var c1 = string.charCodeAt(n);
var enc = null;
if (c1 < 128) {
end++;
} else if (c1 > 127 && c1 < 2048) {
enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
} else {
enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
}
if (enc !== null) {
if (end > start) {
utftext += string.substring(start, end);
}
utftext += enc;
start = end = n+1;
}
}
if (end > start) {
utftext += string.substring(start, string.length);
}
return utftext;
}
| 32.730303 | 164 | 0.676789 |
6fd4ad00722cc887de4575ca9e05404dca3cecd1 | 160 | js | JavaScript | db/models/Player.js | JasenABaker/Dungeon_Master | 46be6686c611c6deccd8a3331718dcc77c7f6ff5 | [
"CC-BY-3.0"
] | null | null | null | db/models/Player.js | JasenABaker/Dungeon_Master | 46be6686c611c6deccd8a3331718dcc77c7f6ff5 | [
"CC-BY-3.0"
] | null | null | null | db/models/Player.js | JasenABaker/Dungeon_Master | 46be6686c611c6deccd8a3331718dcc77c7f6ff5 | [
"CC-BY-3.0"
] | null | null | null | const mongoose = require('mongoose')
const Schema = require('../schema')
const Player = mongoose.model('Player', Schema.PlayerSchema)
module.exports = Player | 22.857143 | 60 | 0.74375 |
6fd4ef40c5cbfb82e308e128671d9a075bcae225 | 2,734 | js | JavaScript | ionic/www/js/controllers/client/checkout.js | juliofiuza/code-delivery | 31040d276037caef7c20280e9639ba653aca3add | [
"MIT"
] | null | null | null | ionic/www/js/controllers/client/checkout.js | juliofiuza/code-delivery | 31040d276037caef7c20280e9639ba653aca3add | [
"MIT"
] | null | null | null | ionic/www/js/controllers/client/checkout.js | juliofiuza/code-delivery | 31040d276037caef7c20280e9639ba653aca3add | [
"MIT"
] | null | null | null | angular.module('code-delivery.controllers')
.controller('ClientCheckoutCtrl', [
'$scope', '$state', '$ionicLoading', '$ionicPopup', '$cordovaBarcodeScanner', '$cart', 'ClientOrder', 'Cupom',
function($scope, $state, $ionicLoading, $ionicPopup, $cordovaBarcodeScanner, $cart, ClientOrder, Cupom) {
var cart = $cart.get();
$scope.cupom = cart.cupom;
$scope.items = cart.items;
$scope.total = $cart.getTotalFinal();
//$scope.showDelete = false;
$scope.removeItem = function(i) {
$cart.removeItem(i);
$scope.items.splice(i, 1);
$scope.total = $cart.getTotalFinal();
};
$scope.openListProducts = function() {
$state.go('client.view_products');
};
$scope.openProductDetail = function(i) {
$state.go('client.checkout_item_detail', { index: i });
};
$scope.save = function() {
var o = {items: angular.copy($scope.items)};
angular.forEach(o.items, function(item) {
item.product_id = item.id;
});
if ($scope.cupom.value) {
o.cupom_code = $scope.cupom.code;
}
$ionicLoading.show({
template: 'Carregando...'
});
ClientOrder.save({ id: null }, o, function(data) {
$ionicLoading.hide();
$state.go('client.checkout_successful');
}, function(error) {
$ionicLoading.hide();
$ionicPopup.alert({
title: 'Advertência',
template: 'Pedido não realizado. Tente novamente.',
buttons: [
{
text: 'Ok',
type: 'button-balanced'
}
]
});
});
};
$scope.readBarCode = function() {
$cordovaBarcodeScanner.scan().then(function(barcodeData) {
getValueCupom(barcodeData.text);
}, function(error) {
$ionicPopup.alert({
title: 'Advertência',
template: 'Não foi possível ler código de barras. Tente novamente.',
buttons: [
{
text: 'Ok',
type: 'button-balanced'
}
]
});
});
};
$scope.removeCupom = function() {
$cart.removeCupom();
$scope.cupom = $cart.get().cupom;
$scope.total = $cart.getTotalFinal();
};
var getValueCupom = function(code) {
$ionicLoading.show({
template: 'Carregando...'
});
Cupom.get({code: code}, function(data) {
$cart.setCupom(data.data.code, data.data.value);
$scope.cupom = $cart.get().cupom;
$scope.total = $cart.getTotalFinal();
$ionicLoading.hide();
}, function(error) {
$ionicLoading.hide();
console.log(error);
$ionicPopup.alert({
title: 'Advertência',
template: 'Cupom inválido',
buttons: [
{
text: 'Ok',
type: 'button-balanced'
}
]
});
});
};
}]); | 25.551402 | 111 | 0.566569 |
6fd511c93b705c2cdc81b56b7ca9b930ba4e8537 | 5,883 | js | JavaScript | src/main/docs/html/search/all_13.js | Team302/Training2020 | 144cb24e5674c857c45fe4544ab42f27e07371f9 | [
"MIT"
] | 1 | 2020-09-03T21:28:43.000Z | 2020-09-03T21:28:43.000Z | src/main/docs/html/search/all_13.js | Team302/training2020 | 144cb24e5674c857c45fe4544ab42f27e07371f9 | [
"MIT"
] | null | null | null | src/main/docs/html/search/all_13.js | Team302/training2020 | 144cb24e5674c857c45fe4544ab42f27e07371f9 | [
"MIT"
] | null | null | null | var searchData=
[
['ultrasonicfactory_1106',['UltrasonicFactory',['../class_ultrasonic_factory.html',1,'']]],
['ultrasonicfactory_2ecpp_1107',['UltrasonicFactory.cpp',['../_ultrasonic_factory_8cpp.html',1,'']]],
['ultrasonicfactory_2eh_1108',['UltrasonicFactory.h',['../_ultrasonic_factory_8h.html',1,'']]],
['undefined_5faxis_1109',['UNDEFINED_AXIS',['../class_i_dragon_game_pad.html#a6ba0408b15301dd149474ebad9b4972bac4b73cf2814ada0f668d675161b714c9',1,'IDragonGamePad']]],
['undefined_5fbutton_1110',['UNDEFINED_BUTTON',['../class_i_dragon_game_pad.html#a07a7fc32b5cb69f2019006c0eb0f7d29a686bc2a101683a20a3596914ac8ae4f4',1,'IDragonGamePad']]],
['under_5fback_1111',['UNDER_BACK',['../class_l_e_d_factory.html#ad0f7083a5e2d6ee688b17a91a6e50992adbaa16ecbf586a6febe089fe1bc8218d',1,'LEDFactory']]],
['under_5ffront_1112',['UNDER_FRONT',['../class_l_e_d_factory.html#ad0f7083a5e2d6ee688b17a91a6e50992aad1e7fe3fc0d9d586a8477d0c02ea0c3',1,'LEDFactory']]],
['unjam_5fclockwise_1113',['UNJAM_CLOCKWISE',['../class_teleop_control.html#a7d4c2a365d8eaf21214611064c8a3a15a6ab7626ea66fb2bed3dc84e9c07356c6',1,'TeleopControl::UNJAM_CLOCKWISE()'],['../class_ball_manipulator.html#a91bf71119c5fecb46b41a90485f7a9a4ab71df697d611ab99469889666c8175dc',1,'BallManipulator::UNJAM_CLOCKWISE()']]],
['unjam_5fcounterclockwise_1114',['UNJAM_COUNTERCLOCKWISE',['../class_teleop_control.html#a7d4c2a365d8eaf21214611064c8a3a15ad857b31c41423f3bd5c2875b4644ef60',1,'TeleopControl::UNJAM_COUNTERCLOCKWISE()'],['../class_ball_manipulator.html#a91bf71119c5fecb46b41a90485f7a9a4a7f6b7e8dfed0b9ca0cf7ad84663c4d60',1,'BallManipulator::UNJAM_COUNTERCLOCKWISE()']]],
['unknown_1115',['UNKNOWN',['../class_control_panel_colors.html#a4137011ea714732b2ba0c01b9c3f70eba923f7a4d7f27a304d643fe8dc2b18b31',1,'ControlPanelColors']]],
['unknown_5fanalog_5ftype_1116',['UNKNOWN_ANALOG_TYPE',['../class_analog_input_usage.html#a0a2b8dec47d570e3e015c1cf4b43dc3eadd180056c5da0e5191d4b1dc044e3e5d',1,'AnalogInputUsage']]],
['unknown_5fchassis_1117',['UNKNOWN_CHASSIS',['../class_chassis_factory.html#ac7a9d3e5c5b09915503114b2112702d4a04e2984c2ce584cae7f95f2847037199',1,'ChassisFactory']]],
['unknown_5fdigital_5ftype_1118',['UNKNOWN_DIGITAL_TYPE',['../class_digital_input_usage.html#a2137e04f1b7fa23da836b516e8365f46a46222776748611fa1cf0a23bb2754712',1,'DigitalInputUsage']]],
['unknown_5ffield_1119',['UNKNOWN_FIELD',['../class_field_measurement.html#a6a6007ff2b3a4208d6db0ed75b035142af5ec37abeabb6b77f710e154a6cc9956',1,'FieldMeasurement']]],
['unknown_5ffunction_1120',['UNKNOWN_FUNCTION',['../class_teleop_control.html#a7d4c2a365d8eaf21214611064c8a3a15a6f54ea506603240492346116d310c09e',1,'TeleopControl']]],
['unknown_5fmechanism_1121',['UNKNOWN_MECHANISM',['../class_mechanism_types.html#adad17689ea795c3d65e2062bdc09284baf47163443d641a45c8ec02e3af24e0de',1,'MechanismTypes']]],
['unknown_5fmotor_5fcontroller_5fusage_1122',['UNKNOWN_MOTOR_CONTROLLER_USAGE',['../class_motor_controller_usage.html#a03b7ee94f8c7e42884d5da8974e3a51aa88dc96bc07f2a3d51e868dc1d8a35ffe',1,'MotorControllerUsage']]],
['unknown_5fpixel_5fformat_1123',['UNKNOWN_PIXEL_FORMAT',['../class_camera_defn.html#ae29ffe10b5b70b63317bbb86366d7be4afaf34eb85e7d84088421a1df36137b1b',1,'CameraDefn']]],
['unknown_5fprimitive_1124',['UNKNOWN_PRIMITIVE',['../_primitive_enums_8h.html#a35fa04dbcd6e8ebd76550c9b14ade0dca44a63c3b48a5e29e57af1ba4893c8678',1,'PrimitiveEnums.h']]],
['unknown_5fsensor_1125',['UNKNOWN_SENSOR',['../class_i_dragon_sensor.html#a48f04b4f71b0f27f8330fd82a26b5fe9aa96ab0d2414159647879dfb522c7415d',1,'IDragonSensor']]],
['unknown_5fservo_5fusage_1126',['UNKNOWN_SERVO_USAGE',['../class_servo_usage.html#a77ece7abcaf45a9b3b4d717f9503b5aaa290e28c686b2c6a85ba42f4c9fe26356',1,'ServoUsage']]],
['unknown_5fsolenoid_5fusage_1127',['UNKNOWN_SOLENOID_USAGE',['../class_solenoid_usage.html#adb45b3112fbc67f57d39931571b60ef7aa59fb8d304066c670bcd91d75f348818',1,'SolenoidUsage']]],
['unknown_5ftalon_5ftach_5fusage_1128',['UNKNOWN_TALON_TACH_USAGE',['../class_dragon_talon_tach.html#a7b73df3604a85825e59645be8f8e19faab3e47194d8faaf2cb7b8a2c7d98ed21c',1,'DragonTalonTach']]],
['up_1129',['UP',['../class_hook_delivery_state_mgr.html#a1db52ff9a2c43a81d323dd3ae9a88223a4b30167cff2f6e856ed4d147bc1075c3',1,'HookDeliveryStateMgr']]],
['update_1130',['Update',['../class_mechanism_target_data.html#aba4da6ec1b211b2f3d788cd6096502e3',1,'MechanismTargetData::Update()'],['../class_i_mech1_ind_motor.html#ac2a4fc46e37505f96054a02496e5b5c1',1,'IMech1IndMotor::Update()'],['../class_i_mech2_ind_motors.html#a1da8a8c5acef53aece885e984431ee3b',1,'IMech2IndMotors::Update()'],['../class_mech1_ind_motor.html#a55626a8ad6f24b69b6472465fbcda416',1,'Mech1IndMotor::Update()'],['../class_mech2_ind_motors.html#ad459458d7d1912216d61fa0cb29538db',1,'Mech2IndMotors::Update()']]],
['updatetarget_1131',['UpdateTarget',['../class_limelight_aim.html#ab80516598f3bea2c227ede5cd1c83fbb',1,'LimelightAim::UpdateTarget()'],['../class_i_mech1_ind_motor.html#a730d0d96efa4a272289934178aa4146f',1,'IMech1IndMotor::UpdateTarget()'],['../class_mech1_ind_motor.html#a999fd41ccd8773e87018d5e6ac849e84',1,'Mech1IndMotor::UpdateTarget()']]],
['updatetargets_1132',['UpdateTargets',['../class_i_mech2_ind_motors.html#a37a3fe93fa4ca711bb96a97100bc0187',1,'IMech2IndMotors::UpdateTargets()'],['../class_mech2_ind_motors.html#a25c34ffd7866a584800e01e85fc0f22c',1,'Mech2IndMotors::UpdateTargets()']]],
['usagevalidation_1133',['UsageValidation',['../class_usage_validation.html',1,'UsageValidation'],['../class_usage_validation.html#acdc3efa3750c4938083c0fd1525285e8',1,'UsageValidation::UsageValidation()']]],
['usagevalidation_2ecpp_1134',['UsageValidation.cpp',['../_usage_validation_8cpp.html',1,'']]],
['usagevalidation_2eh_1135',['UsageValidation.h',['../_usage_validation_8h.html',1,'']]]
];
| 173.029412 | 532 | 0.82169 |
6fd688f29f2d1536f79b0829745fa42bae58f48b | 6,246 | js | JavaScript | test/api/routes/createUser.test.js | eglouberman/friendbank | a44113cfb8befa553ab3d90bdbdc6668fff5cd27 | [
"MIT"
] | null | null | null | test/api/routes/createUser.test.js | eglouberman/friendbank | a44113cfb8befa553ab3d90bdbdc6668fff5cd27 | [
"MIT"
] | null | null | null | test/api/routes/createUser.test.js | eglouberman/friendbank | a44113cfb8befa553ab3d90bdbdc6668fff5cd27 | [
"MIT"
] | null | null | null | const fetch = require('node-fetch');
const chai = require('chai');
const { MongoClient } = require('mongodb');
const { API_URL, MONGODB_URL } = process.env;
// Reference: https://www.chaijs.com/api/assert/
const assert = chai.assert;
require('./_setup');
const {
standardTestSetup,
fakeUser,
} = require('./_faker');
describe('createUser api route v1', function() {
it('should create a new user', async function() {
const standard = await standardTestSetup();
const response = await fetch(`${API_URL}/api/v1/user`, {
method: 'post',
body: JSON.stringify({
email: 'test@marquitabradshaw.com',
password: 'password',
firstName: 'Test',
zip: '00000',
emailFrequency: 'WEEKLY_EMAIL',
}),
headers: {
'Content-Type': 'application/json',
},
});
assert.equal(response.status, 200);
const { token } = await response.json();
assert.isString(token);
assert.lengthOf(token, 128);
const client = await MongoClient.connect(MONGODB_URL, { useUnifiedTopology: true });
const users = client.db().collection('users');
const record = await users.findOne({
email: 'test@marquitabradshaw.com',
});
assert.equal(record.firstName, 'Test');
assert.equal(record.zip, '00000');
assert.equal(record.emailFrequency, 'WEEKLY_EMAIL');
assert.notEqual(record.password, 'password');
assert.equal(record.campaign, standard.campaign._id.toString());
});
it('should create a new user and normalize the email', async function() {
const standard = await standardTestSetup();
const response = await fetch(`${API_URL}/api/v1/user`, {
method: 'post',
body: JSON.stringify({
email: 'TEST@marquitabradshaw.COM',
password: 'password',
firstName: 'Test',
zip: '00000',
emailFrequency: 'WEEKLY_EMAIL',
}),
headers: {
'Content-Type': 'application/json',
},
});
assert.equal(response.status, 200);
const client = await MongoClient.connect(MONGODB_URL, { useUnifiedTopology: true });
const users = client.db().collection('users');
const record = await users.findOne({
email: 'test@marquitabradshaw.com',
});
assert.isOk(record._id);
});
it('should not create a new user if the email is already in use', async function() {
const standard = await standardTestSetup();
const response = await fetch(`${API_URL}/api/v1/user`, {
method: 'post',
body: JSON.stringify({
email: 'marquita@marquitabradshaw.com',
password: 'password',
firstName: 'Test',
zip: '00000',
emailFrequency: 'WEEKLY_EMAIL',
}),
headers: {
'Content-Type': 'application/json',
},
});
assert.equal(response.status, 409);
const { error } = await response.json();
assert.equal(error, 'validations.existingUser');
});
it('should not create a new user if the first name field fails validation', async function() {
const standard = await standardTestSetup();
const response = await fetch(`${API_URL}/api/v1/user`, {
method: 'post',
body: JSON.stringify({
email: 'test@marquitabradshaw.com',
password: 'password',
zip: '00000',
emailFrequency: 'WEEKLY_EMAIL',
}),
headers: {
'Content-Type': 'application/json',
},
});
assert.equal(response.status, 400);
const { field, error } = await response.json();
assert.equal(field, 'firstName');
assert.equal(error, 'validations.required');
});
it('should not create a new user if the email field fails validation', async function() {
const standard = await standardTestSetup();
const response = await fetch(`${API_URL}/api/v1/user`, {
method: 'post',
body: JSON.stringify({
password: 'password',
firstName: 'Test',
zip: '00000',
emailFrequency: 'WEEKLY_EMAIL',
}),
headers: {
'Content-Type': 'application/json',
},
});
assert.equal(response.status, 400);
const { field, error } = await response.json();
assert.equal(field, 'email');
assert.equal(error, 'validations.required');
});
it('should not create a new user if the password field fails validation', async function() {
const standard = await standardTestSetup();
const response = await fetch(`${API_URL}/api/v1/user`, {
method: 'post',
body: JSON.stringify({
email: 'test@marquitabradshaw.com',
firstName: 'Test',
zip: '00000',
emailFrequency: 'WEEKLY_EMAIL',
}),
headers: {
'Content-Type': 'application/json',
},
});
assert.equal(response.status, 400);
const { field, error } = await response.json();
assert.equal(field, 'password');
assert.equal(error, 'validations.required');
});
it('should not create a new user if the zip field fails validation', async function() {
const standard = await standardTestSetup();
const response = await fetch(`${API_URL}/api/v1/user`, {
method: 'post',
body: JSON.stringify({
email: 'test@marquitabradshaw.com',
password: 'password',
firstName: 'Test',
emailFrequency: 'WEEKLY_EMAIL',
}),
headers: {
'Content-Type': 'application/json',
},
});
assert.equal(response.status, 400);
const { field, error } = await response.json();
assert.equal(field, 'zip');
assert.equal(error, 'validations.required');
});
it('should not create a new user if the emailFrequency field fails validation', async function() {
const standard = await standardTestSetup();
const response = await fetch(`${API_URL}/api/v1/user`, {
method: 'post',
body: JSON.stringify({
email: 'test@marquitabradshaw.com',
password: 'password',
firstName: 'Test',
zip: '00000',
}),
headers: {
'Content-Type': 'application/json',
},
});
assert.equal(response.status, 400);
const { field, error } = await response.json();
assert.equal(field, 'emailFrequency');
assert.equal(error, 'validations.required');
});
});
| 28.008969 | 100 | 0.60919 |
6fd6f4063bdacad84daa8ffcd0fb73277f08520f | 319 | js | JavaScript | examples/your-first-app/fac.js | Swizec/modernapp-workshop | dd2064c00d8cd1d4a050d28ebc6d1dc9845525b0 | [
"MIT"
] | 1 | 2019-05-19T20:37:40.000Z | 2019-05-19T20:37:40.000Z | examples/your-first-app/fac.js | Swizec/modernapp-workshop | dd2064c00d8cd1d4a050d28ebc6d1dc9845525b0 | [
"MIT"
] | 26 | 2020-12-31T07:41:18.000Z | 2022-03-08T23:33:36.000Z | examples/your-first-app/fac.js | Swizec/modernapp-workshop | dd2064c00d8cd1d4a050d28ebc6d1dc9845525b0 | [
"MIT"
] | 1 | 2020-06-18T19:16:45.000Z | 2020-06-18T19:16:45.000Z | const Fac = ({ children }) => (
<div>
<h1>One</h1>
{children({ number: 1 })}
</div>
)
const PrettyNumber = () => (
<Fac>
{({ number }) => (
<span style={{ color: '#E52B50', fontSize: '2em' }}>{number}</span>
)}
</Fac>
)
ReactDOM.render(<PrettyNumber />, document.getElementById('root'))
| 18.764706 | 73 | 0.520376 |
6fd72efc0cd6e3393af22e60e248a1d50e47c6d2 | 292 | js | JavaScript | docroot/modules/custom/bos_components/modules/bos_web_app/apps/metrolist/src/components/Callout/_CalloutCta/CalloutCta.test.js | CityOfBoston/boston.gov-d8 | 56f116ed4c354692605d83d7d2db6a1204f62c84 | [
"CC0-1.0"
] | 21 | 2018-06-20T01:17:15.000Z | 2021-12-18T05:26:21.000Z | docroot/modules/custom/bos_components/modules/bos_web_app/apps/metrolist/src/components/Callout/_CalloutCta/CalloutCta.test.js | TMfranken/boston.gov-d8 | 1422cbe6532ad3d550e52555ea897479cfe1120e | [
"CC0-1.0"
] | 1,309 | 2018-07-23T13:55:32.000Z | 2022-03-30T13:47:12.000Z | docroot/modules/custom/bos_components/modules/bos_web_app/apps/metrolist/src/components/Callout/_CalloutCta/CalloutCta.test.js | TMfranken/boston.gov-d8 | 1422cbe6532ad3d550e52555ea897479cfe1120e | [
"CC0-1.0"
] | 15 | 2018-06-20T01:17:19.000Z | 2021-07-21T19:17:48.000Z | import '__mocks__/matchMedia';
import React from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import CalloutCta from './index';
describe( 'CalloutCta', () => {
it( 'Renders', () => {
render( <CalloutCta /> );
} );
} );
| 22.461538 | 49 | 0.640411 |
6fd7ba68e73ba5a9eaa8d7e0e3d16fd296b46dbb | 2,170 | js | JavaScript | exercises/237-caesar-cipher.js | piasoy/js201 | c2d2d8850a6a4d21a589108b0159a626924ba858 | [
"ISC"
] | null | null | null | exercises/237-caesar-cipher.js | piasoy/js201 | c2d2d8850a6a4d21a589108b0159a626924ba858 | [
"ISC"
] | null | null | null | exercises/237-caesar-cipher.js | piasoy/js201 | c2d2d8850a6a4d21a589108b0159a626924ba858 | [
"ISC"
] | null | null | null | // Write a function "cipher" which is given a string, a shift, and returns
// the Caesar cipher of the string.
// Caesar cipher --> http://practicalcryptography.com/ciphers/caesar-cipher/
//
// Examples:
// > cipher('Genius without education is like silver in the mine', 5)
// 'ljsnzx bnymtzy jizhfynts nx qnpj xnqajw ns ymj rnsj'
// > cipher('We hold these truths to be self-evident', 8)
// 'em pwtl bpmam bzcbpa bw jm amtn-mdqlmvb'
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Write a function "decipher" which is given a string, a shift, and returns the
// decoded Caesar cipher message.
//
// Examples:
// > decipher('cvvcem cv fcyp!', 2)
// 'attack at dawn!'
// > decipher('ehz czlod otgpcrpo ty l hzzo', 11)
// 'two roads diverged in a wood'
function decipher(str, shift){
let alphabetCode = {
a: 1,
b: 2,
c: 3, //3-11= -8, =>26 - (8+1)
d: 4, //4-11= -7 =>26 - (7+1)
e: 5, //5-11 = -6 =>26 - (6+1)
f: 6,
g: 7,
h: 8,
i: 9,
j: 10,
k: 11,
l: 12,
m: 13,
n: 14,
o: 15,
p: 16,
q: 17,
r: 18,
s: 19,
t: 20,
u: 21,
v: 22,
w: 23,
x: 24,
y: 25,
z: 26
}
for(let idx =0; idx < str.length; idx++){
let charPos = alphabetCode[str];
let cypherPos = charPos - shift;
let deciphered = '';
console.log (charPos)
console.log (cypherPos)
if (cypherPos === 0){
cypherPos = 26
}
else if (cypherPos < 0) {
cypherPos = 26 + (cypherPos - 1)
}
for (key in alphabetCode)
//console.log ('cypherPos: ', cypherPos, ' | ' ,'key: ', key, ' | ', 'key.cypherPos: ', alphabetCode[key])
if (alphabetCode[key] === cypherPos){
deciphered += this.key;
console.log(deciphered)
}console.log(deciphered)
return deciphered
}
//console.log(deciphered)
// return deciphered
}
decipher('he', 11) | 27.125 | 119 | 0.478341 |
6fd7cc6197f2816c00d6a785188b7aa19863a58c | 1,244 | js | JavaScript | modules/rules/tests/rules/StalemateTest.js | embarced/micro-moves | 90e3dba1d09a50b0f7df3f742a58a6e558bf1500 | [
"Apache-2.0"
] | 9 | 2018-09-30T09:14:55.000Z | 2020-09-06T08:01:29.000Z | modules/rules/tests/rules/StalemateTest.js | embarced/micro-moves | 90e3dba1d09a50b0f7df3f742a58a6e558bf1500 | [
"Apache-2.0"
] | 52 | 2019-06-15T17:50:12.000Z | 2021-08-01T04:16:01.000Z | modules/rules/tests/rules/StalemateTest.js | embarced/micro-moves | 90e3dba1d09a50b0f7df3f742a58a6e558bf1500 | [
"Apache-2.0"
] | 5 | 2018-04-26T14:34:04.000Z | 2020-06-03T12:16:33.000Z | const assert = require('assert');
const domain = require("../../domain.js");
const rules = require("../../rules.js");
const ChessRules = rules.ChessRules;
const Position = domain.Position;
const Colour = domain.Colour;
const boardGeometry = require("../../geometry.js");
const Square = boardGeometry.Square;
describe('ChessRules unit tests', () => {
describe('isStalemate', () => {
it('setup position (no stalemate)', () => {
const pos = new Position();
assert.ok(! ChessRules.isStalemate(pos));
});
it('Checkmate (no stalemate)', () => {
const pos = new Position('4k2R/8/4K3/8/8/8/8/8 b - - 0 1');
assert.ok(ChessRules.isCheckmate(pos));
assert.ok(! ChessRules.isStalemate(pos));
});
it('stalemate with king and pawn, black to move is in stalemate.', () => {
const pos = new Position('5k2/5P2/5K2/8/8/8/8/8 b - - 0 1');
assert.ok(ChessRules.isStalemate(pos));
});
it('stalemate with king and rook, white to move is in stalemate.', () => {
const pos = new Position('K7/1r6/2k5/8/8/8/8/8 w - - 0 1');
assert.ok(ChessRules.isStalemate(pos));
});
})
}); | 28.930233 | 82 | 0.561093 |
6fd813a6c8ea017f46c83f2afddd41b69cc93377 | 354 | js | JavaScript | client/plugins/axios.js | uiuxarghya/webcrate | 34beb5aaf65af1f418ea67f92f06ba8f7184979d | [
"MIT"
] | 271 | 2021-08-24T11:42:12.000Z | 2022-03-28T03:38:42.000Z | client/plugins/axios.js | uiuxarghya/webcrate | 34beb5aaf65af1f418ea67f92f06ba8f7184979d | [
"MIT"
] | 13 | 2021-08-24T12:04:33.000Z | 2022-01-11T16:38:15.000Z | client/plugins/axios.js | uiuxarghya/webcrate | 34beb5aaf65af1f418ea67f92f06ba8f7184979d | [
"MIT"
] | 26 | 2021-08-25T06:28:00.000Z | 2022-03-30T10:31:21.000Z | export default function({ $axios, redirect }) {
$axios.onError((error) => {
const loginUrl = process.client ? `https://deta.space/auth?redirect_uri=${ window.location.toString() }` : `https://deta.space/library?open=webcrate`
const code = parseInt(error.response && error.response.status)
if (code === 403) {
return redirect(loginUrl)
}
})
} | 39.333333 | 151 | 0.683616 |
6fd91b47ebcbaec503c4a0089c498d2cb5b6eaad | 3,223 | js | JavaScript | src/app/utils/physics.js | Themis3000/drone_sim | 49dd8cb60a07b424f5df0a230605bff7feb3a68d | [
"MIT"
] | null | null | null | src/app/utils/physics.js | Themis3000/drone_sim | 49dd8cb60a07b424f5df0a230605bff7feb3a68d | [
"MIT"
] | null | null | null | src/app/utils/physics.js | Themis3000/drone_sim | 49dd8cb60a07b424f5df0a230605bff7feb3a68d | [
"MIT"
] | null | null | null | export class Physics {
constructor(camera, getHidState, forcesScale) {
this.camera = camera;
this.getHidState = getHidState;
this.forcesScale = forcesScale;
this.motorPower = 4;
//max rotations per second in radians
this.rates = 3;
//added camera angle in degrees
this.camAngle = 14;
this.pitch = new Angle(0);
this.roll = new Angle(0);
this.yaw = new Angle(0);
}
set camAngle(angle) {
this.camAngleRad = angle * (Math.PI/180);
}
runPhysicsStep(frameTimeDelta) {
let hidState = this.getHidState();
//end function if gamepad is not detected
if (!hidState.online)
return
//translate throttle stick into force (feet per second)
let systemForce = hidState.throttle * (9.8*this.motorPower);
//translate pitch and roll stick into rotations
this.pitch.value += (this.rates * hidState.pitch)/1000 * frameTimeDelta;
this.roll.value += (this.rates * hidState.roll)/1000 * frameTimeDelta;
this.yaw.value += (this.rates * hidState.yaw)/1000 * frameTimeDelta;
//find amount of force in each axis
let angleFromPlane = Math.atan(Math.sqrt((Math.tan(this.pitch.value)**2) + (Math.tan(this.roll.value)**2)));
let yForce = ((1/(Math.PI/2))*Math.abs(angleFromPlane-Math.PI)-1)*systemForce;
let xzForce = systemForce - Math.abs(yForce);
let xForce = Math.abs(this.pitch.value)/(this.roll.value+this.pitch.value)*xzForce*Math.sign(this.pitch.value);
let zForce = (xzForce - Math.abs(xForce)) * Math.sign(this.pitch.value);
//adjust forces for yaw
//uc for unit circle
let ucAngle = Math.atan(xForce/zForce);
let ucHypotenuse = xForce/Math.sin(ucAngle);
let adjXForce = ucHypotenuse*Math.sin(ucAngle+this.yaw.value);
let adjZForce = ucHypotenuse*Math.cos(ucAngle+this.yaw.value);
//apply forces to camera
this.camera.position.y += Physics.calcMovement(yForce-9.8, frameTimeDelta);
if (adjXForce > 0)
this.camera.position.x += Physics.calcMovement(adjXForce, frameTimeDelta);
if (adjZForce > 0)
this.camera.position.z += Physics.calcMovement(adjZForce, frameTimeDelta);
//apply rotations to camera
this.camera.rotation.x = (this.pitch.value + this.camAngleRad);
this.camera.rotation.y = this.yaw.value;
this.camera.rotation.z = -this.roll.value;
}
//given an amount of force/second, this function returns the movement that force caused over an amount of time in ms
static calcMovement(force, time) {
return force/1000 * time;
}
}
class Angle {
constructor(rotation) {
this.rotation = rotation;
}
get value() {
return this.rotation;
}
set value(num) {
this.rotation = Angle.simplifyAngle(num);
}
//Simplifies an angle (in radians) to be the smallest number possible while still representing the same angle
//e.g. 3pi represents the same angle as pi, so this function would simplify 3pi down to pi
static simplifyAngle(angle) {
return angle % (2*Math.PI);
}
} | 39.790123 | 120 | 0.636984 |
6fd9c97e30ab6d26a98df78cdee6755fac510a65 | 1,684 | js | JavaScript | client/src/components/topbar.js | bjpreece/mercury | 7cd12420ab2ad6fb312b0959bed3558387f40c45 | [
"MIT"
] | 1 | 2018-06-19T16:04:39.000Z | 2018-06-19T16:04:39.000Z | client/src/components/topbar.js | bjpreece/mercury | 7cd12420ab2ad6fb312b0959bed3558387f40c45 | [
"MIT"
] | null | null | null | client/src/components/topbar.js | bjpreece/mercury | 7cd12420ab2ad6fb312b0959bed3558387f40c45 | [
"MIT"
] | 1 | 2018-08-06T10:33:41.000Z | 2018-08-06T10:33:41.000Z | import React from 'react'
import styled from 'styled-components'
import { NavLink } from 'react-router-dom'
import { colour, size } from '../style/theme'
import Halo from '../img/md-aperture.svg'
const TopBarGrid = styled.section`
display: grid;
grid-template-columns: 240px 1fr;
grid-template-rows: 1fr;
grid-column: 1 / 3;
background-color: ${colour.background};
`
const Logo = styled.div`
background-color: ${colour.backgrounddark};
color: ${colour.white};
display: grid;
grid-template-columns: 70px 1fr;
`
const HaloImage = styled.img`
width: 40px;
height: 40px;
margin-top: ${size.formpadding};
margin-left: ${size.grid};
`
const LogoText = styled.span`
line-height: 60px;
`
const Nav = styled.nav`
display: grid;
grid-template-columns: 100px 100px 100px 100px;
a.active {
background-color: ${colour.yellow};
color: ${colour.backgrounddark};
}
`
const NavItem = styled(NavLink)`
text-decoration: none;
color: ${colour.white};
line-height: 60px;
font-size: ${size.fontsmall};
text-align: center;
:hover {
background-color: ${colour.yellow};
color: ${colour.backgrounddark};
}
`
const TopBar = () =>
<TopBarGrid>
<Logo>
<HaloImage src={Halo} />
<LogoText>Halo</LogoText>
</Logo>
<Nav>
<NavItem to="/" exact>
Dashboard
</NavItem>
<NavItem to="/operations">
Operations
</NavItem>
<NavItem to="/exhibits">
Exhibits
</NavItem>
<NavItem to="/search">
Search
</NavItem>
</Nav>
</TopBarGrid>
export default TopBar | 20.289157 | 50 | 0.603325 |
6fda0332999eb143f0cd83be5e7620e84e1d0acf | 678 | js | JavaScript | packages/opensdk/__tests__/examples/plugin/miniprogram/pages/index/index.js | ChuanfengZhang/dingtalk-design-cli | 8a3c1f003a9069fc5e548c889302a78c05e8c0c2 | [
"MIT"
] | 11 | 2021-05-24T06:31:22.000Z | 2022-03-14T10:13:29.000Z | packages/opensdk/__tests__/examples/plugin/miniprogram/pages/index/index.js | tobuf/dingtalk-design-cli | 8d6283c7c0527f64fda3bf17d5eb3bbef31806f9 | [
"MIT"
] | 3 | 2021-04-29T06:14:50.000Z | 2022-03-31T09:48:22.000Z | packages/opensdk/__tests__/examples/plugin/miniprogram/pages/index/index.js | tobuf/dingtalk-design-cli | 8d6283c7c0527f64fda3bf17d5eb3bbef31806f9 | [
"MIT"
] | 6 | 2021-06-27T15:29:24.000Z | 2022-01-06T09:17:29.000Z | var plugin = requirePlugin("myPlugin");
Page({
onLoad(query) {
plugin.getData();
// 页面加载
console.info(`Page onLoad with query: ${JSON.stringify(query)}`);
},
onReady() {
// 页面加载完成
},
onShow() {
// 页面显示
},
onHide() {
// 页面隐藏
},
onUnload() {
// 页面被关闭
},
onTitleClick() {
// 标题被点击
},
onPullDownRefresh() {
// 页面被下拉
},
onReachBottom() {
// 页面被拉到底部
},
onShareAppMessage() {
// 返回自定义分享信息
return {
title: 'My App',
desc: 'My App description',
path: 'pages/index/index',
};
},
navigateToPlugin() {
dd.navigateTo({
url: 'plugin://myPlugin/hello-page',
});
}
});
| 15.409091 | 69 | 0.516224 |
6fda6b2b019bdc3e0693d9a7cfc2da65d115d2ba | 102 | js | JavaScript | ecosystem.config.js | lpgera/air-conditioner-web-remote | 2d4d1e5c4f7646be3e8ddcbde2be01f661c9c726 | [
"MIT"
] | null | null | null | ecosystem.config.js | lpgera/air-conditioner-web-remote | 2d4d1e5c4f7646be3e8ddcbde2be01f661c9c726 | [
"MIT"
] | null | null | null | ecosystem.config.js | lpgera/air-conditioner-web-remote | 2d4d1e5c4f7646be3e8ddcbde2be01f661c9c726 | [
"MIT"
] | null | null | null | module.exports = {
apps: [
{
name: 'ac-remote',
script: 'src/server.js',
}
]
} | 12.75 | 30 | 0.45098 |
6fdb3aabfdc49cbdefd9daf1b7475af09004d690 | 865 | js | JavaScript | docs/implementors/core/iter/traits/collect/trait.FromIterator.js | HuguesGuilleus/srt2webvtt | e2bfbe1896b9a35b6e49ede89872bd67df42cb80 | [
"BSD-3-Clause"
] | null | null | null | docs/implementors/core/iter/traits/collect/trait.FromIterator.js | HuguesGuilleus/srt2webvtt | e2bfbe1896b9a35b6e49ede89872bd67df42cb80 | [
"BSD-3-Clause"
] | null | null | null | docs/implementors/core/iter/traits/collect/trait.FromIterator.js | HuguesGuilleus/srt2webvtt | e2bfbe1896b9a35b6e49ede89872bd67df42cb80 | [
"BSD-3-Clause"
] | null | null | null | (function() {var implementors = {};
implementors["proc_macro2"] = [{"text":"impl FromIterator<TokenTree> for TokenStream","synthetic":false,"types":[]},{"text":"impl FromIterator<TokenStream> for TokenStream","synthetic":false,"types":[]}];
implementors["syn"] = [{"text":"impl<T, P> FromIterator<T> for Punctuated<T, P> <span class=\"where fmt-newline\">where<br> P: Default, </span>","synthetic":false,"types":[]},{"text":"impl<T, P> FromIterator<Pair<T, P>> for Punctuated<T, P>","synthetic":false,"types":[]}];
implementors["vec_map"] = [{"text":"impl<V> FromIterator<(usize, V)> for VecMap<V>","synthetic":false,"types":[]}];
if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})() | 173 | 343 | 0.695954 |
6fdc5948f048498f152614dbfc46866b8a734541 | 781 | js | JavaScript | res/project/plan.js | 13927729580/kooteam | 4fc376c2296ce2dff0ca414adaec6125dc016d43 | [
"Apache-2.0"
] | 38 | 2018-12-01T06:48:50.000Z | 2021-05-22T12:45:24.000Z | res/project/plan.js | hafly/kooteam | 4fc376c2296ce2dff0ca414adaec6125dc016d43 | [
"Apache-2.0"
] | 6 | 2018-12-26T03:52:56.000Z | 2021-05-19T11:49:43.000Z | res/project/plan.js | hafly/kooteam | 4fc376c2296ce2dff0ca414adaec6125dc016d43 | [
"Apache-2.0"
] | 18 | 2019-01-11T03:55:46.000Z | 2021-05-22T12:45:26.000Z | zenTemplate={"content":"<div id='J_app'><z-datasource> <var name=\"data\">/select/thing.json</var></z-datasource><div class=\"k-plan z-row\"><div class=\"z-col k-project-toolbar\"><div v-href=\"'/project/board.htm?$id'\"> <i class=\"z-icon\"></i> <span>看板</span></div><div class=\"active\"> <i class=\"z-icon\"></i> <span>计划</span></div><div v-href=\"'/project/doc.htm?$id'\"> <i class=\"z-icon\"></i> <span>文档</span></div><div v-href=\"'/project/member.htm?$id'\"> <i class=\"z-icon\"></i> <span>成员</span></div><div v-href=\"'/project/set.htm?$id'\"> <i class=\"z-icon\"></i> <span>统计</span></div></div><k-plan v-if=\"data\" v-model=\"data.data\"></k-plan></div><k-todo-detail></k-todo-detail></div>","ext":"","sons":{},"data":{"data":""}}; | 781 | 781 | 0.590269 |
6fdc8c8db4b7158c4e56be5ff25c275cd77464ba | 21,774 | js | JavaScript | bomberman/game.js | slawyn/pc-bomberman-javascript | b6ae5241f30496ec1f81b75a2fe48031f306e19c | [
"Apache-2.0"
] | null | null | null | bomberman/game.js | slawyn/pc-bomberman-javascript | b6ae5241f30496ec1f81b75a2fe48031f306e19c | [
"Apache-2.0"
] | null | null | null | bomberman/game.js | slawyn/pc-bomberman-javascript | b6ae5241f30496ec1f81b75a2fe48031f306e19c | [
"Apache-2.0"
] | null | null | null | var G_FIELD;
var G_CONCRETE_BLOCKS = {};
var G_CONCRETE_DEATH_BLOCKS={};
var G_START_SUDDEN_DEATH=0;
var G_BOMBS = {};
var G_CRATES = {};
var G_EXPLOSIONS = [];
var G_GAMECONTEXT;
var G_BORDERCONTEXT=[];
var G_DECORATIONS_BACK=[];
var G_DECORATIONS_FRONT =[]
var G_SPRITES=[];
var G_ROUND_ENDED;
var G_SUDDEN_DEATH_TIME;
var G_SOUNDS ={};
var G_PLAYERS = [];
var G_PLAYER1;
var G_PLAYER2;
var G_WINNER;
var G_LAST_TIME; // global variable for calculating dt
var G_TIME;
var G_FPS;
var help;
var nm_of_death_blocks;
var death_block_side_done_counter;
var fps_counter;
var death_block_starting_side;
var death_block_distance;
var invertedx;
var invertedy;
var XXX;
var YYY;
// automatically generated according to G_Actions
var G_Controls = {};
var G_Actions = {
player1_move_left: 65,
player1_move_right: 68,
player1_move_down: 83,
player1_move_up: 87,
player1_lay_bomb: 67,
player2_move_left: 37,
player2_move_right: 39,
player2_move_down: 40,
player2_move_up: 38,
player2_lay_bomb: 107
};
// field is 15 x 11: each block is 36 pixels + 2 pixels(border)
//0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
var G_LEVEL_Layout = [
[0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0], // 0.
[0, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 0], // 1. row
[3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3], // 3. row
[3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3], // 3. row
[3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3], // 4. row
[3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3], // 5. row
[3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3], // 6. row
[3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3], // 7. row
[3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3], // 8. row
[0, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 0], // 9. row
[0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0], // 10. row
];
function reset_globals(){
for(var key in G_EXPLOSIONS){
delete G_EXPLOSIONS[key];
}
for(var key in G_CONCRETE_BLOCKS){
delete G_CONCRETE_BLOCKS[key];
}
for(var key in G_CONCRETE_DEATH_BLOCKS){
delete G_CONCRETE_DEATH_BLOCKS[key];
}
for(var key in G_BOMBS){
delete G_BOMBS[key];
}
for(var key in G_CRATES){
delete G_CRATES[key];
}
for(var key in G_BORDERCONTEXT){
G_BORDERCONTEXT.pop(key);
}
for(var key in G_SOUNDS){
delete G_SOUNDS[key];
}
for(var key in G_PLAYERS){
G_PLAYERS[key].respawn();
}
for(var key in G_DECORATIONS_BACK){
delete G_DECORATIONS_BACK[key];
delete G_DECORATIONS_FRONT[key];
}
G_GAMECONTEXT = null;
G_SUDDEN_DEATH_TIME = 20;
G_START_SUDDEN_DEATH=0;
G_FIELD = null;
// G_PLAYER1 = null;
// G_PLAYER2 = null;
G_WINNER = null;
G_LAST_TIME = Date.now(); // global variable for calculating dt
G_TIME = 0;
G_FPS = 0;
help = 0;
nm_of_death_blocks = 0;
death_block_side_done_counter =0;
fps_counter=0;
death_block_starting_side=0;
death_block_distance = 0;
invertedx=0;
invertedy=0;
XXX=0;
YYY=0;
}
// create control dictionary
function create_controls() {
for (var key in G_Actions){
// create controls according to G_Actions
G_Controls[G_Actions[key]] = 0;
}
// start listening to the keys
window.addEventListener('keydown', keyHandler, false);
window.addEventListener('keyup', keyHandler, false);
}
function renderBorder0(dt){
if(!G_BORDERCONTEXT[0])
return;
G_BORDERCONTEXT[0].fillText("Name Range Bombs Kills",10,40,"#555555","14px Arial");
var idx = 0;
for(var i in G_PLAYERS){
var string = G_PLAYERS[i].costume+" "+G_PLAYERS[i].bombrange + " "+G_PLAYERS[i].bombscarrying+" "+G_PLAYERS[i].kills;
G_BORDERCONTEXT[0].fillText(string,10,70+20*idx,"#FFFFFF","14px Arial");
idx++;
}
var time_format = "time: 0:";
var time = (G_TIME%60)|0;
if(time<10){
time_format = time_format +"0"+time;
}else{
time_format = time_format+time;
}
G_BORDERCONTEXT[0].fillText(time_format,180,20*idx,"#124511","14px Arial");
G_BORDERCONTEXT[0].fillText("fps:"+(G_FPS|0),180,50+20*idx,"#555555","14px Arial");
if(G_ROUND_ENDED){
G_BORDERCONTEXT[0].fillText("WINNER IS "+G_WINNER,100,300,"#FF1100",'50px Arial');
}
}
// Main game loop
function gameLoop() {
var now = Date.now();
var dt = (now - G_LAST_TIME) / 1000.0; // about 18 milliseconds
update(dt); // update the game
G_GAMECONTEXT.clearContext();// WARNING is there flickering or problems with joint pixels?
render(); // render the game
renderBorder0();
G_LAST_TIME = now;
window.requestAnimationFrame(gameLoop);
}
// Handle input for all players
function handleInput(dt) {
for (var cellpos in G_PLAYERS) {
if (G_PLAYERS[cellpos] == G_PLAYER1) {
var dirX = (-G_Controls[G_Actions.player1_move_left]) | G_Controls[G_Actions.player1_move_right]; // set x direction: either negative 0 or positive
var dirY = (-G_Controls[G_Actions.player1_move_up]) | G_Controls[G_Actions.player1_move_down]; // set y direction
if(dirX)
dirY=0;
G_PLAYER1.update(dt, dirX, dirY); // update player movement. TODO we should immediately check for collisions before anything else! WARNING on higher speed bomb is placed everywhere!
if(G_PLAYER1.laybomb(dt, G_Controls[G_Actions.player1_lay_bomb], G_BOMBS, G_PLAYERS)){
}; // place a bomb
} else if (G_PLAYERS[cellpos] == G_PLAYER2) {
var dirX = (-G_Controls[G_Actions.player2_move_left]) | G_Controls[G_Actions.player2_move_right];
var dirY = (-G_Controls[G_Actions.player2_move_up]) | G_Controls[G_Actions.player2_move_down];
if(dirX)
dirY=0;
G_PLAYER2.update(dt, dirX, dirY);
if(G_PLAYER2.laybomb(dt, G_Controls[G_Actions.player2_lay_bomb], G_BOMBS, G_PLAYERS)){
};
} // TODO add more players
}
}
// update objects
function updateEntities(dt) {
for (var cellpos in G_SPRITES) {
G_SPRITES[cellpos].update(dt);
if(G_SPRITES[cellpos].done()){
delete G_SPRITES[cellpos];
}
}
// update explosions
for (var cellpos in G_EXPLOSIONS) {
G_EXPLOSIONS[cellpos].update(dt);
if (G_EXPLOSIONS[cellpos].done())
delete G_EXPLOSIONS[cellpos];
}
// update bombs
for (var cellpos in G_BOMBS) {
G_BOMBS[cellpos].update(dt);
// TODO create chain reaction by exploding all the other bombs
if (G_BOMBS[cellpos].exploded(G_CRATES, G_BOMBS, G_CONCRETE_BLOCKS)) {
var collisions = handleExplosion(cellpos);
// remove the destroyable objects
delete G_BOMBS[cellpos];
// delete exploded bombs
for (var i in collisions.col_bombs) {
delete G_BOMBS[collisions.col_bombs[i]];
}
// delete destroyed crates
for (var i in collisions.col_crates) {
delete G_CRATES[collisions.col_crates[i]];
}
}
}
// update the rest
}
// Handle different collisions
function handleCollisions(dt) {
for (var cellpos in G_PLAYERS) {
G_PLAYERS[cellpos].checkLevelBounds(G_FIELD); // don't let player go off the map
G_PLAYERS[cellpos].checkBlockCollisions(G_CONCRETE_BLOCKS); // don't let players go through blocks
G_PLAYERS[cellpos].checkBlockCollisions(G_CRATES); //
G_PLAYERS[cellpos].checkBlockCollisions(G_CONCRETE_DEATH_BLOCKS); // don't let players go through blocks
G_PLAYERS[cellpos].checkBlockCollisions(G_BOMBS); // don't let players go through bombs
G_PLAYERS[cellpos].checkExplosionCollisions(G_EXPLOSIONS); // player dies if he goes into explosion
}
}
function handleExplosion(cellpos) {
var collisions = {
col_bombs: [],
col_crates: [],
col_field_blocks: []
};
// let user use the bomb
// exploded
var cellpos_ = parseInt(cellpos);
var hor = cellpos_ % 15;
var ver = (cellpos_ - hor) / 15;
var explosion_direction = {
left: 1,
right: 1,
up: 1,
down: 1
};
var range = G_BOMBS[cellpos].range;
// horizontal
if (hor == 14) {
explosion_direction.right = 0;
} else if (hor == 0) {
explosion_direction.left = 0;
}
// vertical
if (ver == 10) {
explosion_direction.down = 0;
} else if (ver == 0) {
explosion_direction.up = 0;
}
if (cellpos_ in G_CRATES) {
collisions.col_crates.push(cellpos_);
}
if (explosion_direction.left) {
while (true) {
if ((cellpos_ - explosion_direction.left) in G_CRATES) {
collisions.col_crates.push(cellpos_ - explosion_direction.left);
break;
} else if ((cellpos_ - explosion_direction.left) in G_CONCRETE_BLOCKS) {
explosion_direction.left--;
break;
} else if ((cellpos_ - explosion_direction.left) in G_BOMBS) {
if (G_BOMBS[(cellpos_ - explosion_direction.left)].lifetime > 0) { // avoid endless recursion, if lifetime is already 0 we don't add the bombs to the list
collisions.col_bombs.push(cellpos_ - explosion_direction.left);
}
explosion_direction.left--;
break;
} else if ((cellpos_ - explosion_direction.left) % 15 == 0) {
break;
} else if (explosion_direction.left < range) {
explosion_direction.left++;
} else {
break;
}
}
}
if (explosion_direction.right) {
while (true) {
if ((explosion_direction.right + cellpos_) in G_CRATES) {
collisions.col_crates.push(explosion_direction.right + cellpos_);
break;
} else if ((explosion_direction.right + cellpos_) in G_CONCRETE_BLOCKS) {
explosion_direction.right--;
break;
} else if ((explosion_direction.right + cellpos_) in G_BOMBS) {
if (G_BOMBS[(explosion_direction.right + cellpos_)].lifetime > 0) {
collisions.col_bombs.push(explosion_direction.right + cellpos_);
}
explosion_direction.right--;
break;
} else if ((explosion_direction.right + cellpos_) % 15 == 14) {
break;
} else if (explosion_direction.right < range) {
explosion_direction.right++;
} else {
break;
}
}
}
if (explosion_direction.up) {
while (true) {
if ((cellpos_ - explosion_direction.up * 15) in G_CRATES) {
collisions.col_crates.push(cellpos_ - explosion_direction.up * 15);
break;
} else if ((cellpos_ - explosion_direction.up * 15) in G_CONCRETE_BLOCKS) {
explosion_direction.up--;
break;
} else if ((cellpos_ - explosion_direction.up * 15) < 0) {
explosion_direction.up--;
break;
} else if ((cellpos_ - explosion_direction.up * 15) in G_BOMBS) {
if (G_BOMBS[(cellpos_ - explosion_direction.up * 15)].lifetime > 0) {
collisions.col_bombs.push(cellpos_ - explosion_direction.up * 15);
}
explosion_direction.up--
break;
} else if (explosion_direction.up < range) {
explosion_direction.up++;
} else {
break;
}
}
}
if (explosion_direction.down) {
while (true) {
if ((cellpos_ + explosion_direction.down * 15) in G_CRATES) {
collisions.col_crates.push(cellpos_ + explosion_direction.down * 15);
break;
} else if ((cellpos_ + explosion_direction.down * 15) in G_CONCRETE_BLOCKS) {
explosion_direction.down--;
break;
} else if ((cellpos_ + explosion_direction.down * 15) > 164) {
explosion_direction.down--;
break;
} else if ((cellpos_ + explosion_direction.down * 15) in G_BOMBS) {
if (G_BOMBS[(cellpos_ + explosion_direction.down * 15)].lifetime > 0) {
collisions.col_bombs.push(cellpos_ + explosion_direction.down * 15);
}
explosion_direction.down--
break;
} else if (explosion_direction.down < range) {
explosion_direction.down++;
} else {
break;
}
}
}
// add new explosion
G_EXPLOSIONS.push(new Explosion(G_GAMECONTEXT, G_BOMBS[cellpos_].owner, G_BOMBS[cellpos_].posX, G_BOMBS[cellpos_].posY, explosion_direction, range));
for (var i in collisions.col_bombs) {
bomb_cell = collisions.col_bombs[i];
G_BOMBS[bomb_cell].lifetime = 0;
G_BOMBS[bomb_cell].exploded();
var rec_collisions = handleExplosion(bomb_cell);
collisions.col_bombs.push.apply(collisions.col_bombs, rec_collisions.col_bombs); // add chain to the current list
collisions.col_crates.push.apply(collisions.col_crates, rec_collisions.col_crates);
}
return collisions;
}
// Add new crate entities
function timedEvents(dt) {
var p_time = G_TIME;
var done = 0;
var sec = 0;
G_TIME += dt;
fps_counter++;
// fps counter
if(((0|(G_TIME % 2)) == 1 )&& (((p_time % 2)|0) == 0) ||(((0|(G_TIME % 2)) == 0 )&& (((p_time % 2)|0) == 1))){
G_FPS = fps_counter;
fps_counter =0;
sec = 1;
}
if(G_ROUND_ENDED>0 ){
G_START_SUDDEN_DEATH= 0; // stop sudden death when round ended
G_ROUND_ENDED+=dt;
if((0|G_ROUND_ENDED)==3){
reset_globals();
create_game();
G_ROUND_ENDED = 0;
}
}
// sudden death
if(!G_START_SUDDEN_DEATH&&((0|G_TIME)==G_SUDDEN_DEATH_TIME)){
G_SPRITES.push(new Object(40,40,new Sprite({
canvas: G_GAMECONTEXT ,
url: 'levels/sudden_death.png',
size: [459,90],
speed: 1,
once:true,
frames: [0,1]
})));
G_START_SUDDEN_DEATH = 1;
death_block_starting_side = (0|(Math.random() *4));
if(death_block_starting_side==1){
XXX=14;
}
else if (death_block_starting_side ==2){
XXX=14;
YYY=10;}
else if (death_block_starting_side ==3){
YYY=10;
XXX=0;
}
G_SOUNDS["alarm"].play();
}
// sec = 1;
// sudden death
if(G_START_SUDDEN_DEATH && (sec)){
var new_cell = XXX +YYY*15;
nm_of_death_blocks++;
if(nm_of_death_blocks == (164)){// last block
G_START_SUDDEN_DEATH = 0;
}
if(!(new_cell in G_CONCRETE_DEATH_BLOCKS ||(new_cell in G_CONCRETE_BLOCKS ))){
var block =(new ConcreteBlock(G_GAMECONTEXT, XXX * 40 + 2, YYY * 40 + 2));
G_CONCRETE_BLOCKS[XXX +YYY*15] = block;
G_SOUNDS["death_block"].play();
for(var cellpos in G_PLAYERS){
if(G_PLAYERS[cellpos].checkDeathBlockCollision(block))
G_PLAYERS[cellpos].die();
}
if( new_cell in G_CRATES){
delete G_CRATES[new_cell];
}
if( new_cell in G_BOMBS){
G_BOMBS[new_cell].lifetime=0;
}
}
if(death_block_starting_side == 0) {
++XXX;
if((14-XXX)<=death_block_distance)
done = 1;
}
if(death_block_starting_side == 1) {
++YYY;
if((10-YYY)<=death_block_distance)
done = 1;
}
if(death_block_starting_side == 2) {
--XXX;
if(XXX<=death_block_distance)
done = 1;
}
if(death_block_starting_side == 3) {
--YYY;
if(YYY<=death_block_distance)
done = 1;
}
if(done){
death_block_starting_side =((++death_block_starting_side)%4);
++death_block_side_done_counter;
if(death_block_side_done_counter%4==0){
death_block_distance++;
}
if(death_block_starting_side==0){
XXX = death_block_distance;
YYY = death_block_distance;
}else if(death_block_starting_side == 1){
XXX = 14-death_block_distance;
YYY = death_block_distance;
}else if(death_block_starting_side == 2){
XXX =14-death_block_distance;
YYY =10-death_block_distance;
}else if(death_block_starting_side == 3){
XXX =death_block_distance;
YYY =10-death_block_distance;
}
done = 0;
}
}
// WARNING does overflow create an exception behavior??
if ((0|(G_TIME % 21)) == 20 && ((p_time % 21)|0) == 19) { // every 20 seconds
var new_cellpos = Math.floor((Math.random() * 165));
if (!(new_cellpos in G_CRATES) && !(new_cellpos in G_CONCRETE_BLOCKS)) {
for (var i in G_PLAYERS) {
if (G_PLAYERS[i].posCELL == new_cellpos)
return;
}
G_CRATES[new_cellpos] = new Crate(G_GAMECONTEXT, (new_cellpos % 15 * 40), (new_cellpos - new_cellpos % 15) / 15 * 40 );
}
}
// TODO add sudden death after time limit
}
function handleTheDead(){
var alive = 0;
var key ;
// remove dead players from the game. TODO change it so that players stay in the game but become invisible
for (var cellpos in G_PLAYERS) {
if (G_PLAYERS[cellpos].dead()) {
// delete G_PLAYERS[cellpos];
}
else{
alive++;
key = cellpos;
}
}
if(!G_ROUND_ENDED && alive == 1){
G_WINNER = G_PLAYERS[key].costume;
G_ROUND_ENDED = 1;
}
else if(!G_ROUND_ENDED && alive == 0){
G_WINNER = "nobody";
G_ROUND_ENDED = 1;
}
}
// Updating function
function update(dt) {
handleTheDead();
handleInput(dt);
handleCollisions();
updateEntities(dt);
timedEvents(dt);
}
function compareDepth(p1, p2){
if(p1.posY <p2.posY){
return -1;
}
if(p1.posY>p2.posY){
return 1;
}
return 0;
}
// Rendering function
function render() {
// render in this order
G_FIELD.render(); // render field
for (var cellpos in G_EXPLOSIONS) {
G_EXPLOSIONS[cellpos].render(); // render explosions
}
for (var cellpos in G_CONCRETE_BLOCKS) {
G_CONCRETE_BLOCKS[cellpos].render(); // render concrete blocks
}
for (var cellpos in G_BOMBS) {
G_BOMBS[cellpos].render(); // render bombs
}
for (var cellpos in G_CRATES) {
G_CRATES[cellpos].render(); // render crates
}
for(var cellpos in G_DECORATIONS_BACK){
G_DECORATIONS_BACK[cellpos].render(); // render crates
}
G_PLAYERS.sort(compareDepth);
for (var cellpos in G_PLAYERS){
G_PLAYERS[cellpos].render(); //render players. WARNING who is higher renders first
}
for(var cellpos in G_DECORATIONS_FRONT){
G_DECORATIONS_FRONT[cellpos].render(); // render crates
}
for (var cellpos in G_SPRITES) {
G_SPRITES[cellpos].render();
}
}
function create_game(){
// set canvas size
var canvas = document.getElementById("gamecanvas");
canvas.width = 800;
canvas.height = 600;
var gamefield_sizex = 604;
var gamefield_sizey = 444;
var game_field_offsetx = 170;
var game_field_offsety = 100;
// upper
G_BORDERCONTEXT.push(new Context(canvas,0,0, canvas.width ,canvas.height));
G_GAMECONTEXT = new Context(canvas,game_field_offsetx,game_field_offsety,gamefield_sizex,gamefield_sizey);
// Field is 604 x 444 pixels
G_FIELD = new Field(G_GAMECONTEXT);
// create blocks. one block is 36 pixels.
for (var i = 0; i < G_LEVEL_Layout.length; i++) {
for (var j = 0; j < G_LEVEL_Layout[i].length; j++) {
// place concrete block according to raster
if (G_LEVEL_Layout[i][j] == 1) {
G_CONCRETE_BLOCKS[i * 15 + j] = new ConcreteBlock(G_GAMECONTEXT, j * 40 + 2, i * 40 + 2);
// place crates
} else if (Math.floor((Math.random() * G_LEVEL_Layout[i][j]) +1) == 3) {
G_CRATES[i * 15 + j] = new Crate(G_GAMECONTEXT, j * 40 + 2, i * 40 + 2);
}
}
}
// spawn player
if(!G_PLAYER1){
G_PLAYER1 = new Character(G_GAMECONTEXT, 0, -20, "player1");
G_PLAYERS[G_PLAYER1.posCELL] = G_PLAYER1;
}
G_PLAYER1.bombsplaced=0;
if(!G_PLAYER2){
G_PLAYER2 = new Character(G_GAMECONTEXT, 560,380 , "player2");
G_PLAYERS[G_PLAYER2.posCELL] = G_PLAYER2;
}
G_PLAYER2.bombsplaced = 0;
G_SOUNDS["death_block"] = new Sound("sounds/death_block.mp3");
G_SOUNDS["alarm"] = new Sound("sounds/alarm.wav");
for(var i=0;i<15;i++){
G_DECORATIONS_BACK.push(new Decoration(G_GAMECONTEXT,0+40*i,-35));
G_DECORATIONS_FRONT.push(new Decoration(G_GAMECONTEXT,0+40*i, 444-34));
}
}
// init game
function init() {
create_controls();
reset_globals();
create_game();
gameLoop(); // start game loop
}
function keyHandler(e) {
var key = e.keyCode;
if (key in G_Controls) {
if (e.type == 'keydown') {
G_Controls[key] = 1
} else {
G_Controls[key] = 0
}
}
}
| 27.2175 | 193 | 0.579866 |
6fdc92b42cc40736e729fe4fbc0c0c1e0aa78dbd | 1,442 | js | JavaScript | services/frontend/src/components/mobile-search.js | kuronosec/eos-rate | 3300dcacb12756d7e25c2b328af7130e39cea4ea | [
"MIT"
] | null | null | null | services/frontend/src/components/mobile-search.js | kuronosec/eos-rate | 3300dcacb12756d7e25c2b328af7130e39cea4ea | [
"MIT"
] | null | null | null | services/frontend/src/components/mobile-search.js | kuronosec/eos-rate | 3300dcacb12756d7e25c2b328af7130e39cea4ea | [
"MIT"
] | null | null | null | import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { withStyles } from '@material-ui/core/styles'
import Dialog from '@material-ui/core/Dialog'
import AppBar from '@material-ui/core/AppBar'
import Toolbar from '@material-ui/core/Toolbar'
import IconButton from '@material-ui/core/IconButton'
import CloseIcon from '@material-ui/icons/Close'
import Slide from '@material-ui/core/Slide'
import InputAutocomplete from 'components/input-autocomplete'
const styles = theme => ({
appBar: {
position: 'relative'
},
flex: {
flex: 1
}
})
const Transition = React.forwardRef((props, ref) => <Slide direction='up' {...props} ref={ref} />)
class MobileSearch extends PureComponent {
static propTypes = {
classes: PropTypes.object,
isOpen: PropTypes.bool,
onClose: PropTypes.func
}
render () {
const { classes, isOpen, onClose } = this.props
return (
<Dialog
fullScreen
open={isOpen}
onClose={onClose}
TransitionComponent={Transition}
>
<AppBar className={classes.appBar}>
<Toolbar>
<InputAutocomplete onItemSelected={onClose} isFocused={isOpen} />
<IconButton color='inherit' onClick={onClose} aria-label='Close'>
<CloseIcon />
</IconButton>
</Toolbar>
</AppBar>
</Dialog>
)
}
}
export default withStyles(styles)(MobileSearch)
| 26.218182 | 98 | 0.651179 |
6fdce372d58487919676723b9385915e83a64bb1 | 6,978 | js | JavaScript | node_modules/@progress/kendo-angular-upload/dist/npm/navigation.service.js | divlaksh/questionnaire-new | 900b4a74943dbbddffce930ad2d2b8216233facd | [
"Apache-2.0"
] | null | null | null | node_modules/@progress/kendo-angular-upload/dist/npm/navigation.service.js | divlaksh/questionnaire-new | 900b4a74943dbbddffce930ad2d2b8216233facd | [
"Apache-2.0"
] | 6 | 2020-06-17T13:26:07.000Z | 2022-03-02T09:09:27.000Z | node_modules/@progress/kendo-angular-upload/dist/npm/navigation.service.js | divlaksh/questionnaire-new | 900b4a74943dbbddffce930ad2d2b8216233facd | [
"Apache-2.0"
] | null | null | null | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = require("@angular/core");
var upload_service_1 = require("./upload.service");
var kendo_angular_common_1 = require("@progress/kendo-angular-common");
/**
* @hidden
*/
var NavigationService = /** @class */ (function () {
function NavigationService(uploadService) {
this.uploadService = uploadService;
this.onActionButtonAction = new core_1.EventEmitter();
this.onActionButtonFocus = new core_1.EventEmitter();
this.onFileAction = new core_1.EventEmitter();
this.onFileFocus = new core_1.EventEmitter();
this.onTab = new core_1.EventEmitter();
this.onWrapperFocus = new core_1.EventEmitter();
this.onSelectButtonFocus = new core_1.EventEmitter();
this.actionButtonsVisible = false;
this.focused = false;
this._focusedIndex = -1;
}
NavigationService.prototype.action = function (event) {
var key = event.keyCode;
return this.keyBindings[key];
};
NavigationService.prototype.process = function (event) {
var handler = this.action(event);
if (handler) {
handler(event.shiftKey);
}
};
NavigationService.prototype.computeKeys = function (direction) {
var _this = this;
var _a;
this.keyBindings = (_a = {},
_a[kendo_angular_common_1.Keys.Enter] = function () { return _this.handleEnter(); },
_a[kendo_angular_common_1.Keys.Escape] = function () { return _this.handleEscape(); },
_a[kendo_angular_common_1.Keys.Delete] = function () { return _this.handleDelete(); },
_a[kendo_angular_common_1.Keys.Tab] = function (shifted) { return _this.handleTab(shifted); },
_a[kendo_angular_common_1.Keys.ArrowUp] = function () { return _this.handleUp(); },
_a[kendo_angular_common_1.Keys.ArrowDown] = function () { return _this.handleDown(); },
_a[this.invertKeys(direction, kendo_angular_common_1.Keys.ArrowLeft, kendo_angular_common_1.Keys.ArrowRight)] = function () { return _this.handleLeft(); },
_a[this.invertKeys(direction, kendo_angular_common_1.Keys.ArrowRight, kendo_angular_common_1.Keys.ArrowLeft)] = function () { return _this.handleRight(); },
_a);
};
NavigationService.prototype.invertKeys = function (direction, original, inverted) {
return direction === 'rtl' ? inverted : original;
};
NavigationService.prototype.focusSelectButton = function () {
this.focused = true;
this._focusedIndex = -1;
this.onSelectButtonFocus.emit();
};
NavigationService.prototype.handleEnter = function () {
if (this.lastIndex >= 0) {
if (this.focusedIndex <= this.lastFileIndex) {
this.onFileAction.emit(kendo_angular_common_1.Keys.Enter);
return;
}
if (this.actionButtonsVisible && this.focusedIndex <= this.lastIndex) {
this.onActionButtonAction.emit(this.focusedIndex < this.lastIndex ? "clear" : "upload");
}
}
};
NavigationService.prototype.handleDelete = function () {
if (this.focusedIndex >= 0 && this.focusedIndex <= this.lastFileIndex) {
this.onFileAction.emit(kendo_angular_common_1.Keys.Delete);
}
};
NavigationService.prototype.handleEscape = function () {
if (this.focusedIndex >= 0 && this.focusedIndex <= this.lastFileIndex) {
this.onFileAction.emit(kendo_angular_common_1.Keys.Escape);
}
};
NavigationService.prototype.handleLeft = function () {
if (this.actionButtonsVisible && this.focusedIndex === this.lastIndex) {
this.focusedIndex -= 1;
this.onActionButtonFocus.emit("clear");
}
};
NavigationService.prototype.handleRight = function () {
if (this.actionButtonsVisible && this.focusedIndex === this.lastIndex - 1) {
this.focusedIndex += 1;
this.onActionButtonFocus.emit("upload");
}
};
NavigationService.prototype.handleTab = function (shifted) {
if (this.focusedIndex >= 0 && shifted) {
this.focusedIndex = -1;
return;
}
this.onTab.emit();
};
NavigationService.prototype.handleDown = function () {
if (this.lastIndex >= 0 && this.focusedIndex < this.lastIndex) {
if (this.focusedIndex < this.lastFileIndex) {
this.focusedIndex += 1;
this.onFileFocus.emit(this.focusedIndex);
return;
}
if (this.actionButtonsVisible && this.focusedIndex === this.lastFileIndex) {
this.focusedIndex += 1;
this.onActionButtonFocus.emit("clear");
}
}
};
NavigationService.prototype.handleUp = function () {
if (this.lastIndex >= 0 && this.focusedIndex > -1) {
this.focusedIndex -= 1;
if (this.focusedIndex === -1) {
this.onSelectButtonFocus.emit();
return;
}
if (this.focusedIndex <= this.lastFileIndex) {
this.onFileFocus.emit(this.focusedIndex);
return;
}
if (this.actionButtonsVisible && this.focusedIndex <= this.lastIndex) {
this.focusedIndex = this.lastFileIndex;
this.onFileFocus.emit(this.focusedIndex);
}
}
};
Object.defineProperty(NavigationService.prototype, "focusedIndex", {
get: function () {
return this._focusedIndex;
},
set: function (index) {
if (!this.focused) {
this.onWrapperFocus.emit();
}
this._focusedIndex = index;
this.focused = true;
if (this._focusedIndex >= 0 && this._focusedIndex <= this.lastFileIndex) {
this.onFileFocus.emit(index);
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(NavigationService.prototype, "lastFileIndex", {
get: function () {
return this.actionButtonsVisible ? this.lastIndex - 2 : this.lastIndex;
},
enumerable: true,
configurable: true
});
Object.defineProperty(NavigationService.prototype, "lastIndex", {
get: function () {
var fileCount = this.uploadService.files.count;
return this.actionButtonsVisible ? fileCount + 1 : fileCount - 1;
},
enumerable: true,
configurable: true
});
NavigationService.decorators = [
{ type: core_1.Injectable },
];
/** @nocollapse */
NavigationService.ctorParameters = function () { return [
{ type: upload_service_1.UploadService }
]; };
return NavigationService;
}());
exports.NavigationService = NavigationService;
| 41.784431 | 168 | 0.603181 |
6fdd315f3681642783f99a2a99bbc42b029e8f88 | 11,505 | js | JavaScript | app/home/GDHome.js | Hey2Li/RNGD | 67ee45439c5fe05aa8f2f358f6b28470e3832684 | [
"Apache-2.0"
] | null | null | null | app/home/GDHome.js | Hey2Li/RNGD | 67ee45439c5fe05aa8f2f358f6b28470e3832684 | [
"Apache-2.0"
] | null | null | null | app/home/GDHome.js | Hey2Li/RNGD | 67ee45439c5fe05aa8f2f358f6b28470e3832684 | [
"Apache-2.0"
] | null | null | null | import React, { Component } from 'react';
import {
StyleSheet,
View,
TouchableOpacity,
Image,
ListView,
Dimensions,
ActivityIndicator,
Modal,
AsyncStorage,
Navigator
} from 'react-native';
// 组件
import CommunaNavBar from '../main/GDCommunalNavBar';
import HalfHourHot from './GDHalfHourHot';
import Search from '../main/GDSearch';
import NoDataView from '../main/GDNoDataView';
import CommunaCell from '../main/GDCommunalCell';
import CommunaDetail from '../main/GDCommunalDetail';
import CommunaSiftMenu from '../main/GDCommunalSiftMenu';
//第三方
import {PullList} from 'react-native-pull';
//数据
import HomeSiftData from '../data/HomeSiftData.json';
const {width, height} = Dimensions.get('window');
export default class GDHome extends Component {
constructor(props){
super(props);
this.state = {
dataSource:new ListView.DataSource({rowHasChanged:(r1, r2) => r1!==r2}),
loaded:false,
isHalfHourHotModal:false,
isSiftModal:false,
};
this.data = [];
this.fetchData = this.fetchData.bind(this);
this.loadMore = this.loadMore.bind(this);
}
//网络请求的方法
fetchData(resolve){
let params = {"count":10};
HTTPBase.get('http://guangdiu.com/api/getlist.php',params)
.then((responseData)=>{
//清空数组
this.data = [];
//拼接数据
this.data = this.data.concat(responseData.data);
//重新渲染
this.setState({
dataSource:this.state.dataSource.cloneWithRows(this.data),
loaded:true,
});
//关闭加载动画
if (resolve !== undefined){
setTimeout(()=>{
resolve();
},1000);
}
//存储数组的中最后一个元素的ID
let cnlastID = responseData.data[responseData.data.length - 1].id;
AsyncStorage.setItem('cnlastID',cnlastID.toString());
//存储数组中的第一个元素的ID
let cnfirstID = responseData.data[0].id;
AsyncStorage.setItem('cnfirstID',cnfirstID.toString());
//清空本地存储的数据
RealmBase.removeAllData('HomeData');
//存储到本地
RealmBase.create('HomeData', responseData.data);
}).catch((error)=>{
//拿到本地存储的的数据展示出来,如果没有数据就显示无数据页面
this.data = RealmBase.loadAll('HomeData');
//重新渲染
this.setState({
dataSource:this.state.dataSource.cloneWithRows(this.data),
loaded:true,
})
})
// let formData = new FormData();
// formData.append("count","5");
// formData.append("mall","京东商城");
// fetch('http://guangdiu.com/api/getlist.php',{
// method:'POST',
// headers:{},
// body:formData,
// })
// .then((response) => response.json())
// .then((responseData)=>{
// this.setState({
// dataSource:this.state.dataSource.cloneWithRows(responseData.data),
// loaded:true,
// });
// if (resolve !== undefined){
// setTimeout(()=>{
// resolve();
// },1000);
// }
// })
// .done();
}
//加载更多数据
loadMoreData(value){
//读取id
let params = {
"count":10,
"sinceid":value
};
HTTPBase.get('http://guangdiu.com/api/getlist.php',params)
.then((responseData)=>{
//拼接数据
this.data = this.data.concat(responseData.data);
this.setState({
dataSource:this.state.dataSource.cloneWithRows(this.data),
loaded:true,
});
//存储数组的中最后一个元素的ID
let cnlastID = responseData.data[responseData.data.length - 1].id;
AsyncStorage.setItem('cnlastID',cnlastID.toString());
}).catch((error)=>{
})
}
//网络请求的方法
loadSiftData(mall, cate){
let params = {};
if (mall === "" && cate === ""){
this.fetchData(undefined);
return;
}
if (mall === ""){ //cate有值
params = {
"cate":cate,
};
}else {
params = {
"mall":mall
};
}
HTTPBase.get('http://guangdiu.com/api/getlist.php',params)
.then((responseData)=>{
//清空数组
this.data = [];
//拼接数据
this.data = this.data.concat(responseData.data);
//重新渲染
this.setState({
dataSource:this.state.dataSource.cloneWithRows(this.data),
loaded:true,
});
//关闭加载动画
if (resolve !== undefined){
setTimeout(()=>{
resolve();
},1000);
}
//存储数组的中最后一个元素的ID
let cnlastID = responseData.data[responseData.data.length - 1].id;
AsyncStorage.setItem('cnlastID',cnlastID.toString());
}).catch((error)=>{
})
}
//跳转到半小时热门
pushToHalfHourHot(){
this.setState({
isHalfHourHotModal:true,
})
// this.props.navigator.push({
// component:HalfHourHot,
// animationType:Navigator.SceneConfigs.FloatFromBottom,
// });
}
pushToSearch() {
this.props.navigator.push({
component: Search,
});
}
renderLeftItem(){
return(
<TouchableOpacity onPress={()=>{
this.pushToHalfHourHot()
}}>
<Image source={{uri:'hot_icon_20x20'}} style={styles.navbarLeftItemStyle} />
</TouchableOpacity>
);
}
//显示筛选菜单
showSiftMenu() {
this.setState({
isSiftModal:true,
});
}
renderTitleItem(){
return(
<TouchableOpacity
onPress={() => {this.showSiftMenu()}}
>
<Image source={{uri:'navtitle_home_down_66x20'}} style={styles.navbarTitleItemStyle} />
</TouchableOpacity>
);
}
renderRightItem(){
return(
<TouchableOpacity onPress={()=>{this.pushToSearch()}}>
<Image source={{uri:'search_icon_20x20'}} style={styles.navbarRightItemStyle} />
</TouchableOpacity>
);
}
componentDidMount(){
this.fetchData();
}
//加载更多
loadMore(){
//读取存储的id
AsyncStorage.getItem('cnlastID')
.then((value)=>{
//数据加载操作
this.loadMoreData(value);
})
}
renderFooter(){
return (
<View style={{height:100}}>
<ActivityIndicator style={{alignItems:'center', justifyContent:'center', marginTop:30}}/>
</View>
);
}
renderListView(){
if (this.state.loaded === false){
return(
<NoDataView/>
);
}else {
return (
<PullList
onPullRelease={(resolve) => this.fetchData(resolve)}
dataSource={this.state.dataSource}
renderRow={this.renderRow.bind(this)}
showsHorizontalScrollIndicator={false}
style={styles.listViewStyle}
initialListSize={5}
renderHeader={this.renderHeader}
onEndReached={this.loadMore}
onEndReachedThreshold={60}
renderFooter={this.renderFooter}
/>
);
}
}
pushToDetail(value){
this.props.navigator.push({
component:CommunaDetail,
params:{
url:'http://guangdiu.com/go.php' + '?' + 'id=' + value,
}
});
}
//填充cell
renderRow(rowData){
return(
<TouchableOpacity onPress={()=>this.pushToDetail(rowData.id)}>
<CommunaCell
image={rowData.image}
title={rowData.title}
mall={rowData.mall}
pubTime={rowData.pubtime}
fromSite={rowData.fromsite}
/>
</TouchableOpacity>
);
}
onRequestClose(){
this.setState({
isHalfHourHotModal:false,
isSiftModal:false,
})
}
closeModal(data){
this.setState({
isHalfHourHotModal:data,
isSiftModal:false,
})
}
render() {
return (
<View style={styles.container}>
<CommunaNavBar
leftItem={()=>this.renderLeftItem()}
titleItem={()=>this.renderTitleItem()}
rightItem={()=>this.renderRightItem()}
/>
{/*根据网络状态决定是否渲染*/}
{this.renderListView()}
{/*初始化近半小时热门*/}
<Modal
animationType='slide'
translucent={false}
visible={this.state.isHalfHourHotModal}
onRequestClose={() => this.onRequestClose()}
>
<Navigator
initialRoute={{
name:'halfHourHot',
component:HalfHourHot
}}
renderScene={(route, navigator = {})=>{
let Component = route.component;
return <Component
removeModal={(data)=>this.closeModal(data)}
{...route.params}
navigator={navigator}/>
}}
/>
</Modal>
{/*初始化筛选菜单*/}
<Modal
pointerEvents={'box-none'}
animationType='none'
translucent={true}
visible={this.state.isSiftModal}
onRequestClose={() => this.onRequestClose()}
>
<CommunaSiftMenu
removeModal={(data)=>this.closeModal(data)}
data={HomeSiftData}
loadSiftData = {(mall, cate) => this.loadSiftData(mall, cate)}/>
</Modal>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
backgroundColor: 'white',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
navbarLeftItemStyle:{
width:20,
height:20,
marginLeft:15,
},
navbarTitleItemStyle:{
width:66,
height:20,
},
navbarRightItemStyle:{
width:20,
height:20,
marginRight:15,
},
listViewStyle:{
width:width,
},
});
| 27.789855 | 105 | 0.458931 |
6fdd9f2bd4c0fa5173b53b9513dd566c3e53f712 | 1,230 | js | JavaScript | client/src/redux/reducers/board.reducer.js | mfasman95/HTTP-API-assignmentt | a76d72f283960e2c88fe2a1d7ad0335445c502f1 | [
"MIT"
] | null | null | null | client/src/redux/reducers/board.reducer.js | mfasman95/HTTP-API-assignmentt | a76d72f283960e2c88fe2a1d7ad0335445c502f1 | [
"MIT"
] | null | null | null | client/src/redux/reducers/board.reducer.js | mfasman95/HTTP-API-assignmentt | a76d72f283960e2c88fe2a1d7ad0335445c502f1 | [
"MIT"
] | null | null | null | import extend from 'extend';
// Set initial application state
const initialState = {};
// Handle actions dispatched to the reducer
const actionHandlers = {
ENTER_BOARD: (returnState, action) => {
const rs = returnState;
// Set the new page value
rs.board = action.board;
return rs;
},
LEAVE_BOARD: (returnState) => {
const rs = returnState;
// Set the new page value
delete rs.board;
return rs;
},
UPDATE_TODO: (returnState, action) => {
const rs = returnState;
// Add the received toDo to the board
rs.board.toDos[action.toDo.digest] = action.toDo;
return rs;
},
};
// Define my action creators
export const enterBoard = board => ({ type: 'ENTER_BOARD', board });
export const leaveBoard = () => ({ type: 'LEAVE_BOARD' });
export const updateToDo = toDo => ({ type: 'UPDATE_TODO', toDo });
// Export the reducer
export default (state = initialState, action) => {
// Make an object for the return state
const rs = extend(true, {}, state);
// Handle unknown action types
if (!actionHandlers[action.type]) return rs;
// Handle the action dispatched to the reducer, return the updated state
return actionHandlers[action.type](rs, action, state);
};
| 24.6 | 74 | 0.665041 |
6fdda44481ae401edeef11885805a0feb19e67fa | 212 | js | JavaScript | index.js | ariutta/ariutta-loading | 5dc176ad9a54054e2faa236c627861a846005cf5 | [
"Apache-2.0"
] | null | null | null | index.js | ariutta/ariutta-loading | 5dc176ad9a54054e2faa236c627861a846005cf5 | [
"Apache-2.0"
] | null | null | null | index.js | ariutta/ariutta-loading | 5dc176ad9a54054e2faa236c627861a846005cf5 | [
"Apache-2.0"
] | null | null | null | 'use strict';
var fs = require('fs');
var insertCss = require('insert-css');
module.exports = (function() {
var css = [
fs.readFileSync(__dirname + '/ariutta-loading.css')
];
css.map(insertCss);
})();
| 19.272727 | 55 | 0.627358 |
6fddae20b8e54ee78216e7470e03f2ff54b44a27 | 6,453 | js | JavaScript | src/components/menu/menu-item/menu-item.style.js | liam-cochrane/carbon | 09a244ec004462e7ef7d4a6da9c097e36b3ab70c | [
"Apache-2.0"
] | null | null | null | src/components/menu/menu-item/menu-item.style.js | liam-cochrane/carbon | 09a244ec004462e7ef7d4a6da9c097e36b3ab70c | [
"Apache-2.0"
] | null | null | null | src/components/menu/menu-item/menu-item.style.js | liam-cochrane/carbon | 09a244ec004462e7ef7d4a6da9c097e36b3ab70c | [
"Apache-2.0"
] | null | null | null | import styled, { css } from "styled-components";
import { baseTheme } from "../../../style/themes";
import LinkStyle from "../../link/link.style";
import IconStyle from "../../icon/icon.style";
const StyledMenuItemWrapper = styled.a`
${({
menuType,
theme,
selected,
hasSubmenu,
isOpen,
variant,
showDropdownArrow,
isSearch,
href,
clickToOpen,
maxWidth,
inFullscreenView,
as,
}) => css`
display: inline-block;
font-size: 14px;
font-weight: 700;
height: 40px;
position: relative;
cursor: pointer;
background-color: ${theme.menu.light.background};
${!inFullscreenView &&
css`
max-width: inherit;
a,
button {
${maxWidth &&
css`
box-sizing: border-box;
max-width: inherit;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
vertical-align: bottom;
`}
}
`}
&& a:focus,
&& button:focus {
outline: none;
box-shadow: inset 0 0 0 2px ${theme.colors.focus};
background: ${theme.colors.primary};
color: ${theme.colors.white};
z-index: 1;
position: relative;
[data-component="icon"] {
color: ${theme.colors.white};
}
}
a,
${LinkStyle} a,
button,
${LinkStyle} button {
padding: 0 16px;
}
button,
${LinkStyle} button {
line-height: 40px;
height: 40px;
margin: 0px;
text-align: left;
}
a,
button,
[data-component="icon"],
${LinkStyle} a,
${LinkStyle} button,
${LinkStyle} [data-component="icon"] {
font-weight: 700;
text-decoration: none;
color: ${theme.colors.black};
}
a:hover,
a:focus,
button:hover,
button:focus {
color: ${theme.colors.white};
background: transparent;
}
a:focus,
button:focus,
${LinkStyle} a:focus,
${LinkStyle} button:focus {
color: ${theme.colors.white};
box-shadow: inset 0 0 0 2px ${theme.colors.focus};
background: ${theme.colors.primary};
z-index: 1;
position: relative;
}
${IconStyle} {
bottom: 1px;
}
:hover {
background: ${theme.colors.primary};
a,
button,
[data-component="icon"] {
color: ${theme.colors.white};
}
}
${variant === "alternate" &&
css`
&&& {
background-color: ${theme.menu.light.background};
}
`}
${selected &&
css`
background-color: ${theme.menu.light.selected};
`}
${menuType === "dark" &&
css`
background-color: ${theme.colors.slate};
color: ${theme.colors.white};
a,
a:hover,
a:focus,
button,
button:hover,
[data-component="icon"],
${LinkStyle} [data-component="icon"] {
font-weight: 700;
text-decoration: none;
color: ${theme.colors.white};
background-color: transparent;
}
${selected &&
css`
background-color: ${theme.menu.dark.selected};
`}
[data-component='icon'] {
color: ${theme.colors.white};
}
${hasSubmenu &&
css`
${!href &&
css`
&& a:hover,
&& button:hover {
background-color: ${theme.menu.dark.submenuBackground};
color: ${theme.colors.white};
[data-component="icon"] {
color: ${theme.colors.white};
}
}
&& a:focus,
&& button:focus {
background-color: ${theme.menu.dark.submenuBackground};
color: ${theme.colors.white};
a,
button,
[data-component="icon"] {
color: ${theme.colors.white};
}
}
`}
${isOpen &&
css`
background-color: ${theme.menu.dark.submenuBackground};
color: ${theme.colors.white};
`}
`}
${variant === "alternate" &&
css`
&&& {
background-color: ${theme.colors.slate};
}
`}
`}
${hasSubmenu &&
css`
a:hover,
button:hover {
${!(href || clickToOpen) &&
css`
cursor: default;
`}
}
${menuType === "light" &&
css`
${!href &&
css`
&& a:hover,
&& b:hover {
background-color: ${theme.colors.white};
color: ${theme.colors.black};
[data-component="icon"] {
color: ${theme.colors.black};
}
}
&& a:focus,
&& button:focus {
background-color: ${theme.colors.white};
color: ${theme.colors.black};
a,
button,
[data-component="icon"] {
color: ${theme.colors.black};
}
}
`}
${isOpen &&
css`
background-color: ${theme.colors.white};
color: ${theme.colors.black};
`}
`}
${showDropdownArrow &&
css`
> a,
> button {
padding-right: 32px;
${href &&
css`
&:hover::before,
&:focus::before {
border-top-color: ${theme.colors.white};
}
`}
}
a::before,
button::before {
display: block;
margin-top: -2px;
pointer-events: none;
position: absolute;
right: 16px;
top: 50%;
z-index: 2;
content: "";
width: 0;
height: 0;
border-top: 5px solid
${menuType !== "dark" ? theme.colors.slate : theme.colors.white};
border-right: 4px solid transparent;
border-bottom: 4px solid transparent;
border-left: 4px solid transparent;
}
`};
`}
${isSearch &&
css`
padding: 2px 16px;
`}
${inFullscreenView &&
css`
${as === "div" &&
css`
width: 100vw;
cursor: default;
padding: 0 16px;
:hover {
background: transparent;
}
`}
a,
${LinkStyle} a,
button,
${LinkStyle} button {
width: 100vw;
box-sizing: border-box;
}
`}
`}
`;
StyledMenuItemWrapper.defaultProps = {
theme: baseTheme,
};
export default StyledMenuItemWrapper;
| 20.420886 | 77 | 0.477607 |
6fddbb34e92a23d5d1070cad7d9051332e2fab21 | 703 | js | JavaScript | server/src/routes.js | Hayato9203/imooc_fullstatck | b6aea73bed137c6918144a2e2572e230dbe065fd | [
"MIT"
] | null | null | null | server/src/routes.js | Hayato9203/imooc_fullstatck | b6aea73bed137c6918144a2e2572e230dbe065fd | [
"MIT"
] | null | null | null | server/src/routes.js | Hayato9203/imooc_fullstatck | b6aea73bed137c6918144a2e2572e230dbe065fd | [
"MIT"
] | null | null | null | // 集中处理从client端过来的请求
const GoodsController = require('./controllers/GoodsController')
const CartController = require('./controllers/CartController')
const AuthenticationController = require('./controllers/AuthenticationController')
const isAuthenticated = require('./policies/isAuthenticated')
// 将下面的server路由请求暴露一个名为app的模块
module.exports = (app) => {
app.get('/goods', GoodsController.index)
// app.get('/goods/:page', GoodsController.index)
app.post('/addcart',
isAuthenticated,
CartController.post)
app.post('/login',
AuthenticationController.login)
app.get('/checkout',
isAuthenticated,
CartController.checkout)
// app.post('/a',
// AuthenticationController.a)
}
| 33.47619 | 82 | 0.742532 |
6fde00ddfcd93e8782fe8f8dd2809d2bf9b37126 | 7,399 | js | JavaScript | couchdb/homework/_design/status/_list/complex.js | ICT-Infer/DDU | 8feed71a4cd652650749f875cc9ef135cbe79248 | [
"0BSD"
] | null | null | null | couchdb/homework/_design/status/_list/complex.js | ICT-Infer/DDU | 8feed71a4cd652650749f875cc9ef135cbe79248 | [
"0BSD"
] | 1 | 2016-10-26T16:16:43.000Z | 2016-10-26T17:41:24.000Z | couchdb/homework/_design/status/_list/complex.js | ICT-Infer/DDU | 8feed71a4cd652650749f875cc9ef135cbe79248 | [
"0BSD"
] | null | null | null | /*
* Copyright (c) 2016, 2017 Erik Nordstrøm <erikn@ict-infer.no>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
function validate_query_params (query)
{
qks_allowed = ['semester', 'course'].sort();
qks = [];
function err_inv_req_param ()
{
err = "<p>Query string contains an invalid "
+ "query parameter. Allowed "
+ "parameters are:</p>";
err += "<ul>";
for (i = 0 ; i < qks_allowed.length ; i++)
{
err += "<li>" + qks_allowed[i];
}
err += "</ul>";
return err;
}
for (qk in query)
{
if (query.hasOwnProperty(qk))
{
qks.push(qk);
}
}
qks = qks.sort();
if (qks.length > qks_allowed.length)
{
return err_inv_req_param();
}
i = 0;
j = 0;
while (i < qks.length && j < qks_allowed.length)
{
while (qks_allowed[j] < qks[i] && j < qks_allowed.length)
{
j++;
}
if (qks_allowed[j] !== qks[i])
{
return err_inv_req_param();
}
i++;
}
if (query.semester && !query.semester.match(
/^([0-9]{4,})\/(autumn|spring)$/))
{
return "<p>Invalid semester format.</p>";
}
if (query.course && !query.course.match(
/^([A-Z]{3,4})([0-9]{2}|[0-9]{4})([A-Z])?$/))
{
return "<p>Invalid course format.</p>";
}
}
function(head, req)
{
provides("html", function ()
{
if (err = validate_query_params(req.query))
{
return err;
}
function sname (semid)
{
sparts = semid.split('/');
return sparts[1].charAt(0).toUpperCase()
+ sparts[1].slice(1) + " " + sparts[0];
}
title = "DDU";
snamev = "";
if (req.query.semester)
{
snamev = sname(req.query.semester);
title = snamev + " - " + title;
}
html = "<!DOCTYPE html><html lang=en><head><title>"
+ title + "</title>";
html += "<style>"
+ "meter"
+ "{"
+ "-webkit-appearance: none;"
+ "-moz-appearance: none;"
+ "appearance: none;"
+ "background: lightgrey;"
+ "}"
+ "meter:-moz-meter-optimum::-moz-meter-bar"
+ "{"
+ "background: green;"
+ "}"
+ "meter:-moz-meter-sub-optimum::-moz-meter-bar"
+ "{"
+ "background: yellow;"
+ "}"
+ "meter::-webkit-meter-bar"
+ "{"
+ "background: lightgrey;"
+ "}"
+ "#type-4 meter:-moz-meter-sub-optimum::-moz-meter-bar"
+ "{"
+ "background: red;"
+ "}"
+ "meter::-webkit-meter-optimum-value"
+ "{"
+ "background: green;"
+ "}"
+ "meter::-webkit-meter-suboptimum-value"
+ "{"
+ "background: yellow;"
+ "}"
+ "#type-4 meter::-webkit-meter-suboptimum-value"
+ "{"
+ "background: red;"
+ "}"
+"</style>";
html += "</head>";
//html += "<p>" + JSON.stringify(req) + "</p>";
function htmltime (datearr)
{
var ts = new Date(Date.UTC(datearr[0],
datearr[1] - 1, datearr[2],
datearr[3], datearr[4]))
.toISOString();
return "<time datetime=" + ts + ">" + ts + "</time>";
}
function querystr (qobj)
{
qcount = 0;
qparams = ["semester", "course"];
qstr = "";
for (i = 0 ; i < qparams.length ; i++)
{
qparam = qparams[i];
if (qparam in qobj)
{
qstr += (!qcount ? "?" : "&");
qstr += qparam + "=" + qobj[qparam];
qcount++;
}
}
return qstr;
}
function trv_casol (vd)
{
return "<td>"
+ (vd.has_solution_published ? "Yes" : "No")
+ "</td>";
}
function trv_cadu (vd)
{
return "<td>" + htmltime(vd.due) + "</td>";
}
function trv_casde (vd)
{
return trv_casol(vd)
+ "<td>" + htmltime(vd.delivered) + "</td>";
}
function trv_cass (vd)
{
frag = "";
frag += trv_casol(vd);
if (vd.score_frac)
{
frag += "<td><meter min=0"
+ " max=" + vd.score_frac[1]
+ " optimum=" + vd.score_frac[1]
+ " low=" + vd.score_frac[1]
+ " value=" + vd.score_frac[0] + ">"
+ vd.score_pct
+ "</meter></td>";
}
else if (vd.not_graded)
{
frag += "<td>?</td>";
}
else
{
frag += "<td>N/A</td>";
}
return frag;
}
function trv_casdu (vd)
{
return trv_casol(vd) + trv_cadu(vd);
}
function tr (trv, row)
{
frag = "";
vd = row.value; // View-provided data.
frag += "<tr>";
changeq = {};
if (req.query.course)
{
changeq.course = req.query.course;
}
if (req.query.semester)
{
changeq.semester = req.query.semester;
}
if (!req.query.semester)
{
changeq.semester = vd.semester;
frag += "<td><a href='"
+ req.raw_path.split('?')[0]
+ querystr(changeq) + "'>"
+ sname(vd.semester)
+ "</a></td>";
}
frag += "<td>" + vd.course + "</td>";
frag += "<td><a href=\"" + vd.doc_url + "\">"
+ vd.title + "</a></td>";
frag += trv(vd);
frag += "</tr>";
return frag;
}
function table (first_row, n, title, ths, trv)
{
frag = "";
row = first_row;
count_valid_semester = 0;
if (row && ('key' in row) && row.key[0] === n)
{
frag += "<h2>" + title + "</h2>";
frag += "<table id=type-" + n + ">";
frag += "<thead><tr>" + ths + "</tr></thead>";
frag += "<tbody>";
do
{
if ((req.query.semester
&& req.query.semester
=== row.value.semester)
|| !req.query.semester)
{
frag += tr(trv, row);
count_valid_semester++;
}
row = getRow();
} while (row && ('key' in row)
&& row.key[0] === n)
frag += "</tbody></table>";
if (count_valid_semester)
{
html += frag;
}
}
return row;
}
ths_common = (req.query.semester ? "" : "<th>Semester</th>")
+ "<th>Course</th><th>Assignment</th>";
ths_sol = "<th>Solution Published?</th>";
ths_cadu = ths_common + "<th>Due</th>";
ths_casde = ths_common + ths_sol + "<th>Delivered</th>";
ths_cass = ths_common + ths_sol + "<th>Score</th>";
ths_casdu = ths_common + ths_sol + "<th>Due</th>";
row = getRow();
row = table(row, 0, "Pending delivery", ths_cadu, trv_cadu);
row = table(row, 1, "Pending review", ths_casde, trv_casde);
row = table(row, 2, "Approved", ths_cass, trv_cass);
row = table(row, 4, "Rejected", ths_cass, trv_cass);
row = table(row, 5, "Overdue", ths_casdu, trv_casdu);
html += "<script>"
+ "function twd (num)" // two digits
+ "{"
+ "return ('0' + num).substr(-2);"
+ "}"
+ "function localizedt (d)"
+ "{"
+ "l = new Date(d.getAttribute('datetime'));"
+ "d.textContent = "
+ "twd(l.getMonth() + 1) + '/'"
+ "+ twd(l.getDate()) + ' '"
+ "+ twd(l.getHours()) + ':'"
+ "+ twd(l.getMinutes())"
+ ";"
+ "}"
+ "var ds = document.evaluate('//time',document,null,"
+ "XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,"
+ "null);"
+ "for (var i = 0 ; i < ds.snapshotLength ; i++)"
+ "{"
+ "localizedt(ds.snapshotItem(i));"
+ "}"
+ "</script>";
return html;
});
}
| 20.783708 | 75 | 0.540208 |
6fde3480e71c873892d447c0a6986b22f6d092fb | 1,081 | js | JavaScript | resources/js/store/store.js | hfazlul/blog | 7da65a693e2882d44626d5e34fc0327882356f05 | [
"MIT"
] | 1 | 2020-12-06T05:27:35.000Z | 2020-12-06T05:27:35.000Z | resources/js/store/store.js | hfazlul/blog | 7da65a693e2882d44626d5e34fc0327882356f05 | [
"MIT"
] | null | null | null | resources/js/store/store.js | hfazlul/blog | 7da65a693e2882d44626d5e34fc0327882356f05 | [
"MIT"
] | null | null | null | export default {
state: {
catData: [],
postData: [],
},
getters:{
categories(state){
return state.catData;
},
posts(state){
return state.postData;
}
},
actions: {
getCategories(data){
axios.get("getCategories").then((response)=>{
data.commit("categories",response.data.categories);
}).catch((error)=>{
})
},
getActiveCategories(data){
axios.get("getActiveCategories").then((response)=>{
data.commit("categories",response.data.categories);
}).catch((error)=>{
})
},
getPosts(data){
axios.get("getPosts").then((response)=>{
data.commit("posts",response.data.posts);
}).catch((error)=>{
})
}
},
mutations: {
categories(state,data){
return state.catData = data;
},
posts(state,data){
return state.postData = data;
}
},
};
| 20.396226 | 65 | 0.456984 |
6fde51e02f6d3dec767e8638b1966bd9736cdbee | 1,774 | js | JavaScript | src/utils/shortcodes.js | jasperro/jasperro-website | 0b6fc277c668596314f4c11b0a0ada1e1c9821b5 | [
"0BSD"
] | 3 | 2020-06-23T17:46:22.000Z | 2021-02-01T18:51:15.000Z | src/utils/shortcodes.js | jasperro/jasperro-website | 0b6fc277c668596314f4c11b0a0ada1e1c9821b5 | [
"0BSD"
] | 5 | 2021-02-05T08:45:08.000Z | 2021-06-08T16:17:19.000Z | src/utils/shortcodes.js | jasperro/jasperro-website | 0b6fc277c668596314f4c11b0a0ada1e1c9821b5 | [
"0BSD"
] | null | null | null | const fs = require("fs");
const Image = require("@11ty/eleventy-img");
module.exports = {
icon: function (name, size = "small", rest, inline = true) {
const iconsprites = "/assets/icons/icons.sprite.svg";
const iconid = `#icon-${name}`;
const href = inline ? iconid : `${iconsprites}${iconid}`;
let classList = "w-6 h-6";
switch (size) {
case "medium":
classList = "w-9 h-9";
break;
case "smaller":
classList = "w-5 h-5";
break;
}
return `<svg class="icon ${classList}" role="img" ${rest}>
<title>${name}</title>
<use href="${href}"></use>
</svg>`;
},
iconsprites: function () {
const iconsprites = `${__dirname}/../../dist/assets/icons/icons.sprite.svg`;
const data = fs.readFileSync(iconsprites, (err, data) => {
if (err) {
throw new Error(err);
}
});
return `
<div class="nodispsvg" aria-hidden="true">
${data}
</div>
`;
},
image: async function (cls, src, alt, sizes = [300, 600]) {
let metadata = await Image(`src/${src}`, {
widths: [300, 600],
formats: ["avif", "webp", "jpeg"],
outputDir: "dist/assets/images/",
urlPath: "/assets/images",
});
let imageAttributes = {
class: cls,
alt,
sizes,
loading: "lazy",
decoding: "async",
};
// You bet we throw an error on missing alt in `imageAttributes` (alt="" works okay)
return Image.generateHTML(metadata, imageAttributes);
},
};
| 31.122807 | 92 | 0.470124 |
6fdea379409ddbe8ef6c20a21d96ef610efcd3cc | 1,257 | js | JavaScript | app/scripts/directives/nobeProjectModal/nobeProjectModal.js | gruan/NOBEIllinois-Website | e6fbd3d80a499102b9a25c155f04eb754be68e93 | [
"MIT"
] | null | null | null | app/scripts/directives/nobeProjectModal/nobeProjectModal.js | gruan/NOBEIllinois-Website | e6fbd3d80a499102b9a25c155f04eb754be68e93 | [
"MIT"
] | null | null | null | app/scripts/directives/nobeProjectModal/nobeProjectModal.js | gruan/NOBEIllinois-Website | e6fbd3d80a499102b9a25c155f04eb754be68e93 | [
"MIT"
] | null | null | null | /**
* Created by George Ruan on July 3, 2016.
*
* nobeProjectModal defines the appearance and functionality of
* the project modal.
*/
(function() {
'use strict';
angular.module('nobe')
.directive('nobeProjectModal', nobeProjectModal);
nobeProjectModal.$inject = ['$timeout', 'nobeWindowData'];
function nobeProjectModal($timeout, nobeWindowData) {
var directive;
directive = {
link: link,
restrict: 'E',
scope: {
team: '='
},
templateUrl: 'scripts/directives/nobeProjectModal/nobeProjectModal.html'
};
return directive;
function link(scope) {
var isCurrentModalOpen = false;
function isModalOpen() {
return isCurrentModalOpen;
}
function openModal() {
isCurrentModalOpen = true;
nobeWindowData.setIsModalOpen(true);
}
function closeModal() {
isCurrentModalOpen = false;
nobeWindowData.setIsModalOpen(false);
}
// ==================
// Variables
// ==================
scope.isModalOpen = isModalOpen;
// ==================
// Functions
// ==================
scope.closeModal = closeModal;
scope.openModal = openModal;
}
}
})();
| 20.95 | 78 | 0.566428 |
6fdeee6e592bcad2768ace68a1d01028ce24ca61 | 12,273 | js | JavaScript | docs/html/search/all_8.js | FThompsonAWS/aws-iot-device-sdk-cpp-v2 | 4131533736a47cd82cac38416586cbd8f60f3ccc | [
"Apache-2.0"
] | 88 | 2019-11-29T19:30:29.000Z | 2022-03-28T02:29:51.000Z | docs/html/search/all_8.js | FThompsonAWS/aws-iot-device-sdk-cpp-v2 | 4131533736a47cd82cac38416586cbd8f60f3ccc | [
"Apache-2.0"
] | 194 | 2019-12-01T15:54:42.000Z | 2022-03-31T22:06:11.000Z | docs/html/search/all_8.js | FThompsonAWS/aws-iot-device-sdk-cpp-v2 | 4131533736a47cd82cac38416586cbd8f60f3ccc | [
"Apache-2.0"
] | 64 | 2019-12-17T14:13:40.000Z | 2022-03-12T07:43:13.000Z | var searchData=
[
['has_5fvalue_0',['has_value',['../class_aws_1_1_crt_1_1_optional.html#a4356231bdd8a67fd565f8a8211a2e770',1,'Aws::Crt::Optional']]],
['hash_1',['Hash',['../class_aws_1_1_crt_1_1_crypto_1_1_hash.html',1,'Aws::Crt::Crypto::Hash'],['../class_aws_1_1_crt_1_1_crypto_1_1_hash.html#afcf6014cc28bf7fd3110e1a6dc639367',1,'Aws::Crt::Crypto::Hash::Hash(Hash &&toMove)'],['../class_aws_1_1_crt_1_1_crypto_1_1_hash.html#ac267bbbd6638110b4fa5ad64663f882c',1,'Aws::Crt::Crypto::Hash::Hash(const Hash &)=delete']]],
['hash_2ecpp_2',['Hash.cpp',['../_hash_8cpp.html',1,'']]],
['hash_2eh_3',['Hash.h',['../_hash_8h.html',1,'']]],
['hash_3c_20aws_3a_3acrt_3a_3abasic_5fstring_5fview_3c_20chart_2c_20traits_20_3e_20_3e_4',['hash< Aws::Crt::basic_string_view< CharT, Traits > >',['../structstd_1_1hash_3_01_aws_1_1_crt_1_1basic__string__view_3_01_char_t_00_01_traits_01_4_01_4.html',1,'std']]],
['headerlines_5',['HeaderLines',['../struct_elasticurl_ctx.html#a84c6a13a124d0031542796f3f277ffbe',1,'ElasticurlCtx']]],
['headervaluetype_6',['HeaderValueType',['../namespace_aws_1_1_eventstreamrpc.html#a6a6036d8e92a0a233c2db987e2445d93',1,'Aws::Eventstreamrpc']]],
['help_7',['help',['../namespacecreate-projects.html#a57186536b7a1811230fd299b142617cf',1,'create-projects']]],
['hmac_8',['HMAC',['../class_aws_1_1_crt_1_1_crypto_1_1_h_m_a_c.html',1,'Aws::Crt::Crypto::HMAC'],['../class_aws_1_1_crt_1_1_crypto_1_1_h_m_a_c.html#a0a5ba60e148c376ec88898eb4182bc62',1,'Aws::Crt::Crypto::HMAC::HMAC(HMAC &&toMove)'],['../class_aws_1_1_crt_1_1_crypto_1_1_h_m_a_c.html#a3a39f3c2e4b4c99e1db442211107695c',1,'Aws::Crt::Crypto::HMAC::HMAC(const HMAC &)=delete']]],
['hmac_2ecpp_9',['HMAC.cpp',['../_h_m_a_c_8cpp.html',1,'']]],
['hmac_2eh_10',['HMAC.h',['../_h_m_a_c_8h.html',1,'']]],
['hooks_11',['hooks',['../namespace_aws.html#a57ce4f2b5c9bd06f9c6e1f6c00e31315',1,'Aws::hooks()'],['../struct_aws_1_1printbuffer.html#ad8f8ebc3108605383f793ee2d5cb6732',1,'Aws::printbuffer::hooks()'],['../struct_aws_1_1parse__buffer.html#a8f0335e19fdfc545034d9a5156b61815',1,'Aws::parse_buffer::hooks()']]],
['hostaddress_12',['HostAddress',['../namespace_aws_1_1_crt_1_1_io.html#a74f2659525c59a6d43f579af6586a1ce',1,'Aws::Crt::Io::HostAddress()'],['../class_aws_1_1_discovery_1_1_connectivity_info.html#aad735b25e284bf2a861ed5e5af1fa307',1,'Aws::Discovery::ConnectivityInfo::HostAddress()']]],
['hostname_13',['HostName',['../class_aws_1_1_crt_1_1_http_1_1_http_client_connection_options.html#ad010ce92d39b0393991f6bbbd13fd365',1,'Aws::Crt::Http::HttpClientConnectionOptions::HostName()'],['../class_aws_1_1_crt_1_1_http_1_1_http_client_connection_proxy_options.html#adc029eaab5556579b1fd3e5f99e4b445',1,'Aws::Crt::Http::HttpClientConnectionProxyOptions::HostName()']]],
['hostresolver_14',['HostResolver',['../class_aws_1_1_crt_1_1_io_1_1_host_resolver.html',1,'Aws::Crt::Io']]],
['hostresolver_2ecpp_15',['HostResolver.cpp',['../_host_resolver_8cpp.html',1,'']]],
['hostresolver_2eh_16',['HostResolver.h',['../_host_resolver_8h.html',1,'']]],
['http1_5f0_17',['Http1_0',['../namespace_aws_1_1_crt_1_1_http.html#afba23b4ec95a8d1b95d18b2ffe5d82e5aa820a7cca3410e94af1e51058023680a',1,'Aws::Crt::Http']]],
['http1_5f1_18',['Http1_1',['../namespace_aws_1_1_crt_1_1_http.html#afba23b4ec95a8d1b95d18b2ffe5d82e5a2c494112f4c9bef921aacd3650fd34ea',1,'Aws::Crt::Http']]],
['http2_19',['Http2',['../namespace_aws_1_1_crt_1_1_http.html#afba23b4ec95a8d1b95d18b2ffe5d82e5ab354a53a47e18f05f6cc27c7259e0791',1,'Aws::Crt::Http']]],
['httpclientconnection_20',['HttpClientConnection',['../class_aws_1_1_crt_1_1_http_1_1_http_client_connection.html',1,'Aws::Crt::Http::HttpClientConnection'],['../class_aws_1_1_crt_1_1_http_1_1_http_stream.html#a11a38cfaaeb753536df9e6ccb846d5d1',1,'Aws::Crt::Http::HttpStream::HttpClientConnection()'],['../class_aws_1_1_crt_1_1_http_1_1_http_client_stream.html#a11a38cfaaeb753536df9e6ccb846d5d1',1,'Aws::Crt::Http::HttpClientStream::HttpClientConnection()'],['../class_aws_1_1_crt_1_1_http_1_1_http_client_connection.html#ad96d1be1fc1f4408ba917cbc7e0b2ff9',1,'Aws::Crt::Http::HttpClientConnection::HttpClientConnection(const HttpClientConnection &)=delete'],['../class_aws_1_1_crt_1_1_http_1_1_http_client_connection.html#af6038bf3963a4eb3cd20971e3685bf06',1,'Aws::Crt::Http::HttpClientConnection::HttpClientConnection(HttpClientConnection &&)=delete'],['../class_aws_1_1_crt_1_1_http_1_1_http_client_connection.html#a171692c127a7fddec5e525c95a9e1a77',1,'Aws::Crt::Http::HttpClientConnection::HttpClientConnection(aws_http_connection *m_connection, Allocator *allocator) noexcept']]],
['httpclientconnectionmanager_21',['HttpClientConnectionManager',['../class_aws_1_1_crt_1_1_http_1_1_http_client_connection_manager.html',1,'Aws::Crt::Http']]],
['httpclientconnectionmanageroptions_22',['HttpClientConnectionManagerOptions',['../class_aws_1_1_crt_1_1_http_1_1_http_client_connection_manager_options.html',1,'Aws::Crt::Http::HttpClientConnectionManagerOptions'],['../class_aws_1_1_crt_1_1_http_1_1_http_client_connection_manager_options.html#a2205486e0c63e9ccf85c9b611859f69a',1,'Aws::Crt::Http::HttpClientConnectionManagerOptions::HttpClientConnectionManagerOptions() noexcept'],['../class_aws_1_1_crt_1_1_http_1_1_http_client_connection_manager_options.html#ae9d7c43df048a3ed7d58cfe174fda598',1,'Aws::Crt::Http::HttpClientConnectionManagerOptions::HttpClientConnectionManagerOptions(const HttpClientConnectionManagerOptions &rhs)=default'],['../class_aws_1_1_crt_1_1_http_1_1_http_client_connection_manager_options.html#ad0b12376571150ca1733de2e470ed2dc',1,'Aws::Crt::Http::HttpClientConnectionManagerOptions::HttpClientConnectionManagerOptions(HttpClientConnectionManagerOptions &&rhs)=default']]],
['httpclientconnectionoptions_23',['HttpClientConnectionOptions',['../class_aws_1_1_crt_1_1_http_1_1_http_client_connection_options.html',1,'Aws::Crt::Http::HttpClientConnectionOptions'],['../class_aws_1_1_crt_1_1_http_1_1_http_client_connection_options.html#add59a5797e4e5e5fa647cb2edcdb18f1',1,'Aws::Crt::Http::HttpClientConnectionOptions::HttpClientConnectionOptions()'],['../class_aws_1_1_crt_1_1_http_1_1_http_client_connection_options.html#a85def7033733798127c195cd5292a546',1,'Aws::Crt::Http::HttpClientConnectionOptions::HttpClientConnectionOptions(const HttpClientConnectionOptions &rhs)=default'],['../class_aws_1_1_crt_1_1_http_1_1_http_client_connection_options.html#a354652aa2b41fb329b6c52828dc3b8a6',1,'Aws::Crt::Http::HttpClientConnectionOptions::HttpClientConnectionOptions(HttpClientConnectionOptions &&rhs)=default']]],
['httpclientconnectionproxyoptions_24',['HttpClientConnectionProxyOptions',['../class_aws_1_1_crt_1_1_http_1_1_http_client_connection_proxy_options.html',1,'Aws::Crt::Http::HttpClientConnectionProxyOptions'],['../class_aws_1_1_crt_1_1_http_1_1_http_client_connection_proxy_options.html#a586bc6d411173e88d7aaf43d80160ddc',1,'Aws::Crt::Http::HttpClientConnectionProxyOptions::HttpClientConnectionProxyOptions(HttpClientConnectionProxyOptions &&rhs)=default'],['../class_aws_1_1_crt_1_1_http_1_1_http_client_connection_proxy_options.html#a2df2a2e0c68c5c3697d4578cde419fdd',1,'Aws::Crt::Http::HttpClientConnectionProxyOptions::HttpClientConnectionProxyOptions()'],['../class_aws_1_1_crt_1_1_http_1_1_http_client_connection_proxy_options.html#a53a23991783977c5cc1067895c403e87',1,'Aws::Crt::Http::HttpClientConnectionProxyOptions::HttpClientConnectionProxyOptions(const HttpClientConnectionProxyOptions &rhs)=default']]],
['httpclientstream_25',['HttpClientStream',['../class_aws_1_1_crt_1_1_http_1_1_http_client_stream.html',1,'Aws::Crt::Http::HttpClientStream'],['../class_aws_1_1_crt_1_1_http_1_1_http_client_stream.html#aae664d9de8102f460c81d97fd8f1c68d',1,'Aws::Crt::Http::HttpClientStream::HttpClientStream(HttpClientStream &&)=delete'],['../class_aws_1_1_crt_1_1_http_1_1_http_client_stream.html#a94182540a8d5bc5dbedc4b14becb9b44',1,'Aws::Crt::Http::HttpClientStream::HttpClientStream(const HttpClientStream &)=delete']]],
['httpconnection_2ecpp_26',['HttpConnection.cpp',['../_http_connection_8cpp.html',1,'']]],
['httpconnection_2eh_27',['HttpConnection.h',['../_http_connection_8h.html',1,'']]],
['httpconnectionmanager_2ecpp_28',['HttpConnectionManager.cpp',['../_http_connection_manager_8cpp.html',1,'']]],
['httpconnectionmanager_2eh_29',['HttpConnectionManager.h',['../_http_connection_manager_8h.html',1,'']]],
['httpheader_30',['HttpHeader',['../namespace_aws_1_1_crt_1_1_http.html#a06495cd28f64029ef3dbd3b831d7b932',1,'Aws::Crt::Http']]],
['httpmessage_31',['HttpMessage',['../class_aws_1_1_crt_1_1_http_1_1_http_message.html',1,'Aws::Crt::Http::HttpMessage'],['../class_aws_1_1_crt_1_1_http_1_1_http_message.html#afa6b9734bc57422fa525f2987a6b138f',1,'Aws::Crt::Http::HttpMessage::HttpMessage(const HttpMessage &)=delete'],['../class_aws_1_1_crt_1_1_http_1_1_http_message.html#a1eeebdf7b88ab5e83cd01832059deddb',1,'Aws::Crt::Http::HttpMessage::HttpMessage(HttpMessage &&)=delete'],['../class_aws_1_1_crt_1_1_http_1_1_http_message.html#a75cee96cacf100b5b8ed2f5c927dea74',1,'Aws::Crt::Http::HttpMessage::HttpMessage(Allocator *allocator, struct aws_http_message *message) noexcept']]],
['httprequest_32',['HttpRequest',['../class_aws_1_1_crt_1_1_http_1_1_http_request.html',1,'Aws::Crt::Http::HttpRequest'],['../class_aws_1_1_crt_1_1_http_1_1_http_request.html#a7039637f9bcff8daed59338abf26f9d2',1,'Aws::Crt::Http::HttpRequest::HttpRequest(Allocator *allocator=g_allocator)'],['../class_aws_1_1_crt_1_1_http_1_1_http_request.html#a48f1025c071bb810bd18c2ea4291e51b',1,'Aws::Crt::Http::HttpRequest::HttpRequest(Allocator *allocator, struct aws_http_message *message)']]],
['httprequestchunk_33',['HttpRequestChunk',['../namespace_aws_1_1_crt_1_1_auth.html#ae5eec67d027b78e622d984a5df341a66ac6cce716eaa16c90a4693f80a2c1be98',1,'Aws::Crt::Auth']]],
['httprequestevent_34',['HttpRequestEvent',['../namespace_aws_1_1_crt_1_1_auth.html#ae5eec67d027b78e622d984a5df341a66ae684026d77ab12fff8d64337f2311223',1,'Aws::Crt::Auth']]],
['httprequestoptions_35',['HttpRequestOptions',['../struct_aws_1_1_crt_1_1_http_1_1_http_request_options.html',1,'Aws::Crt::Http']]],
['httprequestresponse_2ecpp_36',['HttpRequestResponse.cpp',['../_http_request_response_8cpp.html',1,'']]],
['httprequestresponse_2eh_37',['HttpRequestResponse.h',['../_http_request_response_8h.html',1,'']]],
['httprequestviaheaders_38',['HttpRequestViaHeaders',['../namespace_aws_1_1_crt_1_1_auth.html#ae5eec67d027b78e622d984a5df341a66a005f325e8aacc46033d82eab96a23abc',1,'Aws::Crt::Auth']]],
['httprequestviaqueryparams_39',['HttpRequestViaQueryParams',['../namespace_aws_1_1_crt_1_1_auth.html#ae5eec67d027b78e622d984a5df341a66a49cd1621053c174a1e837870a0145b68',1,'Aws::Crt::Auth']]],
['httpresponse_40',['HttpResponse',['../class_aws_1_1_crt_1_1_http_1_1_http_response.html',1,'Aws::Crt::Http::HttpResponse'],['../class_aws_1_1_crt_1_1_http_1_1_http_response.html#ae076e75000fb0aca4690163eab8d8b08',1,'Aws::Crt::Http::HttpResponse::HttpResponse()']]],
['httpsignercallbackdata_41',['HttpSignerCallbackData',['../struct_aws_1_1_crt_1_1_auth_1_1_http_signer_callback_data.html',1,'Aws::Crt::Auth::HttpSignerCallbackData'],['../struct_aws_1_1_crt_1_1_auth_1_1_http_signer_callback_data.html#a263fb710c38bbaa224f751fe04374379',1,'Aws::Crt::Auth::HttpSignerCallbackData::HttpSignerCallbackData()']]],
['httpstream_42',['HttpStream',['../class_aws_1_1_crt_1_1_http_1_1_http_stream.html',1,'Aws::Crt::Http::HttpStream'],['../class_aws_1_1_crt_1_1_http_1_1_http_stream.html#a08fe714047c2b89382f6ed4a99cbfb69',1,'Aws::Crt::Http::HttpStream::HttpStream(const HttpStream &)=delete'],['../class_aws_1_1_crt_1_1_http_1_1_http_stream.html#a731d454b2bd3fcc030a9ab81faefe462',1,'Aws::Crt::Http::HttpStream::HttpStream(HttpStream &&)=delete'],['../class_aws_1_1_crt_1_1_http_1_1_http_stream.html#ab05c6def1a28d56238a55b888fbac4ae',1,'Aws::Crt::Http::HttpStream::HttpStream(const std::shared_ptr< HttpClientConnection > &connection) noexcept']]],
['httpversion_43',['HttpVersion',['../namespace_aws_1_1_crt_1_1_http.html#afba23b4ec95a8d1b95d18b2ffe5d82e5',1,'Aws::Crt::Http']]]
];
| 255.6875 | 1,099 | 0.813493 |
6fdf18393edb9ce149a2ea54a14288997fd68af2 | 11,633 | js | JavaScript | js/jquery.windows-engine.js | vitt76/majordomo | 0fdd61b440087c6185b5c074f9b78a657b5be36f | [
"MIT"
] | 1 | 2019-07-09T11:06:34.000Z | 2019-07-09T11:06:34.000Z | js/jquery.windows-engine.js | vitt76/majordomo | 0fdd61b440087c6185b5c074f9b78a657b5be36f | [
"MIT"
] | null | null | null | js/jquery.windows-engine.js | vitt76/majordomo | 0fdd61b440087c6185b5c074f9b78a657b5be36f | [
"MIT"
] | 1 | 2017-05-28T09:58:36.000Z | 2017-05-28T09:58:36.000Z | /**
* jQuery Windows Engine Plugin
* @requires jQuery v1.2.6 or greater
* http://hernan.amiune.com/labs
*
* Copyright(c) Hernan Amiune (hernan.amiune.com)
* Licensed under MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Version: 1.3
*/
var jqWindowsEngineZIndex = 100;
jQuery.extend({
newWindow: function(options) {
var lastMouseX = 0;
var lastMouseY = 0;
var defaults = {
id: "",
title: "",
width: 300,
height: 200,
posx: 50,
posy: 50,
content: "",
onDragBegin: null,
onDragEnd: null,
onResizeBegin: null,
onResizeEnd: null,
onAjaxContentLoaded: null,
onWindowClose: null,
statusBar: true,
minimizeButton: true,
maximizeButton: true,
closeButton: true,
draggable: true,
resizeable: true,
type: "normal"
};
var options = $.extend(defaults, options);
var idAttr = "";
if (options.id != "") idAttr = 'id="' + options.id + '"';
if (options.id != "") idAttr = 'id="' + options.id + '"';
$windowContainer = $('<div ' + idAttr + ' class="window-container"></div>');
$titleBar = $('<div class="window-titleBar"></div>');
$titleBar.append('<div class="window-titleBar-leftCorner"></div>');
$titleBarContent = $('<div class="window-titleBar-content">' + options.title + '</div>');
$titleBar.append($titleBarContent);
$titleBar.append('<div class="window-titleBar-rightCorner"></div>');
$windowMinimizeButton = $('<div class="window-minimizeButton"></div>');
$windowMaximizeButton = $('<div class="window-maximizeButton"></div>');
$windowCloseButton = $('<div class="window-closeButton"></div>');
$windowContent = $('<div class="window-content"></div>');
$windowStatusBar = $('<div class="window-statusBar"></div>');
$windowResizeIcon = $('<div class="window-resizeIcon"></div>');
if (options.minimizeButton) $titleBar.append($windowMinimizeButton);
if (options.maximizeButton) $titleBar.append($windowMaximizeButton);
if (options.closeButton) $titleBar.append($windowCloseButton);
if (options.resizeable) $windowStatusBar.append($windowResizeIcon);
$windowContainer.append($titleBar);
$windowContent.append(options.content);
$windowContainer.append($windowContent);
if (options.statusBar) $windowContainer.append($windowStatusBar);
if(options.type === "iframe"){
$windowContent.css("overflow","hidden");
}
var setFocus = function($obj) {
$obj.css("z-index", jqWindowsEngineZIndex++);
}
var resize = function($obj, width, height) {
width = parseInt(width);
height = parseInt(height);
$obj.data("lastWidth", width).data("lastHeight", height);
$obj.css("width", width + "px").css("height", height + "px");
if (options.type === "iframe") {
$obj.find("iframe").css("width", (width-3) + "px").css("height", (height-2) + "px");
}
}
var move = function($obj, x, y) {
x = parseInt(x);
y = parseInt(y);
$obj.data("lastX", x).data("lastY", y);
x = x + "px";
y = y + "px";
$obj.css("left", x).css("top", y);
}
var dragging = function(e, $obj) {
if (options.draggable) {
e = e ? e : window.event;
var newx = parseInt($obj.css("left")) + (e.clientX - lastMouseX);
var newy = parseInt($obj.css("top")) + (e.clientY - lastMouseY);
lastMouseX = e.clientX;
lastMouseY = e.clientY;
move($obj, newx, newy);
}
};
var resizing = function(e, $obj) {
e = e ? e : window.event;
var w = parseInt($obj.css("width"));
var h = parseInt($obj.css("height"));
w = w < 100 ? 100 : w;
h = h < 50 ? 50 : h;
var neww = w + (e.clientX - lastMouseX);
var newh = h + (e.clientY - lastMouseY);
lastMouseX = e.clientX;
lastMouseY = e.clientY;
resize($obj, neww, newh);
};
$titleBarContent.bind('mousedown', function(e) {
$obj = $(e.target).parent().parent();
setFocus($obj);
if ($obj.data("state") != "maximized") {
e = e ? e : window.event;
lastMouseX = e.clientX;
lastMouseY = e.clientY;
$(document).bind('mousemove', function(e) {
dragging(e, $obj);
});
$(document).bind('mouseup', function(e) {
if (options.onDragEnd != null) options.onDragEnd();
$(document).unbind('mousemove');
$(document).unbind('mouseup');
});
if (options.onDragBegin != null) options.onDragBegin();
}
});
$titleBarContent.dblclick(function(e) {
$obj = $(e.target).parent().parent();
$obj.find(".window-maximizeButton").click();
});
$windowResizeIcon.bind('mousedown', function(e) {
$obj = $(e.target).parent().parent();
setFocus($obj);
if ($obj.data("state") === "normal") {
e = e ? e : window.event;
lastMouseX = e.clientX;
lastMouseY = e.clientY;
$(document).bind('mousemove', function(e) {
resizing(e, $obj);
});
$(document).bind('mouseup', function(e) {
if (options.onResizeEnd != null) options.onResizeEnd();
$(document).unbind('mousemove');
$(document).unbind('mouseup');
});
if (options.onResizeBegin != null) options.onResizeBegin();
}
});
$windowMinimizeButton.bind('click', function(e) {
$obj = $(e.target).parent().parent();
setFocus($obj);
if ($obj.data("state") === "minimized") {
$obj.data("state", "normal");
$obj.css("height", $obj.data("lastHeight"));
$obj.find(".window-content").slideToggle("slow");
}
else if ($obj.data("state") === "normal") {
$obj.data("state", "minimized");
$obj.find(".window-content").slideToggle("slow", function() { $obj.css("height", 0); });
}
else {
$obj.find(".window-maximizeButton").click();
}
});
$windowMaximizeButton.bind('click', function(e) {
$obj = $(e.target).parent().parent();
setFocus($obj);
if ($obj.data("state") === "minimized") {
$obj.find(".window-minimizeButton").click();
}
else if ($obj.data("state") === "normal") {
$obj.animate({
top: "5px",
left: "5px",
width: $(window).width() - 15,
height: $(window).height() - 45
}, "slow");
if (options.type === "iframe") {
$obj.find("iframe").animate({
top: "5px",
left: "5px",
width: $(window).width() - 15 - 3,
height: $(window).height() - 45 - 2
}, "slow");
}
$obj.data("state", "maximized")
}
else if ($obj.data("state") === "maximized") {
$obj.animate({
top: $obj.data("lastY"),
left: $obj.data("lastX"),
width: $obj.data("lastWidth"),
height: $obj.data("lastHeight")
}, "slow");
if (options.type === "iframe") {
$obj.find("iframe").animate({
top: $obj.data("lastY"),
left: $obj.data("lastX"),
width: parseInt($obj.data("lastWidth") - 3),
height: parseInt($obj.data("lastHeight") - 2)
}, "slow");
}
$obj.data("state", "normal")
}
});
$windowCloseButton.bind('click', function(e) {
var $window = $(e.target).parent().parent();
$window.fadeOut(function() { $window.remove(); });
if (options.onWindowClose != null) options.onWindowClose();
});
$windowContent.click(function(e) {
setFocus($(e.target).parent());
});
$windowStatusBar.click(function(e) {
setFocus($(e.target).parent());
});
$windowContainer.data("state", "normal");
$windowContainer.css("display", "none");
$('body').append($windowContainer);
$window = $windowContainer;
if (!options.draggable) $window.children(".window-titleBar").css("cursor", "default");
setFocus($window);
move($windowContainer, options.posx, options.posy);
resize($windowContainer, options.width, options.height);
$window.fadeIn();
},
updateWindowContent: function(id, newContent) {
$("#" + id + " .window-content").html(newContent);
},
updateWindowContentWithAjax: function(id, url, cache) {
cache = cache === undefined ? true : false;
$.ajax({
url: url,
cache: cache,
dataType: "html",
success: function(data) {
$("#" + id + " .window-content").html(data);
if (options.onAjaxContentLoaded != null) options.onAjaxContentLoaded();
}
});
},
moveWindow: function(id, x, y) {
$obj = $("#" + id);
x = parseInt(x);
y = parseInt(y);
$obj.data("lastX", x).data("lastY", y);
x = x + "px";
y = y + "px";
$obj.css("left", x).css("top", y);
},
resizeWindow: function(id, width, height) {
$obj = $("#" + id);
width = parseInt(width);
height = parseInt(height);
$obj.data("lastWidth", width).data("lastHeight", height);
width = width + "px";
height = height + "px";
$obj.css("width", width).css("height", height);
},
minimizeWindow: function(id) {
$("#" + id + " .window-minimizeButton").click();
},
maximizeWindow: function(id) {
$("#" + id + " .window-maximizeButton").click();
},
showWindow: function(id) {
$("#" + id + " .window-closeButton").fadeIn();
},
hideWindow: function(id) {
$("#" + id + " .window-closeButton").fadeOut();
},
closeWindow: function(id) {
$("#" + id + " .window-closeButton").click();
},
closeAllWindows: function() {
$(".window-container .window-closeButton").click();
}
});
| 35.145015 | 105 | 0.462048 |
6fdf73fd72f0ebea4893702bf8b8f451c8ab1dc0 | 2,537 | js | JavaScript | src/components/App/index.js | suresh4swamy/usermanagement | 06c61980b1d4b50818499c90fe232a620d774e5f | [
"OML"
] | null | null | null | src/components/App/index.js | suresh4swamy/usermanagement | 06c61980b1d4b50818499c90fe232a620d774e5f | [
"OML"
] | 9 | 2020-09-06T09:39:28.000Z | 2022-02-26T14:58:37.000Z | src/components/App/index.js | suresh4swamy/usermanagement | 06c61980b1d4b50818499c90fe232a620d774e5f | [
"OML"
] | null | null | null | import React from 'react';
import {
BrowserRouter as Router,
Route,
Switch,
Redirect,
} from 'react-router-dom';
// import $ from 'jquery';
// import 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/js/bootstrap';
import 'font-awesome/css/font-awesome.css';
import '@emotion/core';
import PrivateRoute from '../RouteFilter';
import Navigation from '../Navigation';
import LandingPage from '../Landing';
import SignUpPage from '../SignUp';
import SignInPage from '../SignIn';
import PasswordForgetPage from '../PasswordForget';
import HomePage from '../Home';
import AccountPage from '../Account';
import AdminPage from '../Admin';
import PersonalDetails from '../PersonalDetails/personalDetails';
import ProductPage, { MyProductPage } from '../Product';
import MyCart, { MyCartContext, MyCartItems } from '../MyCart';
import * as ROUTES from '../../constants/routes';
import { withAuthentication } from '../Session';
import { toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
toast.configure();
// $.something();
const App = props => {
console.log('App Component.');
return (
<MyCartContext.Provider value={MyCartItems.getMyCart()}>
<Router>
<React.Fragment>
<Navigation />
<Switch>
<Route path={ROUTES.SIGN_UP} component={SignUpPage} />
<Route path={ROUTES.SIGN_IN} component={SignInPage} />
<Route
path={ROUTES.PASSWORD_FORGET}
component={PasswordForgetPage}
/>
<PrivateRoute path={ROUTES.HOME} component={HomePage} />
<PrivateRoute
path={ROUTES.ACCOUNT}
component={AccountPage}
/>
<PrivateRoute path={ROUTES.ADMIN} component={AdminPage} />
<PrivateRoute
path={ROUTES.PERSONAL_DETAILS}
component={PersonalDetails}
/>
<Route path={ROUTES.PRODUCTS} component={ProductPage} />
<PrivateRoute
path={ROUTES.MY_PRODUCTS}
component={MyProductPage}
/>
<Route path={ROUTES.MY_CART} component={MyCart} />
<Route
exact
path={ROUTES.LANDING}
component={LandingPage}
/>
<Route render={() => <Redirect to={ROUTES.LANDING} />} />
</Switch>
</React.Fragment>
</Router>
</MyCartContext.Provider>
);
};
export default withAuthentication(App);
| 30.566265 | 70 | 0.610958 |
6fe01dc1b0b49ace62919a48948a22ab9e93ebb2 | 693 | js | JavaScript | src/data/examples/zh-Hans/21_Input/02_Easing.js | Divyansh013/p5.js-website | f0285037f96a5530d55cbdb9fa12bd322c4e94ae | [
"MIT"
] | 248 | 2015-02-16T22:22:42.000Z | 2022-03-28T12:59:56.000Z | src/data/examples/zh-Hans/21_Input/02_Easing.js | Divyansh013/p5.js-website | f0285037f96a5530d55cbdb9fa12bd322c4e94ae | [
"MIT"
] | 1,113 | 2015-02-16T17:17:07.000Z | 2022-03-31T21:13:40.000Z | src/data/examples/zh-Hans/21_Input/02_Easing.js | Divyansh013/p5.js-website | f0285037f96a5530d55cbdb9fa12bd322c4e94ae | [
"MIT"
] | 554 | 2015-02-17T21:43:35.000Z | 2022-03-31T00:15:16.000Z | /*
* @name Easing
* @description Move the mouse across the screen and the symbol
* will follow. Between drawing each frame of the animation, the
* program calculates the difference between the position of the
* symbol and the cursor. If the distance is larger than 1 pixel,
* the symbol moves part of the distance (0.05) from its current
* position toward the cursor.
*/
let x = 1;
let y = 1;
let easing = 0.05;
function setup() {
createCanvas(720, 400);
noStroke();
}
function draw() {
background(237, 34, 93);
let targetX = mouseX;
let dx = targetX - x;
x += dx * easing;
let targetY = mouseY;
let dy = targetY - y;
y += dy * easing;
ellipse(x, y, 66, 66);
}
| 22.354839 | 65 | 0.666667 |
6fe04eb82d08e8e58d769aea9ef1ed3bdf304322 | 174 | js | JavaScript | src/docs/directives/script/scroll.js | ahmadfajar/vue-mdbootstrap-docs | 63e7353f9103b9ef43d1006b03ad5753c6b39398 | [
"BSD-3-Clause"
] | null | null | null | src/docs/directives/script/scroll.js | ahmadfajar/vue-mdbootstrap-docs | 63e7353f9103b9ef43d1006b03ad5753c6b39398 | [
"BSD-3-Clause"
] | null | null | null | src/docs/directives/script/scroll.js | ahmadfajar/vue-mdbootstrap-docs | 63e7353f9103b9ef43d1006b03ad5753c6b39398 | [
"BSD-3-Clause"
] | null | null | null | export default {
data: () => ({
offsetTop: 0,
}),
methods: {
onScroll(el, e) {
this.offsetTop = e.target.scrollTop;
}
}
}
| 15.818182 | 48 | 0.425287 |
6fe0b39adc6ebde70925304fcd70bd40c42c27d6 | 37 | js | JavaScript | crates/swc_ecma_minifier/tests/terser/compress/export/keyword_valid_3/output.terser.js | mengxy/swc | bcc3ae86ae0732979f9fbfef370ae729ba9af080 | [
"Apache-2.0"
] | 21,008 | 2017-04-01T04:06:55.000Z | 2022-03-31T23:11:05.000Z | ecmascript/minifier/tests/terser/compress/export/keyword_valid_3/output.terser.js | sventschui/swc | cd2a2777d9459ba0f67774ed8a37e2b070b51e81 | [
"Apache-2.0",
"MIT"
] | 2,309 | 2018-01-14T05:54:44.000Z | 2022-03-31T15:48:40.000Z | ecmascript/minifier/tests/terser/compress/export/keyword_valid_3/output.terser.js | sventschui/swc | cd2a2777d9459ba0f67774ed8a37e2b070b51e81 | [
"Apache-2.0",
"MIT"
] | 768 | 2018-01-14T05:15:43.000Z | 2022-03-30T11:29:42.000Z | export { default } from "module.js";
| 18.5 | 36 | 0.675676 |
6fe1905e2119a8c9850e453e2af85e9ed0a5967f | 6,589 | js | JavaScript | static/1627814429/amp/100/9/payload.js | mazipan-quran-offline/mazipan-quran-offline.github.io | 5c4d73b71f87b51903bf88d8e50490d71a6a2b9a | [
"MIT",
"0BSD"
] | 3 | 2020-05-20T03:24:38.000Z | 2020-05-23T14:57:35.000Z | static/1627814429/amp/100/9/payload.js | mazipan-quran-offline/mazipan-quran-offline.github.io | 5c4d73b71f87b51903bf88d8e50490d71a6a2b9a | [
"MIT",
"0BSD"
] | null | null | null | static/1627814429/amp/100/9/payload.js | mazipan-quran-offline/mazipan-quran-offline.github.io | 5c4d73b71f87b51903bf88d8e50490d71a6a2b9a | [
"MIT",
"0BSD"
] | 2 | 2020-05-23T15:10:55.000Z | 2020-06-18T05:57:38.000Z | __NUXT_JSONP__("/amp/100/9", (function(a,b,c,d,e,f,g,h){return {data:[{metaTitle:d,metaDesc:e,verseId:9,surahId:100,currentSurah:{number:"100",name:"العٰديٰت",name_latin:"Al-'Adiyat",number_of_ayah:"11",text:{"1":"وَالْعٰدِيٰتِ ضَبْحًاۙ ","2":"فَالْمُوْرِيٰتِ قَدْحًاۙ","3":"فَالْمُغِيْرٰتِ صُبْحًاۙ","4":"فَاَثَرْنَ بِهٖ نَقْعًاۙ","5":"فَوَسَطْنَ بِهٖ جَمْعًاۙ","6":"اِنَّ الْاِنْسَانَ لِرَبِّهٖ لَكَنُوْدٌ ۚ","7":"وَاِنَّهٗ عَلٰى ذٰلِكَ لَشَهِيْدٌۚ","8":"وَاِنَّهٗ لِحُبِّ الْخَيْرِ لَشَدِيْدٌ ۗ","9":"۞ اَفَلَا يَعْلَمُ اِذَا بُعْثِرَ مَا فِى الْقُبُوْرِۙ","10":"وَحُصِّلَ مَا فِى الصُّدُوْرِۙ","11":"اِنَّ رَبَّهُمْ بِهِمْ يَوْمَىِٕذٍ لَّخَبِيْرٌ ࣖ"},translations:{id:{name:"Kuda Yang Berlari Kencang",text:{"1":"Demi kuda perang yang berlari kencang terengah-engah,","2":"dan kuda yang memercikkan bunga api (dengan pukulan kuku kakinya),","3":"dan kuda yang menyerang (dengan tiba-tiba) pada waktu pagi,","4":"sehingga menerbangkan debu,","5":"lalu menyerbu ke tengah-tengah kumpulan musuh,","6":"sungguh, manusia itu sangat ingkar, (tidak bersyukur) kepada Tuhannya,","7":"dan sesungguhnya dia (manusia) menyaksikan (mengakui) keingkarannya,","8":"dan sesungguhnya cintanya kepada harta benar-benar berlebihan.","9":"Maka tidakkah dia mengetahui apabila apa yang di dalam kubur dikeluarkan,","10":"dan apa yang tersimpan di dalam dada dilahirkan?","11":"sungguh, Tuhan mereka pada hari itu Mahateliti terhadap keadaan mereka."}}},tafsir:{id:{kemenag:{name:"Kemenag",source:"Aplikasi Quran Kementrian Agama Republik Indonesia",text:{"1":a,"2":a,"3":a,"4":a,"5":a,"6":"Dalam ayat ini, Allah menerangkan isi sumpah-Nya, yaitu: watak manusia adalah mengingkari kebenaran dan tidak mengakui hal-hal yang menyebabkan mereka harus bersyukur kepada penciptanya, kecuali orang-orang yang mendapat taufik, membiasakan diri berbuat kebajikan dan menjauhkan diri dari kemungkaran.\n\nHubungan antara ayat 5 yang menggambarkan persoalan kuda dan ayat 6 yang memberi informasi tentang sifat dasar manusia adalah bahwa manusia itu mempunyai potensi menjadi liar seperti kuda yang tidak terkendali, sehingga menyebabkannya ingkar kepada Allah.\n\nSifat yang terpendam dalam jiwa manusia ini menyebabkan ia tidak mementingkan apa yang terdapat di sekelilingnya, tidak menghiraukan apa yang akan datang, dan lupa apa yang telah lalu. Bila Allah memberikan kepadanya sesuatu nikmat, dia menjadi bingung, hatinya menjadi bengis, dan sikapnya menjadi kasar terhadap hamba-hamba Allah.","7":"Dalam ayat ini, Allah menjelaskan bahwa seorang manusia meskipun ingkar, aniaya, dan tetap dalam keingkaran serta kebohongan, bila ia mawas diri, seharusnya ia akan kembali kepada yang benar. \n\nDia mengaku bahwa dia tidak mensyukuri nikmat-nikmat Allah yang dianugerahkan kepadanya. Dia juga mengakui bahwa semua tindakannya merupakan penentangan dan pengingkaran terhadap nikmat tersebut. Ini adalah kesaksian sendiri atas keingkarannya, pengakuan tersebut lebih kuat daripada pengakuan yang timbul dari diri sendiri dengan lisan.","8":"Allah menyatakan bahwa karena sangat sayang dan cinta kepada harta serta keinginan untuk mengumpulkan dan menyimpannya menyebabkan manusia menjadi sangat kikir, tamak, serta melampaui batas. Allah berfirman:\n\nDan kamu mencintai harta dengan kecintaan yang berlebihan. (al-Fajr\u002F89: 20)","9":b,"10":b,"11":b}}}}},jsonldBreadcrumb:{"@context":f,"@type":"BreadcrumbList",itemListElement:[{"@type":c,position:1,name:"Home",item:"https:\u002F\u002Fwww.baca-quran.id\u002F"},{"@type":c,position:2,name:"QS 100",item:"https:\u002F\u002Fwww.baca-quran.id\u002F100\u002F"},{"@type":c,position:3,name:"QS 100:9",item:g}]},jsonLdArticle:{"@context":f,"@type":"NewsArticle",mainEntityOfPage:{"@type":"WebPage","@id":g},headline:d,image:["https:\u002F\u002Fwww.baca-quran.id\u002Fmeta-image.png"],datePublished:h,dateModified:h,author:{"@type":"Person",name:"Irfan Maulana"},description:e,publisher:{"@type":"Organization",name:"mazipan",logo:{"@type":"ImageObject",url:"https:\u002F\u002Fwww.baca-quran.id\u002Ficon.png"}}}}],fetch:{},mutations:[]}}("Allah bersumpah dengan kuda perang yang memperdengarkan suaranya yang gemuruh. Kuda-kuda yang memancarkan bunga api dari kuku kakinya karena berlari kencang. Kuda-kuda yang menyerang di waktu subuh untuk menyergap musuh di waktu mereka tidak siap siaga. Karena kencangnya lari kuda itu, debu-debu jadi beterbangan. Allah menyatakan bahwa kuda yang menyerang itu tiba-tiba berada di tengah-tengah musuh sehingga menyebabkan mereka panik.\n\nAllah bersumpah dengan kuda dan sifat-sifatnya dalam suasana perang bertujuan untuk membangkitkan semangat perjuangan di kalangan orang-orang Mukmin. Sudah selayaknya mereka bersifat demikian dengan membiasakan diri menunggang kuda dengan tangkas untuk menyerbu musuh. Mereka juga diperintahkan agar selalu siap siaga untuk terjun ke medan pertempuran bila genderang perang memanggil mereka untuk menghancurkan musuh yang menyerang, sebagaimana Allah berfirman:\n\nDan persiapkanlah dengan segala kemampuan untuk menghadapi mereka dengan kekuatan yang kamu miliki dan dari pasukan berkuda yang dapat menggentarkan musuh Allah dan musuhmu. (al-Anfal\u002F8: 60).\n\nAllah bersumpah dengan kuda perang yang dalam keadaan berlari kencang, hilir-mudik, memancarkan percikan bunga api dari kakinya karena berlari kencang, dan dengan penyergapan di waktu subuh, menunjukkan bahwa kuda-kuda yang dipelihara itu bukan untuk kebanggaan. Hendaknya kuda yang dipuji adalah yang digunakan untuk memadamkan keganasan musuh, melumpuhkan kekuatan mereka, atau menghadang serangan mereka.\n\nMaksudnya, dalam ketangkasan berkuda terkandung faedah yang tidak terkira banyaknya. Di antaranya adalah dapat dipergunakan untuk mencari nafkah, cepat bergerak untuk suatu keperluan yang mendadak, digunakan untuk menyergap musuh, dan dapat mencapai tempat yang jauh dalam waktu yang singkat.","Dalam ayat-ayat berikut ini, Allah menerangkan ancaman-Nya kepada orang-orang yang ingkar terhadap nikmat-nikmat-Nya dengan menyatakan apakah mereka tidak sadar bahwa Allah mengetahui isi hatinya. Allah juga menyatakan bahwa Dia akan membalas keingkaran mereka itu pada hari dikeluarkan apa yang ada di dalam dada dan dibangkitkan apa yang ada di dalam kubur.","ListItem","Ayat ke 9, QS Al-'Adiyat (Kuda Yang Berlari Kencang) | Baca-Quran.id","Ayat ke 9, QS Al-'Adiyat (Kuda Yang Berlari Kencang) beserta terjemahan dan tafsir dari Kemenag, ❌ tanpa iklan, ❌ tanpa analitik, ✅ gratis sepenuhnya","https:\u002F\u002Fschema.org","https:\u002F\u002Fwww.baca-quran.id\u002F100\u002F9\u002F","2021-08-01T10:39:54.934Z"))); | 6,589 | 6,589 | 0.773562 |
6fe26bbc5d0734673b53abdd9f0da33fc9a68a91 | 7,422 | js | JavaScript | src/marionette.region.js | cmaher/backbone.marionette | c304ecfb9d2a5ffbef39ec2f5df1a139b7833635 | [
"MIT"
] | 1 | 2015-07-17T11:01:17.000Z | 2015-07-17T11:01:17.000Z | src/marionette.region.js | peterblazejewicz/backbone.marionette | 0b010337e1022ee1906b17aa7e106c6986d9e507 | [
"MIT"
] | null | null | null | src/marionette.region.js | peterblazejewicz/backbone.marionette | 0b010337e1022ee1906b17aa7e106c6986d9e507 | [
"MIT"
] | null | null | null | /* jshint maxcomplexity: 10, maxstatements: 27 */
// Region
// ------
//
// Manage the visual regions of your composite application. See
// http://lostechies.com/derickbailey/2011/12/12/composite-js-apps-regions-and-region-managers/
Marionette.Region = function(options) {
this.options = options || {};
this.el = this.getOption('el');
// Handle when this.el is passed in as a $ wrapped element.
this.el = this.el instanceof Backbone.$ ? this.el[0] : this.el;
if (!this.el) {
throwError('An "el" must be specified for a region.', 'NoElError');
}
this.$el = this.getEl(this.el);
if (this.initialize) {
var args = Array.prototype.slice.apply(arguments);
this.initialize.apply(this, args);
}
};
// Region Class methods
// -------------------
_.extend(Marionette.Region, {
// Build an instance of a region by passing in a configuration object
// and a default region class to use if none is specified in the config.
//
// The config object should either be a string as a jQuery DOM selector,
// a Region class directly, or an object literal that specifies both
// a selector and regionClass:
//
// ```js
// {
// selector: "#foo",
// regionClass: MyCustomRegion
// }
// ```
//
buildRegion: function(regionConfig, defaultRegionClass) {
var regionIsString = _.isString(regionConfig);
var regionSelectorIsString = _.isString(regionConfig.selector);
var regionClassIsUndefined = _.isUndefined(regionConfig.regionClass);
var regionIsClass = _.isFunction(regionConfig);
if (!regionIsClass && !regionIsString && !regionSelectorIsString) {
throwError('Region must be specified as a Region class,' +
'a selector string or an object with selector property');
}
var selector, RegionClass;
// get the selector for the region
if (regionIsString) {
selector = regionConfig;
}
if (regionConfig.selector) {
selector = regionConfig.selector;
delete regionConfig.selector;
}
// get the class for the region
if (regionIsClass) {
RegionClass = regionConfig;
}
if (!regionIsClass && regionClassIsUndefined) {
RegionClass = defaultRegionClass;
}
if (regionConfig.regionClass) {
RegionClass = regionConfig.regionClass;
delete regionConfig.regionClass;
}
if (regionIsString || regionIsClass) {
regionConfig = {};
}
regionConfig.el = selector;
// build the region instance
var region = new RegionClass(regionConfig);
// override the `getEl` function if we have a parentEl
// this must be overridden to ensure the selector is found
// on the first use of the region. if we try to assign the
// region's `el` to `parentEl.find(selector)` in the object
// literal to build the region, the element will not be
// guaranteed to be in the DOM already, and will cause problems
if (regionConfig.parentEl) {
region.getEl = function(el) {
if (_.isObject(el)) {
return Backbone.$(el);
}
var parentEl = regionConfig.parentEl;
if (_.isFunction(parentEl)) {
parentEl = parentEl();
}
return parentEl.find(el);
};
}
return region;
}
});
// Region Instance Methods
// -----------------------
_.extend(Marionette.Region.prototype, Backbone.Events, {
// Displays a backbone view instance inside of the region.
// Handles calling the `render` method for you. Reads content
// directly from the `el` attribute. Also calls an optional
// `onShow` and `onDestroy` method on your view, just after showing
// or just before destroying the view, respectively.
// The `preventDestroy` option can be used to prevent a view from
// the old view being destroyed on show.
// The `forceShow` option can be used to force a view to be
// re-rendered if it's already shown in the region.
show: function(view, options){
this._ensureElement();
var showOptions = options || {};
var isDifferentView = view !== this.currentView;
var preventDestroy = !!showOptions.preventDestroy;
var forceShow = !!showOptions.forceShow;
// we are only changing the view if there is a view to change to begin with
var isChangingView = !!this.currentView;
// only destroy the view if we don't want to preventDestroy and the view is different
var _shouldDestroyView = !preventDestroy && isDifferentView;
if (_shouldDestroyView) {
this.empty();
}
// show the view if the view is different or if you want to re-show the view
var _shouldShowView = isDifferentView || forceShow;
if (_shouldShowView) {
view.render();
if (isChangingView) {
this.triggerMethod('before:swap', view);
}
this.triggerMethod('before:show', view);
this.triggerMethod.call(view, 'before:show');
this.attachHtml(view);
this.currentView = view;
if (isChangingView) {
this.triggerMethod('swap', view);
}
this.triggerMethod('show', view);
if (_.isFunction(view.triggerMethod)) {
view.triggerMethod('show');
} else {
this.triggerMethod.call(view, 'show');
}
return this;
}
return this;
},
_ensureElement: function(){
if (!_.isObject(this.el)) {
this.$el = this.getEl(this.el);
this.el = this.$el[0];
}
if (!this.$el || this.$el.length === 0) {
throwError('An "el" ' + this.$el.selector + ' must exist in DOM');
}
},
// Override this method to change how the region finds the
// DOM element that it manages. Return a jQuery selector object.
getEl: function(el) {
return Backbone.$(el);
},
// Override this method to change how the new view is
// appended to the `$el` that the region is managing
attachHtml: function(view) {
// empty the node and append new view
this.el.innerHTML='';
this.el.appendChild(view.el);
},
// Destroy the current view, if there is one. If there is no
// current view, it does nothing and returns immediately.
empty: function() {
var view = this.currentView;
if (!view || view.isDestroyed) { return; }
this.triggerMethod('before:empty', view);
// call 'destroy' or 'remove', depending on which is found
if (view.destroy) { view.destroy(); }
else if (view.remove) { view.remove(); }
this.triggerMethod('empty', view);
delete this.currentView;
},
// Attach an existing view to the region. This
// will not call `render` or `onShow` for the new view,
// and will not replace the current HTML for the `el`
// of the region.
attachView: function(view) {
this.currentView = view;
},
// Reset the region by destroying any existing view and
// clearing out the cached `$el`. The next time a view
// is shown via this region, the region will re-query the
// DOM for the region's `el`.
reset: function() {
this.empty();
if (this.$el) {
this.el = this.$el.selector;
}
delete this.$el;
},
// Proxy `getOption` to enable getting options from this or this.options by name.
getOption: Marionette.proxyGetOption,
// import the `triggerMethod` to trigger events with corresponding
// methods if the method exists
triggerMethod: Marionette.triggerMethod
});
// Copy the `extend` function used by Backbone's classes
Marionette.Region.extend = Marionette.extend;
| 28.436782 | 95 | 0.652115 |
6fe2bd738a73f3cb4beca26735790c53f47792d8 | 301 | js | JavaScript | tests/functional/tests/components/card.spec.js | marlonfrontend/vue-sdz | 50b59fd58fe30ed46e2e10959de337238c2bfe8f | [
"MIT"
] | 1 | 2021-07-23T14:06:47.000Z | 2021-07-23T14:06:47.000Z | tests/functional/tests/components/card.spec.js | sdz-front/vue-sdz | 50b59fd58fe30ed46e2e10959de337238c2bfe8f | [
"MIT"
] | 2 | 2021-08-13T18:40:22.000Z | 2021-09-09T17:54:10.000Z | tests/functional/tests/components/card.spec.js | seedz-ag/vue-sdz | 50b59fd58fe30ed46e2e10959de337238c2bfe8f | [
"MIT"
] | null | null | null | describe('SCard', () => {
it('test 1', () => {
cy.common('app.responsive', 'desktop')
// cy.common('element.click', 'logged-actions-button')
// cy.common('element.click', 'popover-Configurações')
// cy
// .get('.configuration-container')
// .should('be.visible')
})
})
| 27.363636 | 58 | 0.561462 |
6fe3030edd33b89d3f0681701c4fd19161179cb8 | 4,788 | js | JavaScript | src/test/scripts/suite/syntax/identifier/unicode_escape_binding_let.js | mathiasbynens/es6draft | 7e196e8a1482384ca83946998f5fbd22068b47c6 | [
"MIT"
] | 48 | 2015-01-29T09:32:22.000Z | 2022-02-10T11:12:29.000Z | src/test/scripts/suite/syntax/identifier/unicode_escape_binding_let.js | mathiasbynens/es6draft | 7e196e8a1482384ca83946998f5fbd22068b47c6 | [
"MIT"
] | 26 | 2015-01-19T09:16:29.000Z | 2022-02-22T12:15:13.000Z | src/test/scripts/suite/syntax/identifier/unicode_escape_binding_let.js | mathiasbynens/es6draft | 7e196e8a1482384ca83946998f5fbd22068b47c6 | [
"MIT"
] | 17 | 2015-07-10T18:53:24.000Z | 2022-03-23T02:25:05.000Z | /*
* Copyright (c) André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
const {
assertSyntaxError
} = Assert;
// 11.6.2.1 Keywords
const Keywords =
`
break do in typeof
case else instanceof var
catch export new void
class extends return while
const finally super with
continue for switch yield
debugger function this
default if throw
delete import try
`.trim().split(/\s+/);
const KeywordsWithoutYield = Keywords.filter(w => w !== "yield");
// 11.6.2.2 Future Reserved Words
const FutureReservedWords =
`
enum
`.trim().split(/\s+/);
// 11.6.2.2 Future Reserved Words (Strict Mode)
const FutureReservedWordsStrict =
`
implements let private public
interface package protected static
`.trim().split(/\s+/);
const FutureReservedWordsStrictWithoutLet = FutureReservedWordsStrict.filter(w => w !== "let");
// 11.8 Literals
// 11.8.1 Null Literals
// 11.8.2 Boolean Literals
const Literals =
`
null
true
false
`.trim().split(/\s+/);
function toStr(number, radix, pad) {
let s = number.toString(radix);
return "0".repeat(pad - s.length) + s;
}
const transformer = [
function noEscape(name) {
return name;
},
function escapeFirstChar(name) {
return `\\u${toStr(name.charCodeAt(0), 16, 4)}${name.substring(1)}`
},
function escapeSecondChar(name) {
return `${name.substring(0, 1)}\\u${toStr(name.charCodeAt(1), 16, 4)}${name.substring(2)}`
},
];
// non-strict function code
for (let t of transformer) {
// Keywords, except for 'yield', and Future Reserved Words are not allowed as binding identifiers
for (let w of ["let", ...KeywordsWithoutYield, ...FutureReservedWords, ...Literals]) {
w = t(w);
assertSyntaxError(`function f() { let ${w}; }`);
assertSyntaxError(`function f() { let {${w}} = {}; }`);
assertSyntaxError(`function f() { let {x: ${w}} = {}; }`);
assertSyntaxError(`function f() { let [${w}] = {}; }`);
assertSyntaxError(`function f() { let [...${w}] = {}; }`);
}
// 'yield' and Future Reserved Words (Strict Mode) are allowed as binding identifiers
for (let w of ["yield", ...FutureReservedWordsStrictWithoutLet]) {
w = t(w);
Function(`
function f1() { let ${w}; }
function f2() { let {${w}} = {}; }
function f3() { let {x: ${w}} = {}; }
function f4() { let [${w}] = {}; }
function f5() { let [...${w}] = {}; }
`);
}
}
// strict function code
for (let t of transformer) {
// Keywords, Future Reserved Words and Future Reserved Words (Strict Mode) are not allowed as binding identifiers
for (let w of [...Keywords, ...FutureReservedWords, ...FutureReservedWordsStrict, ...Literals]) {
w = t(w);
assertSyntaxError(`function f() {"use strict"; let ${w}; }`);
assertSyntaxError(`function f() {"use strict"; let {${w}} = {}; }`);
assertSyntaxError(`function f() {"use strict"; let {x: ${w}} = {}; }`);
assertSyntaxError(`function f() {"use strict"; let [${w}] = {}; }`);
assertSyntaxError(`function f() {"use strict"; let [...${w}] = {}; }`);
}
}
// non-strict generator code
for (let t of transformer) {
// Keywords, and Future Reserved Words are not allowed as binding identifiers
for (let w of ["let", ...Keywords, ...FutureReservedWords, ...Literals]) {
w = t(w);
assertSyntaxError(`function* f() { let ${w}; }`);
assertSyntaxError(`function* f() { let {${w}} = {}; }`);
assertSyntaxError(`function* f() { let {x: ${w}} = {}; }`);
assertSyntaxError(`function* f() { let [${w}] = {}; }`);
assertSyntaxError(`function* f() { let [...${w}] = {}; }`);
}
// Future Reserved Words (Strict Mode) are allowed as binding identifiers
for (let w of [...FutureReservedWordsStrictWithoutLet]) {
w = t(w);
Function(`
function* f1() { let ${w}; }
function* f2() { let {${w}} = {}; }
function* f3() { let {x: ${w}} = {}; }
function* f4() { let [${w}] = {}; }
function* f5() { let [...${w}] = {}; }
`);
}
}
// strict generator code
for (let t of transformer) {
// Keywords, Future Reserved Words and Future Reserved Words (Strict Mode) are not allowed as binding identifiers
for (let w of [...Keywords, ...FutureReservedWords, ...FutureReservedWordsStrict, ...Literals]) {
w = t(w);
assertSyntaxError(`function* f() {"use strict"; let ${w}; }`);
assertSyntaxError(`function* f() {"use strict"; let {${w}} = {}; }`);
assertSyntaxError(`function* f() {"use strict"; let {x: ${w}} = {}; }`);
assertSyntaxError(`function* f() {"use strict"; let [${w}] = {}; }`);
assertSyntaxError(`function* f() {"use strict"; let [...${w}] = {}; }`);
}
}
| 32.794521 | 115 | 0.592523 |
6fe383e9389378f4279180e0552da60756c432d2 | 1,596 | js | JavaScript | Header/doxygen/html/group___s_t_m8_a_f___s_t_m8_s_struct___c_a_n__t_8_page_8_p_a_g_e__0.js | STM8-SPL-license/discussion | 1a565af33b229c6e14887a1f02f51aa77b267cbe | [
"CNRI-Python",
"Xnet",
"X11"
] | 1 | 2019-06-02T20:40:18.000Z | 2019-06-02T20:40:18.000Z | Header/doxygen/html/group___s_t_m8_a_f___s_t_m8_s_struct___c_a_n__t_8_page_8_p_a_g_e__0.js | STM8-SPL-license/discussion | 1a565af33b229c6e14887a1f02f51aa77b267cbe | [
"CNRI-Python",
"Xnet",
"X11"
] | 2 | 2019-01-06T10:54:45.000Z | 2020-06-14T05:24:21.000Z | Header/doxygen/html/group___s_t_m8_a_f___s_t_m8_s_struct___c_a_n__t_8_page_8_p_a_g_e__0.js | STM8-SPL-license/discussion | 1a565af33b229c6e14887a1f02f51aa77b267cbe | [
"CNRI-Python",
"Xnet",
"X11"
] | null | null | null | var group___s_t_m8_a_f___s_t_m8_s_struct___c_a_n__t_8_page_8_p_a_g_e__0 =
[
[ "MCSR", "group___s_t_m8_a_f___s_t_m8_s.html#a2afa689ca12af7a68d7ec2998eeeb8f2", null ],
[ "MDAR1", "group___s_t_m8_a_f___s_t_m8_s.html#ae556d494a322169ad317404e01a80af0", null ],
[ "MDAR2", "group___s_t_m8_a_f___s_t_m8_s.html#a1e0d7af36b34c23695925d889aa422a4", null ],
[ "MDAR3", "group___s_t_m8_a_f___s_t_m8_s.html#aed24785f7882da467e078672b3eb10bb", null ],
[ "MDAR4", "group___s_t_m8_a_f___s_t_m8_s.html#a537ed23ff3a038d9882ed07a405fe8bc", null ],
[ "MDAR5", "group___s_t_m8_a_f___s_t_m8_s.html#a163c04b594c5ac342874946047af1041", null ],
[ "MDAR6", "group___s_t_m8_a_f___s_t_m8_s.html#ad2b3c2ca8e0c8fb4ddc9e310d3df6578", null ],
[ "MDAR7", "group___s_t_m8_a_f___s_t_m8_s.html#a9f0d2f2e8e0a2ca1e3cc97e4cbb6e308", null ],
[ "MDAR8", "group___s_t_m8_a_f___s_t_m8_s.html#a766c4593e9db96e19f2b7f8ffd0d2737", null ],
[ "MDLCR", "group___s_t_m8_a_f___s_t_m8_s.html#a9b00b9452c7bad430ef9faefdf09357f", null ],
[ "MIDR1", "group___s_t_m8_a_f___s_t_m8_s.html#ad3cb4a3e83b191e645933baaf0733457", null ],
[ "MIDR2", "group___s_t_m8_a_f___s_t_m8_s.html#a05598790257579c406d25705a938942b", null ],
[ "MIDR3", "group___s_t_m8_a_f___s_t_m8_s.html#a2bea704b8c80bcafcc1b5d2c7945b316", null ],
[ "MIDR4", "group___s_t_m8_a_f___s_t_m8_s.html#afc12e5b31b7c2c9afe51aceaac61f964", null ],
[ "MTSRH", "group___s_t_m8_a_f___s_t_m8_s.html#ac33bd2c6d194fdcde43d124b65626edd", null ],
[ "MTSRL", "group___s_t_m8_a_f___s_t_m8_s.html#aca81a329d56278671a23ac1fa92c6688", null ]
]; | 84 | 94 | 0.795113 |
6fe45c91e2ba27e61be4e6881ab72c6dab81ce25 | 471 | js | JavaScript | packages/ember-views/lib/views/states/destroying.js | rob-e-pitts/ember.js | ca76dba3cd9fdf3f7f0a4173e6d9454d5bcfc666 | [
"MIT"
] | 1 | 2019-02-24T08:01:28.000Z | 2019-02-24T08:01:28.000Z | packages/ember-views/lib/views/states/destroying.js | rob-e-pitts/ember.js | ca76dba3cd9fdf3f7f0a4173e6d9454d5bcfc666 | [
"MIT"
] | 1 | 2021-05-07T17:13:03.000Z | 2021-05-07T17:13:03.000Z | packages/ember-views/lib/views/states/destroying.js | rob-e-pitts/ember.js | ca76dba3cd9fdf3f7f0a4173e6d9454d5bcfc666 | [
"MIT"
] | null | null | null | import { assign } from 'ember-utils';
import { Error as EmberError } from 'ember-metal';
import _default from './default';
/**
@module ember
@submodule ember-views
*/
const destroying = Object.create(_default);
assign(destroying, {
appendChild() {
throw new EmberError('You can\'t call appendChild on a view being destroyed');
},
rerender() {
throw new EmberError('You can\'t call rerender on a view being destroyed');
}
});
export default destroying;
| 22.428571 | 82 | 0.700637 |
6fe47cd8862905470b456c7f03ebc92fbd9ea41d | 601 | js | JavaScript | nutz-integration-zbus/src/main/resources/org/nutz/integration/zbus/zbus-rpc-service.js | lihongwu19921215/nutzmore | 798fc634128c8bb4239e3b76a233b87c7a2932cc | [
"Apache-2.0"
] | 353 | 2015-02-13T14:04:50.000Z | 2022-03-04T08:36:19.000Z | nutz-integration-zbus/src/main/resources/org/nutz/integration/zbus/zbus-rpc-service.js | SaviourWong/nutzmore | a49568058a8239f1156bb6b87f1114d0b033e455 | [
"Apache-2.0"
] | 132 | 2015-03-17T07:08:29.000Z | 2022-03-10T02:18:38.000Z | nutz-integration-zbus/src/main/resources/org/nutz/integration/zbus/zbus-rpc-service.js | SaviourWong/nutzmore | a49568058a8239f1156bb6b87f1114d0b033e455 | [
"Apache-2.0"
] | 231 | 2015-02-13T01:30:11.000Z | 2021-06-13T17:18:19.000Z | var ioc = {
// 服务端配置------------------------
rpcProcessor:{
type: "org.zbus.rpc.RpcProcessor"
},
serviceConfig : {
type : "org.zbus.rpc.mq.ServiceConfig",
args : [{refer:"broker"}],
fields:{
mq : {java:"$conf.get('zbus.mq.name', 'nutzbook')"},
consumerCount : {java:"$conf.getInt('zbus.rpc.service.consumerCount', 2)"},
messageProcessor : {refer:"rpcProcessor"}
}
},
rpcService : {
type : "org.zbus.rpc.mq.Service",
args : [{refer:"serviceConfig"}],
events : {
create : "start",
depose : "close"
}
}
// end 服务器端配置----------------------
}; | 25.041667 | 79 | 0.537438 |
6fe57785506550272f22e8e7a65be8b7406eebb6 | 716 | js | JavaScript | test/sandbox.test.js | roman-spiridonov/mortgage-calc | a3c628754abb6ae53262b27006327b3245b12d0e | [
"MIT"
] | 1 | 2019-04-30T01:28:08.000Z | 2019-04-30T01:28:08.000Z | test/sandbox.test.js | roman-spiridonov/mortgage-calc | a3c628754abb6ae53262b27006327b3245b12d0e | [
"MIT"
] | null | null | null | test/sandbox.test.js | roman-spiridonov/mortgage-calc | a3c628754abb6ae53262b27006327b3245b12d0e | [
"MIT"
] | null | null | null | /**
* Created by Roman Spiridonov <romars@phystech.edu> on 4/20/2017.
*/
"use strict";
const
// Libraries
path = require('path'),
expect = require('chai').expect,
sinon = require('sinon'),
// Project modules
mjAPI = require("mathjax-node"),
mjpage = require("mathjax-node-page").mjpage;
describe("sandbox", function () {
it.skip("mjpage API", function (done) {
mjpage("\$\$x\$\$ + \$\$\\frac{x^2+x}{y^3}\$\$", {
format: ["TeX"],
tex: {
processEscapes: false
},
singleDollars: true,
fragment: false
}, {
html: true,
css: true,
equationNumbers: "all"
}, function (data) {
console.log(data);
done();
});
});
});
| 20.457143 | 66 | 0.543296 |
6fe63c4b6cb9c2e8203403a981ec1ceb4ff2b1d0 | 718 | js | JavaScript | jest.config.js | mattkenney/react-bulma-components | 5d103ef780e9ba3387cdbbc33d303a66c71ff247 | [
"MIT"
] | null | null | null | jest.config.js | mattkenney/react-bulma-components | 5d103ef780e9ba3387cdbbc33d303a66c71ff247 | [
"MIT"
] | null | null | null | jest.config.js | mattkenney/react-bulma-components | 5d103ef780e9ba3387cdbbc33d303a66c71ff247 | [
"MIT"
] | null | null | null | module.exports = {
setupFilesAfterEnv: ['./__test__/setup.js'],
rootDir: 'src',
testMatch: ['**/*.test.js'],
coverageDirectory: '<rootDir>/../.coverage',
collectCoverageFrom: [
'**/*.js',
'!**/node_modules/**',
'!**/*.story.js',
'!**/*.test.js',
],
coverageReporters: ['lcov', 'text', 'text-summary'],
moduleDirectories: [
'node_modules',
'<rootDir>',
],
coverageThreshold: {
global: {
branches: 90,
functions: 90,
lines: 90,
statements: 90,
},
},
transform: {
'^.+\\.js$': 'babel-jest',
},
moduleNameMapper: {
'\\.(css|less|s(c|a)ss)$': '<rootDir>/../__mocks__/style.js',
'services(.*)$': '<rootDir>/services$1',
},
};
| 21.757576 | 65 | 0.527855 |
6fe64c0baf1e70449fad7b332a0a355884f73167 | 613 | js | JavaScript | test/serializer/pure-functions/ObjectAssign2.js | himanshiLt/prepack | 185bc0208b0ab98950f45b8dc33307209b6f21ac | [
"BSD-3-Clause"
] | 15,477 | 2017-05-03T17:07:59.000Z | 2022-02-11T15:50:02.000Z | test/serializer/pure-functions/ObjectAssign2.js | himanshiLt/prepack | 185bc0208b0ab98950f45b8dc33307209b6f21ac | [
"BSD-3-Clause"
] | 1,419 | 2017-05-03T17:40:19.000Z | 2022-02-10T16:38:28.000Z | test/serializer/pure-functions/ObjectAssign2.js | himanshiLt/prepack | 185bc0208b0ab98950f45b8dc33307209b6f21ac | [
"BSD-3-Clause"
] | 609 | 2017-05-03T17:12:43.000Z | 2022-01-25T06:55:55.000Z | (function() {
var someAbstract = global.__abstract ? __abstract("function", "(function() {})") : () => {};
var evaluatePureFunction = global.__evaluatePureFunction || (f => f());
var result;
evaluatePureFunction(() => {
function calculate(y) {
var z = { c: 3, e: 1 };
if (global.__makePartial) __makePartial(z);
if (global.__makeSimple) __makeSimple(z);
someAbstract(z);
var x = { a: 1, b: 1, c: 1 };
return Object.assign(x, y, z);
}
result = calculate({ b: 2, d: 1 });
});
global.inspect = function() {
return JSON.stringify(result);
};
})();
| 26.652174 | 94 | 0.570962 |
6fe65723ce80c2e9617f20eb5b66e3faa432c843 | 3,885 | js | JavaScript | src/components/common/NetworkBanner.js | Mintbase/near-wallet | 573702b2b27c3aec8817c1c09c959a343a003a9e | [
"Apache-2.0",
"MIT"
] | 5 | 2021-01-19T07:38:46.000Z | 2021-11-17T17:51:04.000Z | src/components/common/NetworkBanner.js | buiquanganh2001/near-wallet | 573702b2b27c3aec8817c1c09c959a343a003a9e | [
"Apache-2.0",
"MIT"
] | null | null | null | src/components/common/NetworkBanner.js | buiquanganh2001/near-wallet | 573702b2b27c3aec8817c1c09c959a343a003a9e | [
"Apache-2.0",
"MIT"
] | 3 | 2021-01-19T01:42:49.000Z | 2021-09-27T14:15:59.000Z | import React, { useEffect } from 'react';
import styled from 'styled-components';
import helpIconWhite from '../../images/icon-help-white.svg';
import helpIconBrown from '../../images/icon-help-brown.svg';
import { IS_MAINNET, SHOW_PRERELEASE_WARNING, NODE_URL } from '../../utils/wallet';
import { Modal } from 'semantic-ui-react';
import { Translate } from 'react-localize-redux';
import AlertTriangleIcon from '../svg/AlertTriangleIcon.js';
const Container = styled.div`
color: white;
background-color: #0072CE;
position: fixed;
padding: 10px;
top: 0;
left: 0;
right: 0;
z-index: 1000;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
a {
color: white;
:hover {
color: white;
text-decoration: underline;
}
}
.trigger-string {
display: flex;
align-items: center;
cursor: pointer;
text-align: center;
:after {
content: '';
background: url(${helpIconWhite}) center no-repeat;
height: 16px;
min-width: 16px;
width: 16px;
margin: 0 0 0 8px;
display: inline-block;
}
}
h4 {
margin-bottom: 5px !important;
}
&.staging-banner {
background-color: #F6C98E;
color: #452500;
.alert-triangle-icon {
margin-right: 8px;
min-width: 16px;
}
.trigger-string {
:after {
background: url(${helpIconBrown}) center no-repeat;
}
}
}
`
const NetworkBanner = ({ account }) => {
useEffect(() => {
setBannerHeight()
window.addEventListener("resize", setBannerHeight)
return () => {
window.removeEventListener("resize", setBannerHeight)
}
}, [account])
const setBannerHeight = () => {
const bannerHeight = document.getElementById('top-banner') && document.getElementById('top-banner').offsetHeight
const app = document.getElementById('app-container')
const navContainer = document.getElementById('nav-container')
navContainer.style.top = bannerHeight ? `${bannerHeight}px` : 0
app.style.paddingTop = bannerHeight ? `${bannerHeight + 85}px` : '75px'
}
if (!IS_MAINNET) {
return (
<Container id='top-banner'>
<Modal
size='mini'
trigger={
<div className='trigger-string'>
<Translate id='networkBanner.title' />
(<a href={`${NODE_URL}/status`} target='_blank' rel='noopener noreferrer' onClick={e => e.stopPropagation()}>
{NODE_URL.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/')[0]}
</a>)
</div>
}
closeIcon
>
<h4><Translate id='networkBanner.header' /></h4>
<Translate id='networkBanner.desc' />
</Modal>
</Container>
)
} else if (SHOW_PRERELEASE_WARNING) {
return (
<Container id='top-banner' className='staging-banner'>
<AlertTriangleIcon color='#A15600'/>
<Modal
size='mini'
trigger={
<div className='trigger-string'>
<Translate id='stagingBanner.title' />
</div>
}
closeIcon
>
<Translate id='stagingBanner.desc' />
</Modal>
</Container>
)
} else {
return null
}
}
export default NetworkBanner; | 29.656489 | 137 | 0.497297 |
6fe66b5a7c0f575c8576f418486867a379a9ffa5 | 1,275 | js | JavaScript | docs/assets/read-notes_weread_jiucaideziwoxiuyang.md.f5403116.lean.js | MShineRay/MShineRay.github.io | 57ed79235b9753e8ecdd019f966cac26ed18774b | [
"MIT"
] | null | null | null | docs/assets/read-notes_weread_jiucaideziwoxiuyang.md.f5403116.lean.js | MShineRay/MShineRay.github.io | 57ed79235b9753e8ecdd019f966cac26ed18774b | [
"MIT"
] | null | null | null | docs/assets/read-notes_weread_jiucaideziwoxiuyang.md.f5403116.lean.js | MShineRay/MShineRay.github.io | 57ed79235b9753e8ecdd019f966cac26ed18774b | [
"MIT"
] | null | null | null | import { l as logCreated } from "./log-created.c3942cf7.js";
import { _ as _export_sfc, o as openBlock, c as createElementBlock, i as createStaticVNode, g as createVNode } from "./app.2b2dcef6.js";
var _imports_0 = "/img/weread/jiucaideziwoxiuyang/t6_23027232.jpg";
var jiucaideziwoxiuyang_vue_vue_type_style_index_0_scoped_true_lang = "";
const _sfc_main$1 = {
name: "jiucaideziwoxiuyang",
mixins: [logCreated]
};
const _hoisted_1 = { class: "container" };
const _hoisted_2 = /* @__PURE__ */ createStaticVNode("", 4);
const _hoisted_6 = [
_hoisted_2
];
function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
return openBlock(), createElementBlock("div", _hoisted_1, _hoisted_6);
}
var ApiIndex = /* @__PURE__ */ _export_sfc(_sfc_main$1, [["render", _sfc_render], ["__scopeId", "data-v-156df6c1"]]);
const __pageData = '{"title":"","description":"","frontmatter":{},"relativePath":"read-notes/weread/jiucaideziwoxiuyang.md","lastUpdated":1648630957131}';
const __default__ = {};
const _sfc_main = /* @__PURE__ */ Object.assign(__default__, {
setup(__props) {
return (_ctx, _cache) => {
return openBlock(), createElementBlock("div", null, [
createVNode(ApiIndex)
]);
};
}
});
export { __pageData, _sfc_main as default };
| 42.5 | 154 | 0.704314 |
6fe6b6bc4493c8060edce8b2661ca8bac5aed66f | 4,668 | js | JavaScript | src/assets/js/notification.js | fabianskutta/personal-site | 0d14b45a07ad7849408c39c986a9956fbc09e980 | [
"MIT"
] | 2 | 2022-01-04T22:26:41.000Z | 2022-03-07T22:42:58.000Z | src/assets/js/notification.js | fabianskutta/personal-site | 0d14b45a07ad7849408c39c986a9956fbc09e980 | [
"MIT"
] | null | null | null | src/assets/js/notification.js | fabianskutta/personal-site | 0d14b45a07ad7849408c39c986a9956fbc09e980 | [
"MIT"
] | null | null | null | var a1 = localStorage.getItem('achievement-1');
if (a1 === null) {
localStorage.setItem("achievement-1", false)
}
var a2 = localStorage.getItem('achievement-2');
if (a2 === null) {
localStorage.setItem("achievement-2", false)
}
var a3 = localStorage.getItem('achievement-3');
if (a3 === null) {
localStorage.setItem("achievement-3", false)
}
var n = localStorage.getItem('on_load_counter');
if (n === null) {
n = 0;
}
n++;
localStorage.setItem("on_load_counter", n);
if (n == 10) {
localStorage.setItem("achievement-2", true);
document.getElementById('notification').innerHTML = `
<div class="notification-container">
<h3 class="notification-title">10 visits</h3>
<p class="notification-description">You're visiting my website for the 10th time. Wooooooow that's crazy!</p>
<a onclick="achievements()" id="achievements-btn" class="btn-small btn-primary">View achievements</a>
<a id="notification-close" class="btn-small btn-secondary">close</a>
</div>`;
const tl = gsap.timeline({defaults: {duration: 0.75}})
tl.fromTo('.notification-container', {y: 50, opacity:0}, {y: 0, opacity:1}, "+=2.00")
document.getElementById('notification-close').addEventListener('click', event => {
tl.fromTo('.notification-container', { opacity:1}, { opacity:0, duration: 0.25})
setTimeout(function(){
document.getElementById('notification').innerHTML = ``;
}, 1000);
})
}
if (n == 1) {
localStorage.setItem("theme", "dark");
document.getElementById('notification').innerHTML = `
<div class="notification-container">
<h3 class="notification-title">Welcome! It's not about cookies.</h3>
<p class="notification-description">There are various achievements that you can get on my website. Have fun searching! :)</p>
<a onclick="achievements()" id="achievements-btn" class="btn-small btn-primary">View achievements</a>
<a id="notification-close" class="btn-small btn-secondary">close</a>
</div>`;
const tl = gsap.timeline({defaults: {duration: 0.75}})
tl.fromTo('.notification-container', {y: 50, opacity:0}, {y: 0, opacity:1}, "+=2.00")
document.getElementById('notification-close').addEventListener('click', event => {
tl.fromTo('.notification-container', { opacity:1}, { opacity:0, duration: 0.25})
setTimeout(function(){
document.getElementById('notification').innerHTML = ``;
}, 1000);
})
}
function lightmodenotification() {
var l = localStorage.getItem('achievement-1');
if (l == "false") {
localStorage.setItem("achievement-1", true);
document.getElementById('notification').innerHTML = `
<div class="notification-container">
<h3 class="notification-title">Light Mode</h3>
<p class="notification-description">You discovered the light side of my website. But only to try it out, right? :)</p>
<a onclick="achievements()" id="achievements-btn" class="btn-small btn-primary">View achievements</a>
<a id="notification-close" class="btn-small btn-secondary">close</a>
</div>`;
tl.fromTo('.notification-container', {y: 50, opacity:0}, {y: 0, opacity:1}, "+=1.00")
document.getElementById('notification-close').addEventListener('click', event => {
tl.fromTo('.notification-container', { opacity:1}, { opacity:0, duration: 0.25})
setTimeout(function(){
document.getElementById('notification').innerHTML = ``;
}, 1000);
})
}
}
document.getElementById("rocket-btn").onclick = function() {
var b = localStorage.getItem('achievement-3');
if (b == "false") {
localStorage.setItem("achievement-3", true);
document.getElementById('notification').innerHTML = `
<div class="notification-container">
<h3 class="notification-title">Rocket launched!</h3>
<p class="notification-description">You launched the rocket to get back to the top.</p>
<a onclick="achievements()" id="achievements-btn" class="btn-small btn-primary">View achievements</a>
<a id="notification-close" class="btn-small btn-secondary">close</a>
</div>`;
tl.fromTo('.notification-container', {y: 50, opacity:0}, {y: 0, opacity:1}, "+=1.00")
document.getElementById('notification-close').addEventListener('click', event => {
tl.fromTo('.notification-container', { opacity:1}, { opacity:0, duration: 0.25})
setTimeout(function(){
document.getElementById('notification').innerHTML = ``;
}, 1000);
})
}
} | 45.320388 | 137 | 0.635604 |
6fe731f4b9ec49307e37a370c37bed252da2884a | 9,329 | js | JavaScript | src/shared/walletv3.js | xertSuns1/Niffler | 84702319322c9b8ab23236a4fadac24cad76058c | [
"Apache-2.0"
] | 77 | 2019-05-20T08:51:39.000Z | 2022-02-08T13:09:35.000Z | src/shared/walletv3.js | xertSuns1/Niffler | 84702319322c9b8ab23236a4fadac24cad76058c | [
"Apache-2.0"
] | 62 | 2019-05-22T16:13:54.000Z | 2021-04-25T08:18:09.000Z | src/shared/walletv3.js | xertSuns1/Niffler | 84702319322c9b8ab23236a4fadac24cad76058c | [
"Apache-2.0"
] | 25 | 2019-05-30T08:46:38.000Z | 2022-02-13T06:06:54.000Z | const axios = require('axios')
require('promise.prototype.finally').shim()
const crypto = require('crypto')
import fs from 'fs'
import {ownerApiSecretPath, grinWalletPath, platform} from './config'
import log from './logger'
import {exec, execFile} from 'child_process'
let client
let ecdh
let publicKey
let sharedSecret //hex string
let token
//https://docs.rs/grin_wallet_api/4.0.0/grin_wallet_api/trait.OwnerRpc.html
const walletHost = 'http://localhost:3420'
const jsonRPCUrl = 'http://localhost:3420/v3/owner'
function encrypt(key, text, nonce){
//const nonce = new Buffer(crypto.randomBytes(12), 'utf8')
const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce)
const encrypted = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()])
const tag = cipher.getAuthTag()
return Buffer.concat([encrypted, tag]).toString('base64')
}
function decrypt(key, data, nonce){
//key,nonce is all buffer type; data is base64-encoded string
const data_ = Buffer.from(data, 'base64')
const decipher = crypto.createDecipheriv('aes-256-gcm', key, nonce)
const len = data_.length
const tag = data_.slice(len-16, len)
const text = data_.slice(0, len-16)
decipher.setAuthTag(tag)
const decrypted = decipher.update(text, 'binary', 'utf8') + decipher.final('utf8');
return decrypted
}
class WalletServiceV3 {
static initClient() {
if(fs.existsSync(ownerApiSecretPath)){
client = axios.create({
baseURL: walletHost,
auth: {
username: 'grin',
password: fs.readFileSync(ownerApiSecretPath).toString()
},
})
}else{
client = axios.create({baseURL: walletHost})
}
}
static post(method, params){
const headers = {
'Content-Type': 'application/json'
}
const body = {
jsonrpc: '2.0',
id: 1,
method: method,
params: params,
}
return client.post(jsonRPCUrl, body, headers)
}
static postEncrypted(method, params){
if(!sharedSecret)return
const body = {
jsonrpc: '2.0',
id: 1,
method: method,
params: params,
}
//console.log('post body: ' + JSON.stringify(body))
const nonce = crypto.randomBytes(12)
const key = Buffer.from(sharedSecret,'hex')
const bodyEncrypted = encrypt(key, JSON.stringify(body), nonce)
return new Promise((resolve, reject)=>{
WalletServiceV3.post('encrypted_response_v3', {
'nonce': nonce.toString('hex'),
'body_enc': bodyEncrypted
}).then(res=>{
//console.log('postEncrypted return: ' + JSON.stringify(res.data))
const nonce2 = Buffer.from(res.data.result.Ok.nonce, 'hex')
const data = Buffer.from(res.data.result.Ok.body_enc, 'base64')
const decrypted = decrypt(key, data, nonce2)
//console.log('decrypted:' + decrypted)
resolve(JSON.parse(decrypted))
}).catch(err=>{
reject(err)
})
})
}
static initSecureAPI(){
ecdh = crypto.createECDH('secp256k1')
ecdh.generateKeys()
publicKey = ecdh.getPublicKey('hex', 'compressed')
//console.log('publickey: ' + publicKey)
return WalletServiceV3.post('init_secure_api', {
'ecdh_pubkey': publicKey
})
}
static initSharedSecret(){
return new Promise((resolve, reject)=>{
WalletServiceV3.initSecureAPI().then((res)=>{
//log.debug('initSharedSecret return: ' + JSON.stringify(res))
const remotePublicKey = res.data.result.Ok
sharedSecret = ecdh.computeSecret(remotePublicKey, 'hex', 'hex')
//console.log('sharedSecret: ' + sharedSecret)
resolve(res)
}).catch((err)=>{
reject(err)
})
})
}
static getTopLevelDirectory(){
return WalletServiceV3.postEncrypted('get_top_level_directory', {})
}
static createConfig(chainType, walletConfig, loggingConfig, torConfig){
return WalletServiceV3.postEncrypted('create_config', {
'chain_type': chainType,
'wallet_config': walletConfig,
'logging_config': loggingConfig,
'tor_config': torConfig
})
}
static createWallet(name, mnemonic, mnemonicLength, password){
return WalletServiceV3.postEncrypted('create_wallet', {
'name': name,
'mnemonic': mnemonic,
'mnemonic_length': mnemonicLength,
'password': password
})
}
static openWallet(name, password){
return new Promise((resolve, reject)=>{
WalletServiceV3.postEncrypted('open_wallet', {
'name': name,
'password': password
}).then((res)=>{
//log.debug('open_wallet return: ' + JSON.stringify(res))
token = res.result.Ok
resolve(res)
}).catch(err=>{
reject(err)
})
})
}
static isWalletOpened(){
if(token)return true
return false
}
static getNodeHeight(){
if(!token)return
return WalletServiceV3.postEncrypted('node_height', {
'token': token
})
}
static getAccounts(){
if(!token)return
return WalletServiceV3.postEncrypted('accounts', {
'token': token
})
}
static getSummaryInfo(refresh_from_node, minimum_confirmations){
if(!token)return
return WalletServiceV3.postEncrypted('retrieve_summary_info', {
'token': token,
'refresh_from_node': refresh_from_node,
'minimum_confirmations': minimum_confirmations
})
}
static getTransactions(refresh_from_node, tx_id, tx_slate_id){
if(!token)return
return WalletServiceV3.postEncrypted('retrieve_txs', {
'token': token,
'refresh_from_node': refresh_from_node,
"tx_id": tx_id,
"tx_slate_id": tx_slate_id,
})
}
static getCommits(refresh_from_node, include_spent, tx_id){
if(!token)return
return WalletServiceV3.postEncrypted('retrieve_outputs', {
'token': token,
'refresh_from_node': refresh_from_node,
'include_spent': include_spent,
'tx_id': tx_id
})
}
static cancelTransactions(tx_id, tx_slate_id){
if(!token)return
return WalletServiceV3.postEncrypted('cancel_tx', {
'token': token,
'tx_id': tx_id,
'tx_slate_id': tx_slate_id
})
}
static issueSendTransaction(tx_data){
if(!token)return
return WalletServiceV3.postEncrypted('init_send_tx', {
'token': token,
'args': tx_data
})
}
static lockOutputs(slate){
if(!token)return
return WalletServiceV3.postEncrypted('tx_lock_outputs', {
'token': token,
'slate': slate
})
}
static finalizeTransaction(slate){
if(!token)return
return WalletServiceV3.postEncrypted('finalize_tx', {
'token': token,
'slate': slate
})
}
static postTransaction(slate, is_fluff){
if(!token)return
return WalletServiceV3.postEncrypted('post_tx', {
'token': token,
'slate': slate,
'fluff': is_fluff
})
}
static startUpdater(freq){
if(!token)return
return WalletServiceV3.postEncrypted('start_updater', {
'token': token,
'frequency': freq,
})
}
static getUpdaterMessages(count){
if(!token)return
return WalletServiceV3.postEncrypted('get_updater_messages', {
'count': count,
})
}
static getSlatepackAddress(derivation_index){
if(!token)return
return WalletServiceV3.postEncrypted('get_slatepack_address', {
'token': token,
'derivation_index': derivation_index,
})
}
static createSlatepackMessage(slate, sender_index, recipients){
if(!token)return
return WalletServiceV3.postEncrypted('create_slatepack_message', {
'token': token,
'sender_index': sender_index,
'recipients': recipients,
'slate': slate
})
}
static decodeSlatepackMessage(message, secret_indices){
if(!token)return
return WalletServiceV3.postEncrypted('decode_slatepack_message', {
'token': token,
'message':message,
'secret_indices': secret_indices
})
}
static getSlateFromSlatepackMessage(message, secret_indices){
if(!token)return
return WalletServiceV3.postEncrypted('slate_from_slatepack_message', {
'token': token,
'message':message,
'secret_indices': secret_indices
})
}
}
WalletServiceV3.initClient()
export default WalletServiceV3 | 30.993355 | 87 | 0.578304 |
6fe770abc62ea53225292cb4d630e92a0d668ee0 | 253 | js | JavaScript | www/src/helpers/isCriticalError.js | LiTO773/Noodle-core | d38fd0e21a0a372ff5afe45eaf2ddac5471dc38d | [
"MIT"
] | 1 | 2020-02-25T23:57:47.000Z | 2020-02-25T23:57:47.000Z | www/src/helpers/isCriticalError.js | LiTO773/Noodle-core | d38fd0e21a0a372ff5afe45eaf2ddac5471dc38d | [
"MIT"
] | null | null | null | www/src/helpers/isCriticalError.js | LiTO773/Noodle-core | d38fd0e21a0a372ff5afe45eaf2ddac5471dc38d | [
"MIT"
] | null | null | null | /**
* Receives an erro code and return if it is critical
* @return {boolean} true if critical
*/
export default errorCode => {
switch (errorCode) {
case 2:
case 3:
case 5:
case 6:
case 7:
return true
}
return false
}
| 14.882353 | 53 | 0.596838 |
6fe7a9e5336b4f37c047e78c7b87ad08b50f46b8 | 1,673 | js | JavaScript | Software/ChromeExtension/js/not_yet_used/complex_array.js | HiLivin/HEG_ESP32 | c2bdbc8d6de62b07276def183c7e7462002be1d1 | [
"MIT"
] | 72 | 2018-07-24T19:20:03.000Z | 2022-03-31T22:40:50.000Z | Software/ChromeExtension/js/not_yet_used/complex_array.js | HiLivin/HEG_ESP32 | c2bdbc8d6de62b07276def183c7e7462002be1d1 | [
"MIT"
] | 3 | 2019-09-23T07:43:12.000Z | 2020-09-13T18:44:50.000Z | Software/ChromeExtension/js/not_yet_used/complex_array.js | HiLivin/HEG_ESP32 | c2bdbc8d6de62b07276def183c7e7462002be1d1 | [
"MIT"
] | 19 | 2019-02-16T23:15:47.000Z | 2022-03-31T22:40:53.000Z | class baseComplexArray {
constructor(other, arrayType = Float32Array) {
if (other instanceof baseComplexArray) {
// Copy constuctor.
this.ArrayType = other.ArrayType;
this.real = new this.ArrayType(other.real);
this.imag = new this.ArrayType(other.imag);
} else {
this.ArrayType = arrayType;
// other can be either an array or a number.
this.real = new this.ArrayType(other);
this.imag = new this.ArrayType(this.real.length);
}
this.length = this.real.length;
}
toString() {
const components = [];
this.forEach((value, i) => {
components.push(
`(${value.real.toFixed(2)}, ${value.imag.toFixed(2)})`
);
});
return `[${components.join(', ')}]`;
}
forEach(iterator) {
const n = this.length;
// For gc efficiency, re-use a single object in the iterator.
const value = Object.seal(Object.defineProperties({}, {
real: {writable: true}, imag: {writable: true},
}));
for (let i = 0; i < n; i++) {
value.real = this.real[i];
value.imag = this.imag[i];
iterator(value, i, n);
}
}
// In-place mapper.
map(mapper) {
this.forEach((value, i, n) => {
mapper(value, i, n);
this.real[i] = value.real;
this.imag[i] = value.imag;
});
return this;
}
conjugate() {
return new baseComplexArray
(this).map((value) => {
value.imag *= -1;
});
}
magnitude() {
const mags = new this.ArrayType(this.length);
this.forEach((value, i) => {
mags[i] = Math.sqrt(value.real*value.real + value.imag*value.imag);
})
return mags;
}
}
| 22.013158 | 73 | 0.563658 |
6fe824b9e45d2b22e90e1a4cb99a4c840f3e3b45 | 5,854 | js | JavaScript | gulpfile.js | spacegospod/Crate | 784d6f672c67990a47019004ade3c70729910d3a | [
"0BSD"
] | 1 | 2016-06-19T05:33:37.000Z | 2016-06-19T05:33:37.000Z | gulpfile.js | spacegospod/Crate | 784d6f672c67990a47019004ade3c70729910d3a | [
"0BSD"
] | null | null | null | gulpfile.js | spacegospod/Crate | 784d6f672c67990a47019004ade3c70729910d3a | [
"0BSD"
] | null | null | null | const gulp = require('gulp'),
concat = require('gulp-concat'),
ts = require('gulp-typescript'),
uglify = require('gulp-uglify'),
jsonMinify = require('gulp-json-minify'),
zip = require('gulp-zip'),
del = require('del'),
run = require('run-sequence');
/* ------ CLEANUP STEPS ------ */
// Deletes all output directories and files
gulp.task('clean', function() {
return del(['build/', 'publish/', 'repo/']);
});
/* ------ EDITOR STEPS ------ */
// Builds the Crate editor client and
// publishes it to the repository
gulp.task('editor-client', function() {
return gulp.src(['repo/engine-client.ts',
'src/game/client/**/*.ts',
'src/editor/client/**/*.ts'])
.pipe(ts({
target: 'ES5',
noImplicitAny: false,
out: 'editor.js'
}))
.pipe(gulp.dest('build/editor/'));
});
// Packages the editor index file
gulp.task('editor-index', function() {
return gulp.src('src/editor/client/index.html')
.pipe(gulp.dest('build/editor/'));
});
// Builds the Crate editor server and
// publishes it to the build directory
gulp.task('editor-server', function() {
return gulp.src(['repo/engine-server.js', 'src/editor/server/**/*.js'])
.pipe(concat('editor-server.js'))
.pipe(gulp.dest('build/editor/'));
});
// Runs all tasks and packages the editor.
// Needs a packaged game to run
gulp.task('install-editor',
[
'editor-client',
'editor-server',
'editor-index'
], function() {
return;
});
/* ------ GAME AND ENGINE STEPS ------ */
// Builds the Crate engine client and
// publishes it to the repository
gulp.task('engine-client', function() {
return gulp.src('src/engine/client/**/*.ts')
.pipe(concat('engine-client.ts'))
.pipe(gulp.dest('repo/'));
});
// Builds the Crate engine server and
// publishes its uglified version to the repository
gulp.task('engine-server', function() {
return gulp.src('src/engine/server/**/*.js')
.pipe(concat('engine-server.js'))
.pipe(gulp.dest('repo/'));
});
// Builds the Crate game server and
// publishes its uglified version to the build directory
gulp.task('game-server', function() {
return gulp.src(['repo/engine-server.js',
'src/game/server/updatesProcessor.js',
'src/game/server/server.js'])
.pipe(concat('server.js'))
.pipe(uglify())
.on('error', function(e) {
console.log(e);
})
.pipe(gulp.dest('build/sources/'));
});
// Builds the Crate game client and
// publishes its uglified version to the build directory
gulp.task('game-client', function() {
return gulp.src(['repo/engine-client.ts',
'src/game/client/util/**/*.ts',
'src/game/client/world/**/*.ts',
'src/game/client/objects/**/*.ts',
'src/game/client/Main.ts'])
.pipe(ts({
target: 'ES5',
noImplicitAny: false,
removeComments: true,
out: 'game.js'
}))
.pipe(uglify())
.on('error', function(e) {
console.log(e);
})
.pipe(gulp.dest('build/sources/'));
});
// Builds the Crate game client in debug mode and
// publishes it to the build directory
gulp.task('game-client-debug', function() {
return gulp.src(['repo/engine-client.ts',
'src/game/client/util/**/*.ts',
'src/game/client/world/**/*.ts',
'src/game/client/objects/**/*.ts',
'src/game/client/Main.ts'])
.pipe(ts({
target: 'ES5',
noImplicitAny: false,
out: 'game.js'
}))
.pipe(gulp.dest('build/sources/'));
});
// Builds the Crate game server in debug mode and
// publishes it to the build directory
gulp.task('game-server-debug', function() {
return gulp.src(['repo/engine-server.js',
'src/game/server/updatesProcessor.js',
'src/game/server/server.js'])
.pipe(concat('server.js'))
.pipe(gulp.dest('build/sources/'));
});
// Packages the index files
gulp.task('index', function() {
return gulp.src('src/game/client/index.html')
.pipe(gulp.dest('build/sources'));
});
// Packages image resources
gulp.task('resources-images', function() {
return gulp.src('resources/images/**/*.*')
.pipe(gulp.dest('build/resources/images/'));
});
// Packages sound resources
gulp.task('resources-sounds', function() {
return gulp.src('resources/sounds/**/*.*')
.pipe(gulp.dest('build/resources/sounds/'));
});
// Packages game and engine metadata
gulp.task('meta', function() {
return gulp.src('meta/**/*.json')
.pipe(jsonMinify())
.pipe(gulp.dest('build/meta/'));
});
// Packages levels
gulp.task('levels', function() {
return gulp.src('levels/**/*.json')
.pipe(jsonMinify())
.pipe(gulp.dest('build/levels/'));
});
gulp.task('package', function() {
return gulp.src([
'build/sources/**/*',
'build/resources/images/**/*',
'build/resources/sounds/**/*',
'build/meta/**/*'
], {base: './build'})
.pipe(zip('crate.zip'))
.pipe(gulp.dest('publish/'));
});
// Runs all tasks and packages the game
gulp.task('install', function() {
run('engine-client',
'engine-server',
'game-client',
'game-server',
'resources-images',
'resources-sounds',
'meta',
'levels',
'index',
'package');
});
// Runs all tasks in debug mode where aplicable and packages the game
gulp.task('install-debug', function() {
run('engine-client',
'engine-server',
'game-client-debug',
'game-server-debug',
'resources-images',
'resources-sounds',
'meta',
'levels',
'index',
'package');
}); | 28.417476 | 75 | 0.5726 |
6fe846a338d956517d8cfb0feb35e587d33ede7d | 2,238 | js | JavaScript | src/infinityScroll.js | pcpl2/infinite-scroll-mithril | e81fd808d7763c13425e4754755d599bf2263325 | [
"BSD-2-Clause"
] | 1 | 2021-09-08T12:57:29.000Z | 2021-09-08T12:57:29.000Z | src/infinityScroll.js | pcpl2/infinite-scroll-mithril | e81fd808d7763c13425e4754755d599bf2263325 | [
"BSD-2-Clause"
] | null | null | null | src/infinityScroll.js | pcpl2/infinite-scroll-mithril | e81fd808d7763c13425e4754755d599bf2263325 | [
"BSD-2-Clause"
] | null | null | null | import m from 'mithril';
function runRequest(vnode) {
if(vnode.state.loading) {
return
}
vnode.state.loading = true
vnode.attrs.pageRequest(vnode.state.page, vnode.state.pageRequestParam).then((result) => {
vnode.state.page = vnode.state.page + 1
vnode.state.scrollElements = vnode.state.scrollElements.concat(result)
vnode.state.loading = false
if(result < (vnode.attrs.pageCount ? vnode.attrs.pageCount : 0)) {
vnode.state.loadNext = false
}
})
}
const InfinityScroll = () => ({
oninit(vnode) {
vnode.state.sentinel = m("div#sentinel", {style: "width: 100%"}, vnode.attrs.loadingFooter ? vnode.attrs.loadingFooter : m("div", { style: "width: 1px;height: 1px;" }))
vnode.state.scrollElements = []
vnode.state.page = 0
vnode.state.processPageData = (content) => { content.map((el) => el) }
if(vnode.attrs.processPageData != undefined) {
vnode.state.processPageData = vnode.attrs.processPageData;
}
vnode.state.loadNext = true
if(vnode.attrs.pageRequestParam != undefined) {
vnode.state.pageRequestParam = vnode.attrs.pageRequestParam
}
const options = {
root: null, //window by default
rootMargin: '0px',
threshold: 0
}
if(vnode.attrs.preload) {
runRequest(vnode)
}
vnode.state.io = new IntersectionObserver(_ => {
runRequest(vnode)
}, options)
},
oncreate(vnode) {
vnode.state.io.observe(document.querySelector('#sentinel'))
},
onupdate(vnode) {
if(vnode.attrs.pageRequestParam != undefined || vnode.state.pageRequestParam != undefined) {
if(Object.entries(vnode.state.pageRequestParam).toString() != Object.entries(vnode.attrs.pageRequestParam).toString()) {
vnode.state.pageRequestParam = vnode.attrs.pageRequestParam;
vnode.state.scrollElements = [];
vnode.state.page = 0;
vnode.state.loadNext = true;
m.redraw();
}
}
},
onbeforeremove(vnode) {
vnode.state.io.unobserve(document.querySelector('#sentinel'))
},
view(vnode) {
return [
vnode.state.processPageData(vnode.state.scrollElements),
vnode.state.loadNext ? vnode.state.sentinel : []
]
}
})
export default InfinityScroll;
| 30.657534 | 172 | 0.658624 |
6fe87fbdfbb0b0646395cb7b3251ef0250eab27f | 5,683 | js | JavaScript | src/MovieClipInstance.js | SpringRoll/springroll-pixi-animate | 6971e98d83f218a745d9e227542021c201cbb7a6 | [
"MIT"
] | null | null | null | src/MovieClipInstance.js | SpringRoll/springroll-pixi-animate | 6971e98d83f218a745d9e227542021c201cbb7a6 | [
"MIT"
] | null | null | null | src/MovieClipInstance.js | SpringRoll/springroll-pixi-animate | 6971e98d83f218a745d9e227542021c201cbb7a6 | [
"MIT"
] | null | null | null | /**
* @module SpringRoll Plugin
* @namespace springroll.pixi.animate
* @requires Pixi Animate
*/
(function(undefined)
{
var MovieClip = include('PIXI.animate.MovieClip');
var AnimatorInstance = include('springroll.AnimatorInstance');
var Animator = include('PIXI.animate.Animator');
var Application = include("springroll.Application");
/**
* The plugin for working with movieclip and animator
* @class MovieClipInstance
* @extends springroll.AnimatorInstance
* @private
*/
var MovieClipInstance = function()
{
AnimatorInstance.call(this);
/**
* The start time of the current animation on the movieclip's timeline.
* @property {Number} startTime
*/
this.startTime = 0;
/**
* Length of current animation in frames.
* @property {int} length
*/
this.length = 0;
/**
* The frame number of the first frame of the current animation. If this is -1, then the
* animation is currently a pause instead of an animation.
* @property {int} firstFrame
*/
this.firstFrame = -1;
/**
* The frame number of the last frame of the current animation.
* @property {int} lastFrame
*/
this.lastFrame = -1;
};
/**
* Required to test clip
* @method test
* @static
* @param {*} clip The object to test
* @return {Boolean} If the clip is compatible with this plugin
*/
MovieClipInstance.test = function(clip)
{
return clip instanceof MovieClip;
};
/**
* Checks if animation exists
* @method hasAnimation
* @static
* @param {*} clip The clip to check for an animation.
* @param {String} event The frame label event (e.g. "onClose" to "onClose_stop")
* @return {Boolean} does this animation exist?
*/
GenericMovieClipInstance.hasAnimation = function(clip, event)
{
//the wildcard event plays the entire timeline
if (event == "*" && !clip.labelsMap[event])
{
return true;
}
var startFrame = -1;
var stopFrame = -1;
var stopLabel = event + Animator.STOP_LABEL;
var loopLabel = event + Animator.LOOP_LABEL;
startFrame = instance.labelsMap[label];
stopFrame = instance.labelsMap[label + Animator.STOP_LABEL];
if (stopFrame === -1) {
stopFrame = instance.labelsMap[label + Animator.LOOP_LABEL];
}
return startFrame >= 0 && stopFrame > 0;
};
/**
* Calculates the duration of an animation or list of animations.
* @method getDuration
* @static
* @param {*} clip The clip to check.
* @param {String} event The animation or animation list.
* @return {Number} Animation duration in milliseconds.
*/
GenericMovieClipInstance.getDuration = function(clip, event)
{
//make sure the movieclip has a framerate
if (!clip.framerate)
{
clip.framerate = Application.instance.options.fps || 15;
}
//the wildcard event plays the entire timeline
if (event == "*" && !clip.labelsMap[event])
{
return clip.totalFrames / clip.framerate * 1000;
}
var startFrame = -1;
var stopFrame = -1;
var stopLabel = event + Animator.STOP_LABEL;
var loopLabel = event + Animator.LOOP_LABEL;
startFrame = instance.labelsMap[label];
stopFrame = instance.labelsMap[label + Animator.STOP_LABEL];
if (stopFrame === -1) {
stopFrame = instance.labelsMap[label + Animator.LOOP_LABEL];
}
if (startFrame >= 0 && stopFrame > 0)
{
return (stopFrame - startFrame) / clip.framerate * 1000;
}
else
{
return 0;
}
};
// Inherit the AnimatorInstance
var s = AnimatorInstance.prototype;
var p = AnimatorInstance.extend(MovieClipInstance, AnimatorInstance);
p.init = function(clip)
{
//make sure clip has a framerate
if (!clip.framerate)
{
clip.framerate = Application.instance.options.fps || 15;
}
clip.selfAdvance = false;
this.clip = clip;
this.isLooping = false;
this.currentName = null;
this.position = this.duration = 0;
};
p.beginAnim = function(animObj, isRepeat)
{
//calculate frames, duration, etc
//then gotoAndPlay on the first frame
var label = this.currentName = animObj.anim;
var l, first = -1,
last = -1,
loop = false;
//the wildcard event plays the entire timeline
if (anim == "*" && !this.clip.labelsMap[anim])
{
first = 0;
last = this.clip.totalFrames - 1;
loop = !!animObj.loop;
}
else
{
first = instance.labelsMap[label];
last = instance.labelsMap[label + Animator.STOP_LABEL];
if (last === undefined) {
last = instance.labelsMap[label + Animator.LOOP_LABEL];
loop = true;
}
}
this.firstFrame = first;
this.lastFrame = last;
this.length = last - first;
this.isLooping = loop;
var fps = this.clip.framerate;
this.startTime = this.firstFrame / fps;
this.duration = this.length / fps;
if (isRepeat)
{
this.position = 0;
}
else
{
var animStart = animObj.start || 0;
this.position = animStart < 0 ? Math.random() * this.duration : animStart;
}
this.clip.play();
this.clip.elapsedTime = this.startTime + this.position;
this.clip.advance();
};
/**
* Ends animation playback.
* @method endAnim
*/
p.endAnim = function()
{
this.clip.gotoAndStop(this.lastFrame);
};
/**
* Updates position to a new value, and does anything that the clip needs, like updating
* timelines.
* @method setPosition
* @param {Number} newPos The new position in the animation.
*/
p.setPosition = function(newPos)
{
this.position = newPos;
this.clip.elapsedTime = this.startTime + newPos;
//because the movieclip only checks the elapsed time here (tickEnabled is false),
//calling advance() with no parameters is fine - it won't advance the time
this.clip.advance();
};
// Assign to namespace
namespace('springroll.pixi.animate').MovieClipInstance = MovieClipInstance;
}()); | 25.484305 | 90 | 0.674644 |
b50ac7b5855ffd4f60c45a0f08230aae17600a85 | 5,307 | js | JavaScript | app/components/layout/TabbedPage.js | zubairzia0/decrediton | ae5f57fe013674a278f2abd10d29ffc380c4934a | [
"ISC"
] | null | null | null | app/components/layout/TabbedPage.js | zubairzia0/decrediton | ae5f57fe013674a278f2abd10d29ffc380c4934a | [
"ISC"
] | null | null | null | app/components/layout/TabbedPage.js | zubairzia0/decrediton | ae5f57fe013674a278f2abd10d29ffc380c4934a | [
"ISC"
] | null | null | null | import { classNames } from "pi-ui";
import { Switch, Route, matchPath } from "react-router-dom";
import { isArray } from "util";
import { RoutedTabsHeader, RoutedTab } from "shared";
import { TransitionMotion, spring } from "react-motion";
import theme from "theme";
import {
createElement as h,
cloneElement as k,
useEffect,
useState,
useReducer
} from "react";
import { useSelector } from "react-redux";
import * as sel from "selectors";
import { usePrevious } from "helpers";
export const TabbedPageTab = ({ children }) => children;
TabbedPageTab.propTypes = {
path: PropTypes.string.isRequired,
link: PropTypes.node.isRequired
};
function getTabs(children) {
if (!isArray(children)) children = [children];
return children
.filter((c) => c.type === TabbedPageTab)
.map((c, i) => ({ index: i, tab: c }));
}
function getMatchedTab(location, children) {
const tabs = getTabs(children);
return tabs.find(
(t) => !!matchPath(location.pathname, { path: t.tab.props.path })
);
}
function getStyles(matchedTab) {
if (!matchedTab) {
return [];
}
const element = React.isValidElement(matchedTab.tab.props.component)
? k(matchedTab.tab.props.component, {
...matchedTab.tab.props,
...matchedTab.tab.props.component.props
})
: // If the component props are needed, it is needed to make it a valid react element
// before send, otherwise they will be undfined.
h(matchedTab.tab.props.component, { ...matchedTab.tab.props }, null);
return [
{
key: matchedTab.tab.props.path,
data: { matchedTab, element },
style: { left: spring(0, theme("springs.tab")), opacity: 1 }
}
];
}
function willLeave(dir) {
const pos = dir === "l2r" ? -1000 : +1000;
return {
left: spring(pos, { stiffness: 180, damping: 20 }),
opacity: spring(0)
};
}
function willEnter(dir) {
const pos = dir === "l2r" ? +1000 : -1000;
return { left: pos, opacity: 1 };
}
// returns the state.styles in a static container, without animations.
function staticStyles(styles) {
return (
<>
{styles.map((s) => (
<div className="tab-content visible" key={s.key}>
{s.data.element}
</div>
))}
</>
);
}
// returns the state.styles wrapped in a TransitionMotion, to show the animations
function animatedStyles(styles, dir) {
return (
<TransitionMotion
styles={styles}
willLeave={() => willLeave(dir)}
willEnter={() => willEnter(dir)}>
{(interpolatedStyles) => {
return (
<>
{interpolatedStyles.map((s) => {
return (
<div
className={[
"tab-content",
Math.abs(s.style.left) < 0.1 ? "visible" : ""
].join(" ")}
style={{
left: s.style.left,
right: -s.style.left,
opacity: s.style.opacity,
visibility: Math.abs(s.style.left) > 990 ? "hidden" : ""
}}
key={s.key}>
{s.data.element}
</div>
);
})}
</>
);
}}
</TransitionMotion>
);
}
function TabbedPage({ children, header, className, onChange, caret }) {
const location = useSelector(sel.location);
const uiAnimations = useSelector(sel.location);
const [matchedTab, setMatchedTab] = useReducer(() =>
getMatchedTab(location, children)
);
const previous = usePrevious({ matchedTab, location });
const [dir, setDir] = useState("l2r");
useEffect(() => {
setMatchedTab(getMatchedTab(location, children));
}, [children, location]);
useEffect(() => {
if (previous && previous.location.pathname === location.pathname) return;
if (typeof onChange === "function") onChange();
const matchedTab = getMatchedTab(location, children);
if (!matchedTab) return;
// if (previous && previous.matchedTab) is false, it probably means it is the first time rendering
// therefore we use "l2r", as it is probably the first tab.
const dir =
previous && previous.matchedTab
? previous.matchedTab.index > matchedTab.index
? "r2l"
: "l2r"
: "l2r";
setDir(dir);
setMatchedTab(matchedTab);
}, [location, previous, children, onChange]);
if (!isArray(children)) children = [children];
const tabs = children.filter(
(c) => c.type === TabbedPageTab && !c.props.disabled
);
const nonTabs = children.filter((c) => c.type !== TabbedPageTab);
const tabHeaders = tabs.map((c) => RoutedTab(c.props.path, c.props.link));
const headers = tabs.map((c) => (
<Route key={c.props.path} path={c.props.path} component={c.props.header} />
));
const styles = getStyles(matchedTab);
const tabContents = uiAnimations
? animatedStyles(styles, dir)
: staticStyles();
return (
<div className="tabbed-page">
<div className="tabbed-page-header">
{header}
<Switch>{headers}</Switch>
<RoutedTabsHeader tabs={tabHeaders} caret={caret} />
</div>
<div className={classNames("tabbed-page-body", className)}>
{tabContents}
{nonTabs}
</div>
</div>
);
}
export default TabbedPage;
| 28.686486 | 102 | 0.593367 |
6fed0f9de463496de9c52153fabcad0f6e7a0983 | 590 | js | JavaScript | test/cases/require-scripts-html/expected/assets/js/main.8a90.js | webdiscus/pug-plugin | bfeebf813fc17714d4eff654fbab38b280eb288e | [
"ISC"
] | 11 | 2021-12-23T20:34:30.000Z | 2022-03-24T15:09:18.000Z | test/cases/require-scripts-html/expected/assets/js/main.8a90.js | webdiscus/pug-plugin | bfeebf813fc17714d4eff654fbab38b280eb288e | [
"ISC"
] | 7 | 2021-12-23T20:32:10.000Z | 2022-03-31T14:03:16.000Z | test/cases/require-scripts-html/expected/assets/js/main.8a90.js | webdiscus/pug-plugin | bfeebf813fc17714d4eff654fbab38b280eb288e | [
"ISC"
] | 3 | 2022-01-27T04:41:29.000Z | 2022-03-19T13:37:24.000Z | (()=>{var e={271:(e,o,t)=>{"use strict";t.r(o),t.d(o,{default:()=>r});const r="<h2>Component</h2>"}},o={};function t(r){var n=o[r];if(void 0!==n)return n.exports;var l=o[r]={exports:{}};return e[r](l,l.exports,t),l.exports}t.d=(e,o)=>{for(var r in o)t.o(o,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:o[r]})},t.o=(e,o)=>Object.prototype.hasOwnProperty.call(e,o),t.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{const e=t(271);console.log(e())})()})(); | 590 | 590 | 0.638983 |
6fe9e8168c176ce9c53a5ed4c1894f0d59c29e0a | 5,077 | js | JavaScript | data/data.js | Nhawdge/stardew-helper | bd5dcb7dcaa612d99ea578e1bf226caca1595a82 | [
"MIT"
] | null | null | null | data/data.js | Nhawdge/stardew-helper | bd5dcb7dcaa612d99ea578e1bf226caca1595a82 | [
"MIT"
] | 1 | 2019-06-01T15:12:19.000Z | 2019-06-01T15:12:19.000Z | data/data.js | Nhawdge/stardew-helper | bd5dcb7dcaa612d99ea578e1bf226caca1595a82 | [
"MIT"
] | null | null | null | // Don't judge. I don't want to deal with ajax & github.
var data = {
"birthdays": [
{
"name": "Kent",
"date": "4",
"season": "spring"
},
{
"name": "Lewis",
"date": "7",
"season": "spring"
},
{
"name": "Vincent",
"date": "3",
"season": "spring"
},
{
"name": "Haley",
"date": "14",
"season": "spring"
},
{
"name": "Pam",
"date": "18",
"season": "spring"
},
{
"name": "Shane",
"date": "20",
"season": "spring"
},
{
"name": "Pierre",
"date": "26",
"season": "spring"
},
{
"name": "Emily",
"date": "27",
"season": "spring"
},
{
"name": "Jas",
"date": "04",
"season": "summer"
},
{
"name": "Gus",
"date": "08",
"season": "summer"
},
{
"name": "Maru",
"date": "10",
"season": "summer"
},
{
"name": "Alex",
"date": "13",
"season": "summer"
},
{
"name": "Sam",
"date": "17",
"season": "summer"
},
{
"name": "Demetrius",
"date": "19",
"season": "summer"
},
{
"name": "Dwarf",
"date": "22",
"season": "summer"
},
{
"name": "Willy",
"date": "24",
"season": "summer"
},
{
"name": "Penny",
"date": "2",
"season": "fall"
},
{
"name": "Elliott",
"date": "5",
"season": "fall"
},
{
"name": "Jodi",
"date": "11",
"season": "fall"
},
{
"name": "Abigail",
"date": "13",
"season": "fall"
},
{
"name": "Sandy",
"date": "15",
"season": "fall"
},
{
"name": "Marnie",
"date": "18",
"season": "fall"
},
{
"name": "Robin",
"date": "21",
"season": "fall"
},
{
"name": "George",
"date": "24",
"season": "fall"
},
{
"name": "Krobus ",
"date": "1",
"season": "winter"
},
{
"name": "Linus",
"date": "3",
"season": "winter"
},
{
"name": "Caroline",
"date": "7",
"season": "winter"
},
{
"name": "Sebastian",
"date": "10",
"season": "winter"
},
{
"name": "Harvey",
"date": "14",
"season": "winter"
},
{
"name": "Wizard",
"date": "17",
"season": "winter"
},
{
"name": "Evelyn",
"date": "20",
"season": "winter"
},
{
"name": "Leah",
"date": "23",
"season": "winter"
},
{
"name": "Clint",
"date": "26",
"season": "winter"
}
],
"events": [
{
"name": "Egg Festival",
"date": "13",
"season": "spring"
},
{
"name": "Flower Dance",
"date": "24",
"season": "spring"
},
{
"name": "SalmonBerry Season (15-18)",
"date": "18",
"season": "spring"
},
{
"name": "Luau",
"date": "11",
"season": "summer"
},
{
"name": "Dance of the Moonlight Jellies",
"date": "28",
"season": "summer"
},
{
"name": "Extra Beach Foragables (12-14)",
"date": "14",
"season": "summer"
},
{
"name": "Stardew Valley Fair",
"date": "16",
"season": "fall"
},
{
"name": "Spirit's Eve",
"date": "27",
"season": "fall"
},
{
"name": "Blackberries (8-11)",
"date": "11",
"season": "fall"
},
{
"name": "Festival of Ice",
"date": "8",
"season": "winter"
},
{
"name": "Night Market(15-17",
"date": "17",
"season": "winter"
},
{
"name": "Feast of the Winter Star",
"date": "25",
"season": "winter"
},
]
} | 21.696581 | 56 | 0.272208 |
6feb0f1425c326d5bf76d642f368c0c536696e97 | 47 | js | JavaScript | src/Tooltip/index.js | 13banda/material-ui | 2c365131307b2071580e8b710b26a17a6cd9cb6b | [
"MIT"
] | null | null | null | src/Tooltip/index.js | 13banda/material-ui | 2c365131307b2071580e8b710b26a17a6cd9cb6b | [
"MIT"
] | 8 | 2020-08-08T10:08:31.000Z | 2022-03-02T09:40:07.000Z | src/Tooltip/index.js | 13banda/material-ui | 2c365131307b2071580e8b710b26a17a6cd9cb6b | [
"MIT"
] | null | null | null | // @flow
export { default } from './Tooltip';
| 11.75 | 36 | 0.595745 |
6feb314c03691eec6bbe47ab3fac76ed6f8e34d8 | 371 | js | JavaScript | src/theme/index.js | TampaBayDesigners/design-challenges-2020 | 05f29a531fcd4366f015c7660d6d25785f0962b0 | [
"MIT"
] | null | null | null | src/theme/index.js | TampaBayDesigners/design-challenges-2020 | 05f29a531fcd4366f015c7660d6d25785f0962b0 | [
"MIT"
] | null | null | null | src/theme/index.js | TampaBayDesigners/design-challenges-2020 | 05f29a531fcd4366f015c7660d6d25785f0962b0 | [
"MIT"
] | null | null | null | export const Theme = {
black: 'hsla(0,0,0,1)',
white: 'hsla(100,100,100,1)',
grayDarkest: '#333333',
grayDarker: '#4F4F4F',
grayDark: '#828282',
grayLight: '#BDBDBD',
grayLighter: '#E0E0E0',
grayLightest: '#F2F2F2',
red: '#EB5757',
orange: '#e06c00',
yellow: '#F2C94C',
green: '#27AE60',
blue: '#5651FF',
purple: '#611f69',
pink: '#ea4c89'
} | 21.823529 | 31 | 0.595687 |
6febf08ef67ca9b866556e5fa2d477cb4473df28 | 5,470 | js | JavaScript | src/lib/structures/base/Store.js | dragondev/klasa | 63bec6b78aea4cd877ad26538b90f37898d7c73c | [
"MIT"
] | null | null | null | src/lib/structures/base/Store.js | dragondev/klasa | 63bec6b78aea4cd877ad26538b90f37898d7c73c | [
"MIT"
] | null | null | null | src/lib/structures/base/Store.js | dragondev/klasa | 63bec6b78aea4cd877ad26538b90f37898d7c73c | [
"MIT"
] | 1 | 2021-06-09T21:26:43.000Z | 2021-06-09T21:26:43.000Z | const { join, extname, relative, sep } = require('path');
const { Collection } = require('discord.js');
const fs = require('fs-nextra');
const { isClass } = require('../../util/util');
/**
* The common base for all stores
* @see ArgumentStore
* @see CommandStore
* @see EventStore
* @see ExtendableStore
* @see FinalizerStore
* @see InhibitorStore
* @see LanguageStore
* @see MonitorStore
* @see ProviderStore
* @see SerializerStore
* @see TaskStore
* @extends external:Collection
*/
class Store extends Collection {
constructor(client, name, holds) {
super();
/**
* The client this Store was created with
* @since 0.0.1
* @name Store#client
* @type {KlasaClient}
* @readonly
*/
Object.defineProperty(this, 'client', { value: client });
/**
* The name of what this holds
* @since 0.3.0
* @name Store#name
* @type {string}
* @readonly
*/
Object.defineProperty(this, 'name', { value: name });
/**
* The type of structure this store holds
* @since 0.1.1
* @name Store#holds
* @type {Piece}
* @readonly
*/
Object.defineProperty(this, 'holds', { value: holds });
/**
* The core directories pieces of this store can hold
* @since 0.5.0
* @name Store#coreDirectories
* @type {Set<string>}
* @readonly
* @private
*/
Object.defineProperty(this, 'coreDirectories', { value: new Set() });
}
/**
* The directory of local pieces relative to where you run Klasa from.
* @since 0.0.1
* @type {string}
* @readonly
*/
get userDirectory() {
return join(this.client.userBaseDirectory, this.name);
}
/**
* Registers a core directory to check for pieces
* @since 0.5.0
* @param {string} directory The directory to check for core pieces
* @returns {this}
* @protected
*/
registerCoreDirectory(directory) {
this.coreDirectories.add(join(directory, this.name));
return this;
}
/**
* Initializes all pieces in this store.
* @since 0.0.1
* @returns {Promise<Array<*>>}
*/
init() {
return Promise.all(this.map(piece => piece.enabled ? piece.init() : piece.unload()));
}
/**
* Loads a piece into Klasa so it can be saved in this store.
* @since 0.0.1
* @param {string} directory The directory the file is located in
* @param {string[]} file A string or array of strings showing where the file is located.
* @returns {?Piece}
*/
load(directory, file) {
const loc = join(directory, ...file);
let piece = null;
try {
const Piece = (req => req.default || req)(require(loc));
if (!isClass(Piece)) throw new TypeError('The exported structure is not a class.');
piece = this.set(new Piece(this, file, directory));
} catch (error) {
if (this.client.listenerCount('wtf')) this.client.emit('wtf', `Failed to load file '${loc}'. Error:\n${error.stack || error}`);
else this.client.console.wtf(`Failed to load file '${loc}'. Error:\n${error.stack || error}`);
}
delete require.cache[loc];
module.children.pop();
return piece;
}
/**
* Loads all of our Pieces from both the user and core directories.
* @since 0.0.1
* @returns {number} The number of Pieces loaded.
*/
async loadAll() {
this.clear();
if (!this.client.options.disabledCorePieces.includes(this.name)) {
for (const directory of this.coreDirectories) await Store.walk(this, directory);
}
await Store.walk(this);
return this.size;
}
/**
* Sets up a piece in our store.
* @since 0.0.1
* @param {Piece} piece The piece we are setting up
* @returns {?Piece}
*/
set(piece) {
if (!(piece instanceof this.holds)) return this.client.emit('error', `Only ${this} may be stored in this Store.`);
const existing = this.get(piece.name);
if (existing) this.delete(existing);
else if (this.client.listenerCount('pieceLoaded')) this.client.emit('pieceLoaded', piece);
super.set(piece.name, piece);
return piece;
}
/**
* Deletes a command from the store.
* @since 0.0.1
* @param {Piece|string} name A command object or a string representing a command or alias name
* @returns {boolean} whether or not the delete was successful.
*/
delete(name) {
const piece = this.resolve(name);
if (!piece) return false;
super.delete(piece.name);
return true;
}
/**
* Resolve a string or piece into a piece object.
* @since 0.0.1
* @param {Piece|string} name The piece object or a string representing a piece's name
* @returns {Piece}
*/
resolve(name) {
if (name instanceof this.holds) return name;
return this.get(name);
}
/**
* Defines toString behavior for stores
* @since 0.3.0
* @returns {string} This store name
*/
toString() {
return this.name;
}
/**
* Walks our directory of Pieces for the user and core directories.
* @since 0.0.1
* @param {Store} store The store we're loading into
* @param {string} [directory=store.userDirectory] The directory to walk in
* @returns {Array<Piece>}
* @private
*/
static async walk(store, directory = store.userDirectory) {
const files = await fs.scan(directory, { filter: (stats, path) => stats.isFile() && extname(path) === '.js' })
.catch(() => { if (store.client.options.createPiecesFolders) fs.ensureDir(directory).catch(err => store.client.emit('error', err)); });
if (!files) return [];
return Promise.all([...files.keys()].map(file => store.load(directory, relative(directory, file).split(sep))));
}
static get [Symbol.species]() {
return Collection;
}
}
module.exports = Store;
| 26.945813 | 138 | 0.653382 |
6fec4b0f4a23836e16d45a1ee1e37112dc00626a | 1,544 | js | JavaScript | out.js | hisland/object-tree-flat-exchange | 16964e64ed287c663c895bf5680d5a6c13bf2f6f | [
"MIT"
] | null | null | null | out.js | hisland/object-tree-flat-exchange | 16964e64ed287c663c895bf5680d5a6c13bf2f6f | [
"MIT"
] | null | null | null | out.js | hisland/object-tree-flat-exchange | 16964e64ed287c663c895bf5680d5a6c13bf2f6f | [
"MIT"
] | null | null | null | 'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var isPlainObject = require('lodash.isplainobject');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var isPlainObject__default = /*#__PURE__*/_interopDefaultLegacy(isPlainObject);
// lodash.isplainobject is not pure es module
function deepIn1(rs, prefix, obj, sep) {
for (const [key, value] of Object.entries(obj)) {
const newKey = `${prefix}${sep}${key}`;
if (isPlainObject__default['default'](value)) {
deepIn1(rs, newKey, value);
} else {
rs[newKey] = value;
}
}
}
// { aa: { bb: 1 } } => { 'aa.bb': 1 }
function fromObjectTree(obj, sep = '.') {
const rs = {};
for (const [key, value] of Object.entries(obj)) {
if (isPlainObject__default['default'](value)) {
deepIn1(rs, key, value, sep);
} else {
rs[key] = value;
}
}
return rs
}
function deepIn2(rs, key, value, sep) {
let tmp = rs;
const paths = key.split(sep);
const last = paths.pop();
for (const path of paths) {
if (!tmp[path]) tmp[path] = {};
tmp = tmp[path];
}
tmp[last] = value;
}
// { 'halo.cc': 1 } => { halo: { cc: 1 } }
function toObjectTree(obj, sep = '.') {
const rs = {};
for (const [key, value] of Object.entries(obj)) {
if (key.indexOf(sep) !== -1) {
deepIn2(rs, key, value, sep);
} else {
rs[key] = value;
}
}
return rs
}
exports.fromObjectTree = fromObjectTree;
exports.toObjectTree = toObjectTree;
| 24.507937 | 114 | 0.596503 |
6fed825c93b21f86128c63f47efc72b589db0869 | 296 | js | JavaScript | src/scripts/config/config.js | veerleprins/web-app-from-scratch-2021 | b5263550f2c64faea3c4511a9952ef201cd3cd96 | [
"MIT"
] | null | null | null | src/scripts/config/config.js | veerleprins/web-app-from-scratch-2021 | b5263550f2c64faea3c4511a9952ef201cd3cd96 | [
"MIT"
] | 11 | 2021-02-05T09:43:50.000Z | 2021-03-02T10:50:08.000Z | src/scripts/config/config.js | veerleprins/web-app-from-scratch-2021 | b5263550f2c64faea3c4511a9952ef201cd3cd96 | [
"MIT"
] | null | null | null | export const URL = `https://api.themoviedb.org/3/`;
export const posterPath = `https://image.tmdb.org/t/p/w342/`;
export const KEY = `?api_key=04d41953aef99908d20a6535b916898e`;
export const param = `&with_genres=27&without_genres=35%2C14%2C18%2C28&page=`;
export const lang = `&language=en-US`;
| 49.333333 | 78 | 0.746622 |
6fee68b07202738960a77517d107b2451f685e4f | 4,221 | js | JavaScript | src/Inverter/ESP3K5/protocol.js | sm-project-dev/sm-protocol-manager | 5709767ecc29983eed164f44a1b04b51c60aa256 | [
"MIT"
] | null | null | null | src/Inverter/ESP3K5/protocol.js | sm-project-dev/sm-protocol-manager | 5709767ecc29983eed164f44a1b04b51c60aa256 | [
"MIT"
] | null | null | null | src/Inverter/ESP3K5/protocol.js | sm-project-dev/sm-protocol-manager | 5709767ecc29983eed164f44a1b04b51c60aa256 | [
"MIT"
] | null | null | null | const _ = require('lodash');
const { BU } = require('base-util-jh');
const Model = require('./Model');
const { parsingMethod } = require('../../format/moduleDefine');
const { makeTroubleList } = require('../../utils/troubleConverter');
const onDeviceOperationStatus = {
/** @param {Buffer} buf -> LSB 로 비트 index 계산 */
[Model.BASE_KEY.operTroubleList]: buf => {
const hexBuf = buf.reverse().toString('hex');
/** @type {troubleInfo[]} */
const troubleStorage = {
'00000001': {
code: '태양전지과전류',
msg: '-',
},
'00000002': {
code: '태양전지과전압',
msg: '-',
},
'00000004': {
code: '태양전지저전압',
msg: '-',
},
'00000008': {
code: 'DCLink과전압',
msg: '-',
},
'00000010': {
code: 'DCLink저전압',
msg: '-',
},
'00000020': {
code: '인버터과전류',
msg: '-',
},
'00000040': {
code: '계통과전압',
msg: '-',
},
'00000080': {
code: '계통저전압',
msg: '-',
},
'00000100': {
code: '내부온도초과',
msg: '-',
},
'00000200': {
code: '계통과주파수',
msg: '-',
},
'00000400': {
code: '계통저주파수',
msg: '-',
},
'00000800': {
code: '태양전지과전력',
msg: '-',
},
'00001000': {
code: 'DC성분규정치초과',
msg: '-',
},
'00002000': {
code: 'DC배선누전',
msg: '-',
},
'00010000': {
code: '단독운전',
msg: '-',
},
'00020000': {
code: '인버터과전류HW',
msg: '-',
},
};
// BU.CLI(troubleStorage);
// BU.CLI(hexBuf);
return _.get(troubleStorage, hexBuf, []);
},
};
exports.onDeviceOperationStatus = onDeviceOperationStatus;
/**
*
* @param {} dialing
*/
const decodingProtocolTable = dialing => {
/** @type {decodingProtocolInfo} */
const DEFAULT = {
dialing,
length: 28, // 수신할 데이터 Byte,
decodingDataList: [
{
key: Model.BASE_KEY.pvVol,
byte: 2,
callMethod: parsingMethod.convertBufToReadInt,
scale: 0.1,
fixed: 1,
},
{
key: Model.BASE_KEY.pvAmp,
byte: 2,
callMethod: parsingMethod.convertBufToReadInt,
scale: 0.1,
fixed: 1,
},
{
key: Model.BASE_KEY.pvVol2,
byte: 2,
callMethod: parsingMethod.convertBufToReadInt,
scale: 0.1,
fixed: 1,
},
{
key: Model.BASE_KEY.gridRsVol,
byte: 2,
callMethod: parsingMethod.convertBufToReadInt,
scale: 0.1,
fixed: 1,
},
{
key: Model.BASE_KEY.gridRAmp,
byte: 2,
callMethod: parsingMethod.convertBufToReadInt,
scale: 0.1,
fixed: 1,
},
{
key: Model.BASE_KEY.operTemperature,
byte: 2,
callMethod: parsingMethod.convertBufToReadInt,
scale: 0.1,
fixed: 1,
},
{
key: Model.BASE_KEY.powerDailyKwh,
byte: 2,
callMethod: parsingMethod.convertBufToReadInt,
scale: 0.01,
fixed: 2,
},
{
key: Model.BASE_KEY.powerCpKwh,
byte: 3,
callMethod: parsingMethod.convertBufToReadInt,
},
{
key: Model.BASE_KEY.operTroubleList,
byte: 4,
},
{
key: Model.BASE_KEY.operIsRun,
byte: 1,
callMethod: parsingMethod.convertBufToReadInt,
},
{
key: Model.BASE_KEY.gridLf,
byte: 2,
callMethod: parsingMethod.convertBufToReadInt,
scale: 0.1,
fixed: 1,
},
{
key: Model.BASE_KEY.operTime,
byte: 2,
callMethod: parsingMethod.convertBufToReadInt,
},
{
key: Model.BASE_KEY.powerPf,
byte: 1,
callMethod: parsingMethod.convertBufToReadInt,
},
],
};
DEFAULT.decodingDataList.forEach(decodingInfo => {
const { callMethod } = decodingInfo;
if (callMethod === parsingMethod.convertBufToReadInt) {
decodingInfo.isLE = true;
}
});
return {
DEFAULT,
};
};
exports.decodingProtocolTable = decodingProtocolTable;
| 21.535714 | 68 | 0.493485 |
6feeef36d81dd35083a05a529a3bead0b7f74d92 | 863 | js | JavaScript | assets/report_page.js | iparips/flog-and-churn | 7289a3d61fecd7b823209f10cee20a8e4cf4835a | [
"MIT"
] | null | null | null | assets/report_page.js | iparips/flog-and-churn | 7289a3d61fecd7b823209f10cee20a8e4cf4835a | [
"MIT"
] | null | null | null | assets/report_page.js | iparips/flog-and-churn | 7289a3d61fecd7b823209f10cee20a8e4cf4835a | [
"MIT"
] | null | null | null | function onPageLoad(metrics) {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Flog');
data.addColumn('number', 'Churn');
data.addColumn({type:'string', role:'tooltip'});
var options = {
title: 'Flog & Churn',
hAxis: {title: 'Churn', minValue: 0, maxValue: 10},
vAxis: {title: 'Flog', minValue: 0, maxValue: 10},
legend: 'none'
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
rows = metricsToDataRows(metrics)
data.addRows(rows)
chart.draw(data, options);
}
function metricsToDataRows(metrics) {
return metrics.map(function(metric) {
return [ metric.times_changed, metric.flog, tooltip(metric) ]
});
}
function tooltip(metric) {
return metric.file +
"\nTimes Changed: " +
metric.times_changed +
"\nFlog: " +
metric.flog
}
| 23.324324 | 90 | 0.66628 |
6fefc31fbb30efa1ef1faf0b5f76515a63458ce9 | 644 | js | JavaScript | Gruntfile.js | Beckuro/portofolioproject | 6e696a71d7d9a5b9fc3da2cbb060f372acc7962d | [
"MIT"
] | null | null | null | Gruntfile.js | Beckuro/portofolioproject | 6e696a71d7d9a5b9fc3da2cbb060f372acc7962d | [
"MIT"
] | null | null | null | Gruntfile.js | Beckuro/portofolioproject | 6e696a71d7d9a5b9fc3da2cbb060f372acc7962d | [
"MIT"
] | null | null | null | /*
After you have changed the settings at "Your code goes here",
run this with one of these options:
"grunt" alone creates a new, completed images directory
"grunt clean" removes the images directory
"grunt responsive_images" re-processes images without removing the old ones
*/
module.exports = function(grunt) {
grunt.initConfig({
imagemin: {
dynamic: {
files: [{
expand: true,
cwd: 'images/',
src: ['**/*.{png,jpg,gif}'],
dest: 'images/'
}]
}
},
});
grunt.loadNpmTasks('grunt-contrib-imagemin');
grunt.registerTask('default', ['imagemin']);
}; | 22.206897 | 77 | 0.607143 |
6ff11386dd9e6ea46184a429423045cafbd8fcb3 | 1,487 | js | JavaScript | EthAdapter/utils/config.js | PharmaLedger-IMI/ethadapter | 62c61b45c9ff44900d31d79d1efc803e024c3589 | [
"MIT"
] | null | null | null | EthAdapter/utils/config.js | PharmaLedger-IMI/ethadapter | 62c61b45c9ff44900d31d79d1efc803e024c3589 | [
"MIT"
] | null | null | null | EthAdapter/utils/config.js | PharmaLedger-IMI/ethadapter | 62c61b45c9ff44900d31d79d1efc803e024c3589 | [
"MIT"
] | null | null | null |
module.exports = function Config(callback) {
//config map
if (typeof process.env.SMARTCONTRACTADDRESS !== "undefined")
{
console.log('Using env SMARTCONTRACTADDRESS : ', process.env.SMARTCONTRACTADDRESS);
this.contractAddress = process.env.SMARTCONTRACTADDRESS;
}else {
return callback(new Error("SMARTCONTRACTADDRESS not found."))
}
//config map
if (typeof process.env.SMARTCONTRACTABI !== "undefined")
{
console.log('Using env SMARTCONTRACTABI : ', process.env.SMARTCONTRACTABI);
this.abi = JSON.parse(process.env.SMARTCONTRACTABI);
}else {
return callback(new Error("SMARTCONTRACTABI not found."))
}
//config map
if (typeof process.env.RPC_ADDRESS !== "undefined")
{
console.log('Using env RPC_ADDRESS : ', process.env.RPC_ADDRESS);
this.rpcAddress = process.env.RPC_ADDRESS;
}else {
return callback(new Error("RPC_ADDRESS not found."))
}
//secrets - ORGACCOUNT
if (typeof process.env.ORGACCOUNT !== "undefined")
{
console.log('Using env ORGACCOUNT : ', process.env.ORGACCOUNT)
const orgacc = JSON.parse(process.env.ORGACCOUNT);
this.account = orgacc.address;
this.accountPrivateKey = orgacc.privateKey;
}else {
return callback(new Error("ORGACCOUNT not found."))
}
console.log('Finish loading data from env.');
console.log(this);
callback(undefined, this);
};
| 27.036364 | 91 | 0.644923 |
6ff2147a0ffe526c87b4330f44e304f86064b609 | 504 | js | JavaScript | components/Footer/BlogSummary.js | PaulHaze/archo | 5e4c464de328e0953791e5347035fc27ed6e9b9a | [
"MIT"
] | null | null | null | components/Footer/BlogSummary.js | PaulHaze/archo | 5e4c464de328e0953791e5347035fc27ed6e9b9a | [
"MIT"
] | null | null | null | components/Footer/BlogSummary.js | PaulHaze/archo | 5e4c464de328e0953791e5347035fc27ed6e9b9a | [
"MIT"
] | null | null | null | import Image from 'next/image';
import styles from './Footer.module.scss';
export function BlogSummary({ blogThumbImgUrl, blogTitle, blogDate }) {
return (
<div className={styles.blogSummaryContainer}>
<div className={styles.imgContainer}>
<Image src={blogThumbImgUrl} objectFit="cover" layout="fill" />
</div>
<div className={styles.textContainer}>
<p>{blogTitle}</p>
<p className="text-sm text-sand mt-5">{blogDate}</p>
</div>
</div>
);
}
| 28 | 71 | 0.636905 |
6ff2ad5a17f69340cdd5d573229f8354497dd8d9 | 396 | js | JavaScript | rules/reactRules.js | tobiasalthoff/eslint-config-epbs | 0d198120131b30b5ae591e64e192e98041a724f6 | [
"MIT"
] | null | null | null | rules/reactRules.js | tobiasalthoff/eslint-config-epbs | 0d198120131b30b5ae591e64e192e98041a724f6 | [
"MIT"
] | null | null | null | rules/reactRules.js | tobiasalthoff/eslint-config-epbs | 0d198120131b30b5ae591e64e192e98041a724f6 | [
"MIT"
] | null | null | null | // https://github.com/yannickcr/eslint-plugin-react/tree/master/docs/rules
module.exports = {
'react/forbid-prop-types': 'off',
'react/jsx-filename-extension': [
'warn',
{
extensions: ['.js', '.jsx'],
},
],
'react/no-array-index-key': 'off',
'react/prefer-stateless-function': 'off',
'react/require-default-props': 'off',
'react/jsx-props-no-spreading': 'off'
};
| 24.75 | 74 | 0.623737 |
6ff461e559a803dedfffcf7e0445aba4a6c7c78c | 5,398 | js | JavaScript | src/AppBundle/Resources/public/js/app.js | sfarkas1988/bankingStatistics | cd6e2cfd754b9cd81b954a2a59d8f3551393844d | [
"MIT"
] | null | null | null | src/AppBundle/Resources/public/js/app.js | sfarkas1988/bankingStatistics | cd6e2cfd754b9cd81b954a2a59d8f3551393844d | [
"MIT"
] | null | null | null | src/AppBundle/Resources/public/js/app.js | sfarkas1988/bankingStatistics | cd6e2cfd754b9cd81b954a2a59d8f3551393844d | [
"MIT"
] | null | null | null | var app = angular.module("banking-stats", []);
app.controller('MonthlyCtrl', function($scope, DateRangePickerService, MonthlyService) {
DateRangePickerService.init();
MonthlyService.loadData(DateRangePickerService.getUnixStart(), DateRangePickerService.getUnixEnd(), $scope);
DateRangePickerService.getObject().on('apply.daterangepicker', function(ev, picker) {
MonthlyService.loadData(DateRangePickerService.getUnixStart(), DateRangePickerService.getUnixEnd(), $scope);
});
//Morris.Area({
// element: 'morris-area-chart',
// data: [{
// period: '2010 Q1',
// iphone: 2666,
// ipad: null,
// itouch: 2647
// }, {
// period: '2010 Q2',
// iphone: 2778,
// ipad: 2294,
// itouch: 2441
// }, {
// period: '2010 Q3',
// iphone: 4912,
// ipad: 1969,
// itouch: 2501
// }, {
// period: '2010 Q4',
// iphone: 3767,
// ipad: 3597,
// itouch: 5689
// }, {
// period: '2011 Q1',
// iphone: 6810,
// ipad: 1914,
// itouch: 2293
// }, {
// period: '2011 Q2',
// iphone: 5670,
// ipad: 4293,
// itouch: 1881
// }, {
// period: '2011 Q3',
// iphone: 4820,
// ipad: 3795,
// itouch: 1588
// }, {
// period: '2011 Q4',
// iphone: 15073,
// ipad: 5967,
// itouch: 5175
// }, {
// period: '2012 Q1',
// iphone: 10687,
// ipad: 4460,
// itouch: 2028
// }, {
// period: '2012 Q2',
// iphone: 8432,
// ipad: 5713,
// itouch: 1791
// }],
// xkey: 'period',
// ykeys: ['iphone', 'ipad', 'itouch'],
// labels: ['iPhone', 'iPad', 'iPod Touch'],
// pointSize: 2,
// hideHover: 'auto',
// resize: true
//});
//
//Morris.Donut({
// element: 'morris-donut-chart',
// data: [{
// label: "Download Sales",
// value: 12
// }, {
// label: "In-Store Sales",
// value: 30
// }, {
// label: "Mail-Order Sales",
// value: 20
// }],
// resize: true
//});
//
});
app.service('MonthlyService', function(DateRangePickerService, AnimationService, StatisticService, $http){
this.loadData = function(unixStart, unixEnd, scope) {
$http.post(
'monthly/data.json',
{'start': unixStart, 'end': unixEnd }
)
.success(function(data) {
console.log(data);
scope.incomeSum = data.incomeSum;
scope.incomeCountRows = data.incomeCountRows;
scope.outcomeSum = data.outcomeSum;
scope.outcomeCountRows = data.outcomeCountRows;
scope.balance = data.balance;
AnimationService.animateWrapper();
StatisticService.printBarChart(data.categoryChart);
}
);
}
});
app.service('StatisticService', function() {
this.printBarChart = function(data) {
$.each(data, function(type, value){
var element = 'morris-bar-chart-' + type;
if(value.data.length > 0) {
$('#' + element).parent().parent().parent().removeClass('hidden');
Morris.Bar({
element: element,
data: value.data,
xkey: value.xkey,
ykeys: value.ykeys,
labels: value.labels,
hideHover: 'auto',
resize: true
});
}
});
}
});
app.service('AnimationService', function(){
this.animateWrapper = function() {
$('#page-wrapper').removeClass('hidden');
}
});
app.service('DateRangePickerService', function(){
var selector = '#reportrange';
this.getObject = function() {
return $(selector);
}
this.init = function() {
this.getObject().daterangepicker(
{
ranges: {
'Heute': [moment(), moment()],
'Gestern': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Letzte 7 Tage': [moment().subtract(6, 'days'), moment()],
'Letzte 30 Tage': [moment().subtract(29, 'days'), moment()],
'Dieser Monat': [moment().startOf('month'), moment().endOf('month')],
'Letzter Monat': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
},
startDate: moment().startOf('month'),
endDate: moment().endOf('month')
},
function(start, end) {
$(selector + ' span').html(start.format('DD.MM.YYYY') + ' - ' + end.format('DD.MM.YYYY'));
}
);
}
this.getUnixStart = function()
{
return this.getObject().data('daterangepicker').startDate.unix();
}
this.getUnixEnd = function()
{
return this.getObject().data('daterangepicker').endDate.unix();
}
}); | 28.86631 | 131 | 0.465913 |
6ff57bbd10c246938352095d34850e7bdddcd103 | 8,929 | js | JavaScript | data-visualization/cases/hamilton/src/ProcessGraph.js | zouv/frontend-boilerplates | 22becd0bca0b7aed072b883f7ddb4b77eab5225b | [
"MIT"
] | null | null | null | data-visualization/cases/hamilton/src/ProcessGraph.js | zouv/frontend-boilerplates | 22becd0bca0b7aed072b883f7ddb4b77eab5225b | [
"MIT"
] | null | null | null | data-visualization/cases/hamilton/src/ProcessGraph.js | zouv/frontend-boilerplates | 22becd0bca0b7aed072b883f7ddb4b77eab5225b | [
"MIT"
] | null | null | null | import _ from 'lodash';
import * as d3 from "d3";
// load the data
import charList from './data/char_list.json';
import songList from './data/song_list.json';
import rawLines from './data/lines.json';
import themeList from './data/theme_list.json';
import rawCharacters from './data/characters.json';
import rawThemes from './data/themes.json';
var themeScale = d3.scaleLinear().range([24, 48]);
var themeColor = d3.scaleOrdinal(d3.schemeCategory20);
var linkScale = d3.scaleLinear().range([3, 10]);
// taken directly from nbremer's occupationcanvas code
//Generates the next color in the sequence, going from 0,0,0 to 255,255,255.
//From: https://bocoup.com/weblog/2d-picking-in-canvas
var nextCol = 1;
function genColor(){
var ret = [];
// via http://stackoverflow.com/a/15804183
if(nextCol < 16777215){
ret.push(nextCol & 0xff); // R
ret.push((nextCol & 0xff00) >> 8); // G
ret.push((nextCol & 0xff0000) >> 16); // B
nextCol += 100; // This is exagerated for this example and would ordinarily be 1.
}
var col = "rgb(" + ret.join(',') + ")";
return col;
}
var ProcessGraph = {
processLinesSongs(width) {
var hoverLookup = {};
// duplicate any of the lines sung by multiple characters
var lines = _.chain(rawLines)
.map((line, lineId) => {
var songId = lineId.split(':')[0];
var startLine = parseInt(lineId.split(':')[1].split('-')[0], 10)
// get all characters from the line
return _.map(line[1][0], (character, i) => {
var id = character + '/' + lineId;
var hoverFill = genColor();
var processedLine = {
id,
lineId,
songId,
startLine,
characterId: character,
characterName: charList[character][0],
songName: songList[songId][0],
numSingers: line[1][0].length,
singerIndex: i,
lineLength: line[2].length,
conversing: null,
themes: [],
fill: charList[character][4],
hoverFill,
selected: true,
data: line,
x: line.x || _.random(window.innerWidth * -0.5, window.innerWidth * 1.5),
y: line.y || _.random(window.innerHeight * -0.5, window.innerHeight * 1.5),
};
hoverLookup[hoverFill] = processedLine;
return processedLine;
});
}).flatten().value();
var songs = _.chain(rawLines)
.groupBy(line => line[0].split(':')[0])
.map((lines, id) => {
return {
id,
name: songList[id][0],
selected: true,
lineLength: _.reduce(lines, (sum, line) => sum + line[2].length, 0),
}
}).value();
return {songs, lines, hoverLookup};
},
processCharacters(lines, width, height) {
var radius = 20;
var linesById = _.groupBy(lines, 'lineId');
var filteredCharList = _.pickBy(charList, char => char[3]);
// character nodes
var characters = _.chain(rawCharacters.characters)
.map((lines, id) => {
var character = filteredCharList[id];
if (!character) return null;
var name = character[0];
var initials = _.map(name.split(' '), 0).join('');
return {
id,
name,
initials,
radius,
fx: id === '2' ? 0 : null,
fy: id === '2' ? 0 : null,
color: character[4],
selected: true,
numLines: lines.length,
available: true,
};
}).filter().value();
var charactersById = _.keyBy(characters, 'id');
// character links
var conversingValues = _.values(rawCharacters.conversing);
var minWidth = _.minBy(conversingValues, (lines) => lines.length).length;
var maxWidth = _.maxBy(conversingValues, (lines) => lines.length).length;
linkScale.domain([minWidth, maxWidth]);
var conversations = _.chain(rawCharacters.conversing)
.map((lines, conversing) => {
var source = conversing.split('-');
var target = charactersById[source[1]];
source = charactersById[source[0]];
if (!source || !target) return null;
var weight = linkScale(lines.length);
_.each(lines, lineId => {
// for each line that has this conversation,
// there could be multiple characters, so go through them all
_.each(linesById[lineId], line => {
if (line.characterId === source.id) {
line.conversing = conversing;
}
});
});
return {
id: conversing,
color: source.color,
selected: true,
available: true,
source, target, weight,
};
}).filter().value();
// position them right away
var simulation = d3.forceSimulation(characters)
.force('collide', d3.forceCollide().radius(radius * 2.5))
// .force('y', d3.forceY().y(d => d.focusY))
.force('charge', d3.forceManyBody().strength(-radius))
.force('link', d3.forceLink(conversations).distance(radius))
.force("center", d3.forceCenter())
.stop();
_.times(1000, simulation.tick);
return {characters, conversations};
},
processThemes(lines) {
var linesById = _.groupBy(lines, 'lineId');
var diamonds = _.chain(rawThemes)
.map((lineKeys, theme) => {
if (!themeList[theme][2]) return null;
return _.map(lineKeys, (lineKey) => {
var lineId = lineKey[0][0];
var songId = parseInt(lineId.split(':')[0], 10);
var startLine = lineId.split(':')[1].split('/');
var startLineId = songId + ':' + startLine[1];
startLine = parseInt(startLine[0], 10);
var endLine = _.last(lineKey[0]).split(':')[1].split('/');
var endLineId = songId + ':' + endLine[1];
endLine = parseInt(endLine[0], 10);
return {
id: theme + '/' + songId + ':' + startLine,
themeId: theme,
themeType: themeList[theme][1],
themeLines: themeList[theme][0],
lineId: lineId.split('/')[0],
songId,
startLine,
endLine,
startLineId,
endLineId,
fill: themeColor(theme),
keys: lineKey[0],
// lines: lineKey[1],
selected: true,
available: true,
}
});
}).filter().flatten()
.value();
var groupedThemes = _.chain(diamonds)
.groupBy(diamond => diamond.themeType)
.map((diamonds, themeType) => {
diamonds = _.chain(diamonds)
.groupBy(diamond => diamond.themeId)
.sortBy(diamonds => diamonds.length)
.map((diamonds, groupId) => {
// add group id's to each of the diamonds
groupId += 1;
_.each(diamonds, theme => theme.groupId = groupId);
return {
id: diamonds[0].themeId,
themeType,
groupId,
lines: diamonds[0].themeLines,
length: diamonds.length,
fill: diamonds[0].fill,
diamonds,
}
}).value();
return {name: themeType, diamonds};
}).sortBy(theme => -theme.diamonds.length).value();
// position the grouped themes
var padding = 5;
var maxDiamonds = _.chain(groupedThemes).map('diamonds')
.flatten().maxBy('length').value().length;
themeScale.domain([1, maxDiamonds]);
_.each(groupedThemes, theme => {
var x = padding;
_.each(theme.diamonds, diamond => {
diamond.x = x;
diamond.x2 = _.round(themeScale(diamond.length), 2);
x += diamond.x2 + 2 * padding;
});
theme.width = x;
});
// and go through all the diamonds just one last time
// for their character id's, conversation id's, and lines
diamonds = _.map(diamonds, diamond => {
var characterIds = [];
var conversationIds = [];
var groupedThemeId = diamond.themeType[0].toLowerCase() + diamond.groupId;
// add themes to the lines
_.chain(diamond.keys)
.map((lineId) => lineId.split(':')[0] + ':' + lineId.split('/')[1])
.uniq()
.each((lineId) => {
// have to loop through all the lines bc could have multiple characters
_.each(linesById[lineId], (line) => {
line.themes.push([diamond.themeId, diamond.startLine, diamond.endLine, diamond.themeType]);
// also add in characters
characterIds.push(line.characterId);
conversationIds.push(line.conversing);
});
}).value();
return Object.assign(diamond, {
groupedThemeId,
characterIds: _.uniq(characterIds),
conversationIds: _.uniq(conversationIds),
});
});
return {diamonds, groupedThemes};
},
}
export default ProcessGraph;
| 33.07037 | 103 | 0.556389 |
6ff79c1ac405061b94186e405b0cf0a7dcf0a863 | 2,581 | js | JavaScript | node_modules/neo.mjs/node_modules/siesta-lite/lib/Siesta/Test/Simulator.js | dnabusinessintelligence/production | 4da3f443392b20a334a53022c5e1f6e445558e0a | [
"MIT"
] | null | null | null | node_modules/neo.mjs/node_modules/siesta-lite/lib/Siesta/Test/Simulator.js | dnabusinessintelligence/production | 4da3f443392b20a334a53022c5e1f6e445558e0a | [
"MIT"
] | null | null | null | node_modules/neo.mjs/node_modules/siesta-lite/lib/Siesta/Test/Simulator.js | dnabusinessintelligence/production | 4da3f443392b20a334a53022c5e1f6e445558e0a | [
"MIT"
] | null | null | null | /*
Siesta 5.3.2
Copyright(c) 2009-2020 Bryntum AB
https://bryntum.com/contact
https://bryntum.com/products/siesta/license
*/
Class('Siesta.Test.Simulator', {
does : [
Siesta.Util.Role.CanGetType,
Siesta.Test.Browser.Role.CanRebindJQueryContext,
Siesta.Test.Simulate.Event,
Siesta.Test.Simulate.Mouse,
Siesta.Test.Simulate.Keyboard,
Siesta.Test.Simulate.Touch
],
has : {
type : 'synthetic',
test : null,
global : null
},
methods : {
initialize : function () {
this.SUPER();
this.onBlur = this.onBlur.bind(this);
},
onTestLaunch : function (test) {
var me = this;
me.test = test
me.global = test.global
// Synthetic events unfortunately doesn't trigger change events on blur of an INPUT
if (me.type === 'synthetic') {
var inputFiresChangeAfterLosingFocus = Siesta.Project.Browser.FeatureSupport().supports.inputFiresChangeAfterLosingFocus;
if (!inputFiresChangeAfterLosingFocus) {
me.global.document.documentElement.addEventListener('blur', me.onBlur, true);
}
}
},
onBlur : function (e) {
if (e.target && this.test.isTextInput(e.target)) {
this.maybeMimicChangeEvent(e.target);
}
},
cleanup : function () {
// Added check that global exists, made tests crash without
this.global && this.global.document.documentElement.removeEventListener('blur', this.onBlur, true);
this.test = null
this.global = null
},
setSpeed : function (name) {
Joose.O.extend(this, Siesta.Test.Simulator.speedPresets[name]);
}
}
});
Siesta.Test.Simulator.speedPresets = {
slow : {
actionDelay : 100,
afterActionDelay : 100,
dragDelay : 25,
pathBatchSize : 5,
mouseMovePrecision : 1,
mouseDragPrecision : 1
},
speedRun : {
actionDelay : 1,
afterActionDelay : 100,
dragDelay : 10,
pathBatchSize : 30,
mouseMovePrecision : 1,
mouseDragPrecision : 1
},
turboMode : {
actionDelay : 1,
afterActionDelay : 1,
dragDelay : 0,
pathBatchSize : 100,
mouseMovePrecision : Infinity,
mouseDragPrecision : Infinity
}
};
| 25.554455 | 137 | 0.543588 |
6ff7b92fd5c9a33834cdbc4affd509cc3ae8fd77 | 244 | js | JavaScript | store/user.js | yqw19920724/realworld-nuxt-demo | eb48bde8ac4ba648b28874aa1155b81f281ef710 | [
"MIT"
] | null | null | null | store/user.js | yqw19920724/realworld-nuxt-demo | eb48bde8ac4ba648b28874aa1155b81f281ef710 | [
"MIT"
] | null | null | null | store/user.js | yqw19920724/realworld-nuxt-demo | eb48bde8ac4ba648b28874aa1155b81f281ef710 | [
"MIT"
] | null | null | null | export const state = () => ({
user: ''
})
export const mutations = {
setUser(state, payload) {
state.user = payload
}
}
export const actions = {
setUser({ commit }, payload) {
commit('setUser', payload)
}
} | 16.266667 | 34 | 0.545082 |
6ff82aa8103fd33f34a96919be9505ef09af4ceb | 4,410 | js | JavaScript | gulptest/dist/script/home.js | 1610736291/project | 2e96c718a6803329f0c792c60ca8e03170fbd1ba | [
"MIT"
] | null | null | null | gulptest/dist/script/home.js | 1610736291/project | 2e96c718a6803329f0c792c60ca8e03170fbd1ba | [
"MIT"
] | null | null | null | gulptest/dist/script/home.js | 1610736291/project | 2e96c718a6803329f0c792c60ca8e03170fbd1ba | [
"MIT"
] | null | null | null | "use strict";!function(a){var n=a(".banner"),t=a(".banner ul"),l=a(".banner ul li"),e=a(".banner p span"),i=a(".banner .wrapper .left"),o=a(".banner .wrapper .right"),c=0,s=null,p=l.eq(0).width();function r(){++c>e.length-1&&(t.stop(!0).animate({left:-p*c},400),c=0),c<0&&(t.stop(!0).animate({left:-p*c},400),c=e.length-1),c===e.length?e.eq(0).addClass("active").siblings().removeClass("active"):e.eq(c).addClass("active").siblings().removeClass("active"),t.stop(!0).animate({left:-p*c},400)}t.width(l.length*p),e.on("click",function(){console.log(c),c=a(this).index()-1,console.log(c),r()}),i.hover(function(){i.css({background:"black"})},function(){i.css({background:"transparent"})}),o.hover(function(){o.css({background:"black"})},function(){o.css({background:"transparent"})}),o.on("click",function(){r()}),i.on("click",function(){console.log(c),c-=2,r(),console.log(c)}),s=setInterval(function(){o.click()},3e3),n.hover(function(){clearInterval(s)},function(){s=setInterval(function(){o.click()},3e3)}),a(".top").click(function(){a("body, html").animate({scrollTop:0},1e3)}),a(".grzx").on("mouseover",function(){a(".grzx p").show(),a(".grzx p").stop(!0).animate({opacity:1,left:-78},400)}),a(".grzx").on("mouseout",function(){a(".grzx p").stop(!0).animate({left:-120,opacity:0},400)}),a(".wdgz").on("mouseover",function(){a(".wdgz p").show(),a(".wdgz p").stop(!0).animate({opacity:1,left:-78},400)}),a(".wdgz").on("mouseout",function(){a(".wdgz p").stop(!0).animate({left:-120,opacity:0},400)}),a(".zxkf").on("mouseover",function(){a(".zxkf p").show(),a(".zxkf p").stop(!0).animate({opacity:1,left:-78},400)}),a(".zxkf").on("mouseout",function(){a(".zxkf p").stop(!0).animate({left:-120,opacity:0},400)});var u=a(".dota_pic ul");a.ajax({url:"http://10.31.152.13/project/gulptest/php/dotadata.php",dataType:"json"}).done(function(n){var t='\n <li class="l1"><img src="http://img.shop.wanmei.com/upload/moduleScroll/2018-06-11/7cef96d122b64cf7976e4233ef0bbc07.jpg" alt=""></li>\n ';a.each(n,function(n,a){t+='\n <li>\n <a href="detail.html?sid='+a.sid+'">\n <img class="lazy" data-original="'+a.src+'" alt="">\n <p class="title">'+a.title+'</p>\n <p class="price">'+a.price+"</p>\n </a>\n </li>\n "}),u.html(t),a(function(){a("img.lazy").lazyload({effect:"fadeIn"})})});var d=a(".wmsj_pic ul");a.ajax({url:"http://10.31.152.13/project/gulptest/php/wmsjdata.php",dataType:"json"}).done(function(n){var t='\n <li class="l1">\n <img src="http://img.shop.wanmei.com/upload/moduleScroll/2016-07-25/b24a4280-eb2a-4cc6-ba6e-97a97dde6c9c.jpg" alt="">\n </li>\n ';a.each(n,function(n,a){t+='\n <li>\n <a href="detail.html?sid='+a.sid+'">\n <img class="lazy" data-original="'+a.src+'" alt="">\n <p class="title">'+a.title+'</p>\n <p class="price">'+a.price+"</p>\n </a>\n </li>\n "}),d.html(t),a(function(){a("img.lazy").lazyload({effect:"fadeIn"})})});var f=a(".csgo_pic ul");a.ajax({url:"http://10.31.152.13/project/gulptest/php/csgodata.php",dataType:"json"}).done(function(n){var t="";a.each(n,function(n,a){t+='\n <li>\n <a href="detail.html?sid='+a.sid+'">\n <img class="lazy" data-original="'+a.src+'" alt="">\n <p class="title">'+a.title+'</p>\n <p class="price">'+a.price+"</p>\n </a>\n </li>\n "}),f.html(t),a(function(){a("img.lazy").lazyload({effect:"fadeIn"})})});var g=a(".jxh_pic ul");a.ajax({url:"http://10.31.152.13/project/gulptest/php/jxhdata.php",dataType:"json"}).done(function(n){var t='\n <li class="l1">\n <img src="http://img.shop.wanmei.com/upload/moduleScroll/2016-09-12/b31b587d-eb0c-4c0f-9e99-bd2185325d08.jpg" alt="">\n </li> \n ';a.each(n,function(n,a){t+='\n <li>\n <a href="detail.html?sid='+a.sid+'">\n <img class="lazy" data-original="'+a.src+'" alt="">\n <p class="title">'+a.title+'</p>\n <p class="price">'+a.price+"</p>\n </a>\n </li>\n "}),g.html(t),a(function(){a("img.lazy").lazyload({effect:"fadeIn"})})})}(jQuery); | 4,410 | 4,410 | 0.551247 |
6ff86b2f05f81fe8d40e0a46c547fd28cdf3a12e | 794 | js | JavaScript | src/views/item/index.js | notYou263/svantic | bdd641b8e9b5c49aef3ead4c4e25946c4521681b | [
"MIT"
] | null | null | null | src/views/item/index.js | notYou263/svantic | bdd641b8e9b5c49aef3ead4c4e25946c4521681b | [
"MIT"
] | null | null | null | src/views/item/index.js | notYou263/svantic | bdd641b8e9b5c49aef3ead4c4e25946c4521681b | [
"MIT"
] | null | null | null |
import { default as Items } from './items.svelte'
import { default as Item } from './item.svelte'
import { default as Content } from './content.svelte'
import { default as Image } from './image.svelte'
import { default as Link } from './link.svelte'
import { default as Description } from './description.svelte'
import { default as Extra } from './extra.svelte'
import { default as Header } from './header.svelte'
import { default as Meta } from './meta.svelte'
import { default as Rating } from './rating.svelte'
Item.content = Content
Item.image = Image
Item.link = Link
Item.description = Description
Item.extra = Extra
Item.header = Header
Item.meta = Meta
Item.rating = Rating
export { Items, Item, Content, Description, Extra, Header, Image, Link, Meta, Rating }
export default Item
| 30.538462 | 86 | 0.720403 |
6ff8bc52f0c91bf22bfe521405246b6424da54e4 | 323 | js | JavaScript | app/plugins/i18n.js | fightforthefuture/earth-day-live | 2a7e6acd210ab81fa1a1681a438565656a23001f | [
"MIT"
] | null | null | null | app/plugins/i18n.js | fightforthefuture/earth-day-live | 2a7e6acd210ab81fa1a1681a438565656a23001f | [
"MIT"
] | 61 | 2020-03-24T20:35:15.000Z | 2022-01-22T11:10:52.000Z | app/plugins/i18n.js | fightforthefuture/earth-day-live | 2a7e6acd210ab81fa1a1681a438565656a23001f | [
"MIT"
] | null | null | null | import Vue from "vue";
import VueI18n from "vue-i18n";
Vue.use(VueI18n)
export default ({ app }) => {
app.i18n = new VueI18n({
locale: "en", // Default locale
fallbackLocale: "en", // The locale to use if the current locale can't be found
messages: {
en: require("~/locales/en.json")
}
});
};
| 21.533333 | 84 | 0.606811 |
6ffa75a0ce6f08d3feded11f9f03219f5059b009 | 4,901 | js | JavaScript | src/components/Videos.js | zyra-zia/badger-community | effb2961d101b14604f0be485868110f148a44af | [
"MIT"
] | null | null | null | src/components/Videos.js | zyra-zia/badger-community | effb2961d101b14604f0be485868110f148a44af | [
"MIT"
] | null | null | null | src/components/Videos.js | zyra-zia/badger-community | effb2961d101b14604f0be485868110f148a44af | [
"MIT"
] | null | null | null | import React from "react";
import VideoCard from "./VideoCard";
export default function Videos(props) {
const external = <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fillRule="evenodd" d="M10.604 1h4.146a.25.25 0 01.25.25v4.146a.25.25 0 01-.427.177L13.03 4.03 9.28 7.78a.75.75 0 01-1.06-1.06l3.75-3.75-1.543-1.543A.25.25 0 0110.604 1zM3.75 2A1.75 1.75 0 002 3.75v8.5c0 .966.784 1.75 1.75 1.75h8.5A1.75 1.75 0 0014 12.25v-3.5a.75.75 0 00-1.5 0v3.5a.25.25 0 01-.25.25h-8.5a.25.25 0 01-.25-.25v-8.5a.25.25 0 01.25-.25h3.5a.75.75 0 000-1.5h-3.5z"></path></svg>;
const officialVideosList = [
{
src: "https://i.ytimg.com/vi/CQWGnbPsfTM/hqdefault.jpg?sqp=-oaymwEcCNACELwBSFXyq4qpAw4IARUAAIhCGAFwAcABBg==&rs=AOn4CLDCuBc4XyGk30uyXPMexmKYcOuqkA",
title: "How to Use the Binance Smart Chain Sett Vaults",
desc: "Learn Badger:https://badger.finance/ https://badgerdao.medium.com/ Use Badger: https://app.badger.finance/ ...",
url: "https://www.youtube.com/watch?v=CQWGnbPsfTM"
},
{
src: "https://i.ytimg.com/vi/dDLOv_5XWy4/hqdefault.jpg?sqp=-oaymwEcCNACELwBSFXyq4qpAw4IARUAAIhCGAFwAcABBg==&rs=AOn4CLAUPk7DIcQM2M3E5PtEAxw7pOr86w",
title: "Office Hours - Rewards & Emissions - 03.18.21",
desc: "Learn Badger:https://badger.finance/ https://badgerdao.medium.com/ Use Badger: https://app.badger.finance/ ...",
url: "https://www.youtube.com/watch?v=dDLOv_5XWy4"
},
{
src: "https://i.ytimg.com/vi/Xldy3BqWonE/hqdefault.jpg?sqp=-oaymwEcCNACELwBSFXyq4qpAw4IARUAAIhCGAFwAcABBg==&rs=AOn4CLARD1bFNVBEpFwnGYHZt_GlCDrzlQ",
title: "Sett Session: Episode 2",
desc: "Badger DAO hosted their second Sett Session Friday January 29th, 2021. Learn Badger:https://badger.finance/ ...",
url: "https://www.youtube.com/watch?v=Xldy3BqWonE"
}
];
const officialVideos = officialVideosList.map((v, index)=>{
return <VideoCard key={index} src={v.src} title={v.title} desc={v.desc} url={v.url} />
});
const communityVideosList = [
{
src: "https://i.ytimg.com/vi/gh79Knm7zzQ/hq720.jpg?sqp=-oaymwEcCNAFEJQDSFXyq4qpAw4IARUAAIhCGAFwAcABBg==&rs=AOn4CLDLHdhechkKHpHkUUGUtPa_co8_Xg",
title: "AMA with Chris Spadafora, Founder of BadgerDAO",
desc: "Chris Spadafora is the Founder of BadgerDAO, a decentralized protocol that promotes the use of tokenized BTC in DeFi. ...",
url: "https://www.youtube.com/watch?v=gh79Knm7zzQ"
},
{
src: "https://i.ytimg.com/vi/RaQm49LbP5c/hq720.jpg?sqp=-oaymwEcCNAFEJQDSFXyq4qpAw4IARUAAIhCGAFwAcABBg==&rs=AOn4CLAF4edlG5vZglh_r-Qjx-w1NVhkyw",
title: "The FTX Podcast #52 - Chris Spadafora Founder of Badger DAO",
desc: "Badger is a decentralized autonomous organization that focuses on building the products and infrastructure necessary ...",
url: "https://www.youtube.com/watch?v=RaQm49LbP5c"
},
{
src: "https://i.ytimg.com/vi/8wXpolSUwRk/hq720.jpg?sqp=-oaymwEcCNAFEJQDSFXyq4qpAw4IARUAAIhCGAFwAcABBg==&rs=AOn4CLDkjjJy8_508KENWe5TWLEYBwfC4w",
title: "Earn On Bitcoin with Badger DAO",
desc: "In this tutorial, I discuss how to convert your BTC to wBTC and start earning yield using Badger DAO. Process utilizes WBTC ...",
url: "https://www.youtube.com/watch?v=8wXpolSUwRk"
}
];
const communityVideos = communityVideosList.map((v, index)=>{
return <VideoCard key={index} src={v.src} title={v.title} desc={v.desc} url={v.url} />
});
return (
<React.Fragment>
<div className="row my-4 border-bottom">
<h5 className="ml-5 col-12">Official Videos</h5>
<div className="col-12 mt-3">
<div className="row px-4">
{officialVideos}
</div>
</div>
<div className="col-12 text-right">
<a href="https://www.youtube.com/channel/UC5kss_AvIpj1g8H8-SZjQJA" target="_blank" className="btn btn-warning mr-5 mb-5">View More {external}</a>
</div>
</div>
<div className="row my-4 border-bottom">
<h5 className="ml-5 col-12">Community Videos</h5>
<div className="col-12 mt-3">
<div className="row px-4">
{communityVideos}
</div>
</div>
<div className="col-12 text-right">
<a href="https://www.youtube.com/results?search_query=badger+dao" target="_blank" className="btn btn-warning mr-5 mb-5">View More {external}</a>
</div>
</div>
</React.Fragment>
);
} | 55.067416 | 501 | 0.612936 |
6ffbb94984c996ddfc5ccd219c66a56cd0efce61 | 2,974 | js | JavaScript | test/common/models/SetResponse.js | linagora/jmap-draft-client | 6036b1308b6c8affe86f0784b2e1397eede05511 | [
"MIT"
] | null | null | null | test/common/models/SetResponse.js | linagora/jmap-draft-client | 6036b1308b6c8affe86f0784b2e1397eede05511 | [
"MIT"
] | 4 | 2020-04-30T15:23:00.000Z | 2020-05-18T10:31:20.000Z | test/common/models/SetResponse.js | linagora/jmap-draft-client | 6036b1308b6c8affe86f0784b2e1397eede05511 | [
"MIT"
] | null | null | null | 'use strict';
var expect = require('chai').expect,
jmapDraft = require('../../../dist/jmap-draft-client');
describe('The SetResponse class', function() {
describe('The constructor', function() {
it('should use default values for all fields if not defined', function() {
var response = new jmapDraft.SetResponse({});
expect(response.accountId).to.equal(null);
expect(response.oldState).to.equal(null);
expect(response.newState).to.equal('');
expect(response.created).to.deep.equal({});
expect(response.updated).to.deep.equal([]);
expect(response.destroyed).to.deep.equal([]);
expect(response.MDNSent).to.deep.equal([]);
expect(response.notCreated).to.deep.equal({});
expect(response.notUpdated).to.deep.equal({});
expect(response.notDestroyed).to.deep.equal({});
expect(response.MDNNotSent).to.deep.equal({});
});
it('should allow defining optional properties through the opts object', function() {
expect(new jmapDraft.SetResponse({}, { accountId: 'id' }).accountId).to.equal('id');
});
});
describe('The fromJSONObject static method', function() {
it('should throw an Error if object is not defined', function() {
expect(function() {
jmapDraft.SetResponse.fromJSONObject({});
}).to.throw(Error);
});
it('should return an instance of SetResponse', function() {
expect(jmapDraft.SetResponse.fromJSONObject({}, {})).to.be.an.instanceof(jmapDraft.SetResponse);
});
it('should use default values for for all fields if not defined', function() {
var response = jmapDraft.SetResponse.fromJSONObject({}, {});
expect(response.accountId).to.equal(null);
expect(response.oldState).to.equal(null);
expect(response.newState).to.equal('');
expect(response.created).to.deep.equal({});
expect(response.updated).to.deep.equal([]);
expect(response.destroyed).to.deep.equal([]);
expect(response.MDNSent).to.deep.equal([]);
expect(response.notCreated).to.deep.equal({});
expect(response.notUpdated).to.deep.equal({});
expect(response.notDestroyed).to.deep.equal({});
expect(response.MDNNotSent).to.deep.equal({});
});
it('should copy values for all fields if defined', function() {
var response = jmapDraft.SetResponse.fromJSONObject({}, {
accountId: 'id',
created: {
ABCD: {
id: 'mailboxId'
}
},
MDNNotSent: {
EFGH: {
type: 'invalidArguments',
description: 'lorem ipsum'
}
}
});
expect(response.accountId).to.equal('id');
expect(response.created).to.deep.equal({
ABCD: {
id: 'mailboxId'
}
});
expect(response.MDNNotSent).to.shallowDeepEqual({
EFGH: {
type: 'invalidArguments',
description: 'lorem ipsum'
}
});
});
});
});
| 31.978495 | 102 | 0.608608 |
6ffc139dfadef8b2ad64de01448b2ec637ff7a7d | 25,247 | js | JavaScript | node_modules/element-plus/lib/el-message-box/index.js | Rizq-Solutions/etiqa-ncov-tracker | dcf8a7c7e587c74915f9ea96729f0b537cb87718 | [
"MIT"
] | null | null | null | node_modules/element-plus/lib/el-message-box/index.js | Rizq-Solutions/etiqa-ncov-tracker | dcf8a7c7e587c74915f9ea96729f0b537cb87718 | [
"MIT"
] | null | null | null | node_modules/element-plus/lib/el-message-box/index.js | Rizq-Solutions/etiqa-ncov-tracker | dcf8a7c7e587c74915f9ea96729f0b537cb87718 | [
"MIT"
] | null | null | null | 'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var vue = require('vue');
var ElButton = require('../el-button');
var ElInput = require('../el-input');
var locale = require('../locale');
var Dialog = require('../utils/aria-dialog');
var usePopup = require('../utils/popup/usePopup');
var dom = require('../utils/dom');
var isServer = require('../utils/isServer');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var ElButton__default = /*#__PURE__*/_interopDefaultLegacy(ElButton);
var ElInput__default = /*#__PURE__*/_interopDefaultLegacy(ElInput);
var Dialog__default = /*#__PURE__*/_interopDefaultLegacy(Dialog);
var usePopup__default = /*#__PURE__*/_interopDefaultLegacy(usePopup);
var isServer__default = /*#__PURE__*/_interopDefaultLegacy(isServer);
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
let dialog;
const TypeMap = {
success: 'success',
info: 'info',
warning: 'warning',
error: 'error',
};
var script = vue.defineComponent({
name: 'ElMessageBox',
components: {
ElButton: ElButton__default['default'],
ElInput: ElInput__default['default'],
},
props: {
openDelay: {
type: Number,
default: 0,
},
closeDelay: {
type: Number,
default: 0,
},
zIndex: Number,
modalFade: {
type: Boolean,
default: true,
},
modalClass: {
type: String,
default: '',
},
modalAppendToBody: {
type: Boolean,
default: false,
},
modal: {
type: Boolean,
default: true,
},
lockScroll: {
type: Boolean,
default: true,
},
showClose: {
type: Boolean,
default: true,
},
closeOnClickModal: {
type: Boolean,
default: true,
},
closeOnPressEscape: {
type: Boolean,
default: true,
},
closeOnHashChange: {
type: Boolean,
default: true,
},
center: {
default: false,
type: Boolean,
},
roundButton: {
default: false,
type: Boolean,
},
},
setup(props) {
let vm;
const popup = usePopup__default['default'](props, doClose);
const state = vue.reactive({
uid: 1,
title: undefined,
message: '',
type: '',
iconClass: '',
customClass: '',
showInput: false,
inputValue: null,
inputPlaceholder: '',
inputType: 'text',
inputPattern: null,
inputValidator: null,
inputErrorMessage: '',
showConfirmButton: true,
showCancelButton: false,
action: '',
confirmButtonText: '',
cancelButtonText: '',
confirmButtonLoading: false,
cancelButtonLoading: false,
confirmButtonClass: '',
confirmButtonDisabled: false,
cancelButtonClass: '',
editorErrorMessage: null,
callback: null,
dangerouslyUseHTMLString: false,
focusAfterClosed: null,
isOnComposition: false,
distinguishCancelAndClose: false,
type$: '',
visible: false,
validateError: false,
});
const icon = vue.computed(() => state.iconClass || (state.type && TypeMap[state.type] ? `el-icon-${TypeMap[state.type]}` : ''));
const hasMessage = vue.computed(() => !!state.message);
const confirmButtonClasses = vue.computed(() => `el-button--primary ${state.confirmButtonClass}`);
vue.watch(() => state.inputValue, (val) => __awaiter(this, void 0, void 0, function* () {
yield vue.nextTick();
if (state.type$ === 'prompt' && val !== null) {
validate();
}
}), { immediate: true });
vue.watch(() => state.visible, val => {
popup.state.visible = val;
if (val) {
state.uid++;
if (state.type$ === 'alert' || state.type$ === 'confirm') {
vue.nextTick().then(() => { vm.refs.confirm.$el.focus(); });
}
state.focusAfterClosed = document.activeElement;
dialog = new Dialog__default['default'](vm.vnode.el, state.focusAfterClosed, getFirstFocus());
}
if (state.type$ !== 'prompt')
return;
if (val) {
vue.nextTick().then(() => {
if (vm.refs.input && vm.refs.input.$el) {
getInputElement().focus();
}
});
}
else {
state.editorErrorMessage = '';
state.validateError = false;
}
});
vue.onBeforeMount(() => {
vm = vue.getCurrentInstance();
vm.setupInstall = {
state,
doClose,
};
});
vue.onMounted(() => __awaiter(this, void 0, void 0, function* () {
yield vue.nextTick();
if (props.closeOnHashChange) {
dom.on(window, 'hashchange', popup.close);
}
}));
vue.onBeforeUnmount(() => {
if (props.closeOnHashChange) {
dom.off(window, 'hashchange', popup.close);
}
setTimeout(() => {
dialog.closeDialog();
});
});
function getSafeClose() {
const currentId = state.uid;
return () => __awaiter(this, void 0, void 0, function* () {
yield vue.nextTick();
if (currentId === state.uid)
doClose();
});
}
function doClose() {
if (!state.visible)
return;
state.visible = false;
popup.updateClosingFlag(true);
dialog.closeDialog();
if (props.lockScroll) {
setTimeout(popup.restoreBodyStyle, 200);
}
popup.state.opened = false;
popup.doAfterClose();
setTimeout(() => {
if (state.action)
state.callback(state.action, state);
});
}
const getFirstFocus = () => {
const btn = vm.vnode.el.querySelector('.el-message-box__btns .el-button');
const title = vm.vnode.el.querySelector('.el-message-box__btns .el-message-box__title');
return btn || title;
};
const handleWrapperClick = () => {
if (props.closeOnClickModal) {
handleAction(state.distinguishCancelAndClose ? 'close' : 'cancel');
}
};
const handleInputEnter = () => {
if (state.inputType !== 'textarea') {
return handleAction('confirm');
}
};
const handleAction = action => {
if (state.type$ === 'prompt' && action === 'confirm' && !validate()) {
return;
}
state.action = action;
if (typeof vm.setupInstall.state.beforeClose === 'function') {
vm.setupInstall.state.close = getSafeClose();
vm.setupInstall.state.beforeClose(action, state, popup.close);
}
else {
doClose();
}
};
const validate = () => {
if (state.type$ === 'prompt') {
const inputPattern = state.inputPattern;
if (inputPattern && !inputPattern.test(state.inputValue || '')) {
state.editorErrorMessage = state.inputErrorMessage || locale.t('el.messagebox.error');
state.validateError = true;
return false;
}
const inputValidator = state.inputValidator;
if (typeof inputValidator === 'function') {
const validateResult = inputValidator(state.inputValue);
if (validateResult === false) {
state.editorErrorMessage = state.inputErrorMessage || locale.t('el.messagebox.error');
state.validateError = true;
return false;
}
if (typeof validateResult === 'string') {
state.editorErrorMessage = validateResult;
state.validateError = true;
return false;
}
}
}
state.editorErrorMessage = '';
state.validateError = false;
return true;
};
const getInputElement = () => {
const inputRefs = vm.refs.input.$refs;
return inputRefs.input || inputRefs.textarea;
};
const handleClose = () => {
handleAction('close');
};
return Object.assign(Object.assign({}, vue.toRefs(state)), { hasMessage,
icon,
confirmButtonClasses,
handleWrapperClick,
handleInputEnter,
handleAction,
handleClose,
t: locale.t,
doClose });
},
});
const _hoisted_1 = {
key: 0,
class: "el-message-box__header"
};
const _hoisted_2 = { class: "el-message-box__title" };
const _hoisted_3 = /*#__PURE__*/vue.createVNode("i", { class: "el-message-box__close el-icon-close" }, null, -1 /* HOISTED */);
const _hoisted_4 = { class: "el-message-box__content" };
const _hoisted_5 = { class: "el-message-box__container" };
const _hoisted_6 = {
key: 1,
class: "el-message-box__message"
};
const _hoisted_7 = { key: 0 };
const _hoisted_8 = { class: "el-message-box__input" };
const _hoisted_9 = { class: "el-message-box__btns" };
function render(_ctx, _cache, $props, $setup, $data, $options) {
const _component_el_input = vue.resolveComponent("el-input");
const _component_el_button = vue.resolveComponent("el-button");
return (vue.openBlock(), vue.createBlock(vue.Transition, { name: "msgbox-fade" }, {
default: vue.withCtx(() => [
vue.withDirectives(vue.createVNode("div", {
ref: "root",
"aria-label": _ctx.title || 'dialog',
class: "el-message-box__wrapper",
tabindex: "-1",
role: "dialog",
"aria-modal": "true",
onClick: _cache[8] || (_cache[8] = vue.withModifiers((...args) => (_ctx.handleWrapperClick && _ctx.handleWrapperClick(...args)), ["self"]))
}, [
vue.createVNode("div", {
class: ["el-message-box", [_ctx.customClass, _ctx.center && 'el-message-box--center']]
}, [
(_ctx.title !== null && _ctx.title !== undefined)
? (vue.openBlock(), vue.createBlock("div", _hoisted_1, [
vue.createVNode("div", _hoisted_2, [
(_ctx.icon && _ctx.center)
? (vue.openBlock(), vue.createBlock("div", {
key: 0,
class: ['el-message-box__status', _ctx.icon]
}, null, 2 /* CLASS */))
: vue.createCommentVNode("v-if", true),
vue.createVNode("span", null, vue.toDisplayString(_ctx.title), 1 /* TEXT */)
]),
(_ctx.showClose)
? (vue.openBlock(), vue.createBlock("button", {
key: 0,
type: "button",
class: "el-message-box__headerbtn",
"aria-label": "Close",
onClick: _cache[1] || (_cache[1] = $event => (_ctx.handleAction(_ctx.distinguishCancelAndClose ? 'close' : 'cancel'))),
onKeydown: _cache[2] || (_cache[2] = vue.withKeys($event => (_ctx.handleAction(_ctx.distinguishCancelAndClose ? 'close' : 'cancel')), ["enter"]))
}, [
_hoisted_3
], 32 /* HYDRATE_EVENTS */))
: vue.createCommentVNode("v-if", true)
]))
: vue.createCommentVNode("v-if", true),
vue.createVNode("div", _hoisted_4, [
vue.createVNode("div", _hoisted_5, [
(_ctx.icon && !_ctx.center && _ctx.hasMessage)
? (vue.openBlock(), vue.createBlock("div", {
key: 0,
class: ['el-message-box__status', _ctx.icon]
}, null, 2 /* CLASS */))
: vue.createCommentVNode("v-if", true),
(_ctx.hasMessage)
? (vue.openBlock(), vue.createBlock("div", _hoisted_6, [
vue.renderSlot(_ctx.$slots, "default", {}, () => [
(!_ctx.dangerouslyUseHTMLString)
? (vue.openBlock(), vue.createBlock("p", _hoisted_7, vue.toDisplayString(_ctx.message), 1 /* TEXT */))
: (vue.openBlock(), vue.createBlock("p", {
key: 1,
innerHTML: _ctx.message
}, null, 8 /* PROPS */, ["innerHTML"]))
])
]))
: vue.createCommentVNode("v-if", true)
]),
vue.withDirectives(vue.createVNode("div", _hoisted_8, [
vue.createVNode(_component_el_input, {
ref: "input",
modelValue: _ctx.inputValue,
"onUpdate:modelValue": _cache[3] || (_cache[3] = $event => (_ctx.inputValue = $event)),
type: _ctx.inputType,
placeholder: _ctx.inputPlaceholder,
class: { invalid: _ctx.validateError },
onKeydown: vue.withKeys(_ctx.handleInputEnter, ["enter"])
}, null, 8 /* PROPS */, ["modelValue", "type", "placeholder", "class", "onKeydown"]),
vue.createVNode("div", {
class: "el-message-box__errormsg",
style: { visibility: !!_ctx.editorErrorMessage ? 'visible' : 'hidden' }
}, vue.toDisplayString(_ctx.editorErrorMessage), 5 /* TEXT, STYLE */)
], 512 /* NEED_PATCH */), [
[vue.vShow, _ctx.showInput]
])
]),
vue.createVNode("div", _hoisted_9, [
(_ctx.showCancelButton)
? (vue.openBlock(), vue.createBlock(_component_el_button, {
key: 0,
loading: _ctx.cancelButtonLoading,
class: [ _ctx.cancelButtonClass ],
round: _ctx.roundButton,
size: "small",
onClick: _cache[4] || (_cache[4] = $event => (_ctx.handleAction('cancel'))),
onKeydown: _cache[5] || (_cache[5] = vue.withKeys($event => (_ctx.handleAction('cancel')), ["enter"]))
}, {
default: vue.withCtx(() => [
vue.createTextVNode(vue.toDisplayString(_ctx.cancelButtonText || _ctx.t('el.messagebox.cancel')), 1 /* TEXT */)
]),
_: 1 /* STABLE */
}, 8 /* PROPS */, ["loading", "class", "round"]))
: vue.createCommentVNode("v-if", true),
vue.withDirectives(vue.createVNode(_component_el_button, {
ref: "confirm",
loading: _ctx.confirmButtonLoading,
class: [ _ctx.confirmButtonClasses ],
round: _ctx.roundButton,
disabled: _ctx.confirmButtonDisabled,
size: "small",
onClick: _cache[6] || (_cache[6] = $event => (_ctx.handleAction('confirm'))),
onKeydown: _cache[7] || (_cache[7] = vue.withKeys($event => (_ctx.handleAction('confirm')), ["enter"]))
}, {
default: vue.withCtx(() => [
vue.createTextVNode(vue.toDisplayString(_ctx.confirmButtonText || _ctx.t('el.messagebox.confirm')), 1 /* TEXT */)
]),
_: 1 /* STABLE */
}, 8 /* PROPS */, ["loading", "class", "round", "disabled"]), [
[vue.vShow, _ctx.showConfirmButton]
])
])
], 2 /* CLASS */)
], 8 /* PROPS */, ["aria-label"]), [
[vue.vShow, _ctx.visible]
])
]),
_: 1 /* STABLE */
}))
}
script.render = render;
script.__file = "packages/message-box/src/index.vue";
/**
* Make a map and return a function for checking if a key
* is in that map.
* IMPORTANT: all calls of this function must be prefixed with
* \/\*#\_\_PURE\_\_\*\/
* So that rollup can tree-shake them if necessary.
*/
const EMPTY_OBJ = (process.env.NODE_ENV !== 'production')
? Object.freeze({})
: {};
const EMPTY_ARR = (process.env.NODE_ENV !== 'production') ? Object.freeze([]) : [];
let currentMsg, instance;
const PROP_KEYS = [
'lockScroll',
'showClose',
'closeOnClickModal',
'closeOnPressEscape',
'closeOnHashChange',
'center',
'roundButton',
'closeDelay',
'zIndex',
'modal',
'modalFade',
'modalClass',
'modalAppendToBody',
'lockScroll',
];
const defaults = {
title: null,
message: '',
type: '',
iconClass: '',
showInput: false,
showClose: true,
modalFade: true,
lockScroll: true,
closeOnClickModal: true,
closeOnPressEscape: true,
closeOnHashChange: true,
inputValue: null,
inputPlaceholder: '',
inputType: 'text',
inputPattern: null,
inputValidator: null,
inputErrorMessage: '',
showConfirmButton: true,
showCancelButton: false,
confirmButtonPosition: 'right',
confirmButtonHighlight: false,
cancelButtonHighlight: false,
confirmButtonText: '',
cancelButtonText: '',
confirmButtonClass: '',
cancelButtonClass: '',
customClass: '',
beforeClose: null,
dangerouslyUseHTMLString: false,
center: false,
roundButton: false,
distinguishCancelAndClose: false,
};
let msgQueue = [];
const defaultCallback = (action, ctx) => {
if (currentMsg) {
const callback = currentMsg.callback;
if (typeof callback === 'function') {
if (ctx.showInput) {
callback(ctx.inputValue, action);
}
else {
callback(action);
}
}
if (currentMsg.resolve) {
if (action === 'confirm') {
if (ctx.showInput) {
currentMsg.resolve({ value: ctx.inputValue, action });
}
else {
currentMsg.resolve(action);
}
}
else if (currentMsg.reject && (action === 'cancel' || action === 'close')) {
currentMsg.reject(action);
}
}
}
};
const initInstance = () => {
const container = document.createElement('div');
const vnode = vue.createVNode(script);
vue.render(vnode, container);
instance = vnode.component;
};
const showNextMsg = () => __awaiter(void 0, void 0, void 0, function* () {
if (!instance) {
initInstance();
}
if (instance && instance.setupInstall.state.visible) {
return;
}
if (msgQueue.length > 0) {
const props = {};
const state = {};
currentMsg = msgQueue.shift();
const options = currentMsg.options;
Object.keys(options).forEach(key => {
if (PROP_KEYS.includes(key)) {
props[key] = options[key];
}
else {
state[key] = options[key];
}
});
const vmProps = instance.props;
for (const prop in props) {
if (props.hasOwnProperty(prop)) {
vmProps[prop] = props[prop];
}
}
const vmState = instance.setupInstall.state;
vmState.action = '';
if (options.callback === undefined) {
options.callback = defaultCallback;
}
for (const prop in state) {
if (state.hasOwnProperty(prop)) {
vmState[prop] = state[prop];
}
}
if (vue.isVNode(options.message)) {
instance.slots.default = () => [options.message];
}
const oldCb = options.callback;
vmState.callback = (action, inst) => {
oldCb(action, inst);
showNextMsg();
};
document.body.appendChild(instance.vnode.el);
vmState.visible = true;
}
});
const MessageBox = function (options, callback) {
if (isServer__default['default'])
return;
if (typeof options === 'string' || vue.isVNode(options)) {
options = {
message: options,
};
if (typeof callback === 'string') {
options.title = callback;
}
}
else if (options.callback && !callback) {
callback = options.callback;
}
if (typeof Promise !== 'undefined') {
return new Promise((resolve, reject) => {
msgQueue.push({
options: Object.assign({}, defaults, options),
callback: callback,
resolve: resolve,
reject: reject,
});
showNextMsg();
});
}
else {
msgQueue.push({
options: Object.assign({}, defaults, options),
callback: callback,
});
showNextMsg();
}
};
MessageBox.alert = (message, title, options) => {
if (typeof title === 'object') {
options = title;
title = '';
}
else if (title === undefined) {
title = '';
}
return MessageBox(Object.assign({
title: title,
message: message,
type$: 'alert',
closeOnPressEscape: false,
closeOnClickModal: false,
}, options));
};
MessageBox.confirm = (message, title, options) => {
if (typeof title === 'object') {
options = title;
title = '';
}
else if (title === undefined) {
title = '';
}
return MessageBox(Object.assign({
title: title,
message: message,
type$: 'confirm',
showCancelButton: true,
}, options));
};
MessageBox.prompt = (message, title, options) => {
if (typeof title === 'object') {
options = title;
title = '';
}
else if (title === undefined) {
title = '';
}
return MessageBox(Object.assign({
title: title,
message: message,
showCancelButton: true,
showInput: true,
type$: 'prompt',
}, options));
};
MessageBox.close = () => {
instance.setupInstall.doClose();
instance.setupInstall.state.visible = false;
msgQueue = [];
currentMsg = null;
};
MessageBox.install = (app) => {
app.config.globalProperties.$msgbox = MessageBox;
app.config.globalProperties.$messageBox = MessageBox;
app.config.globalProperties.$alert = MessageBox.alert;
app.config.globalProperties.$confirm = MessageBox.confirm;
app.config.globalProperties.$prompt = MessageBox.prompt;
};
exports.default = MessageBox;
| 36.642961 | 167 | 0.50406 |