text
stringlengths
3
1.05M
import firebase from '@firebase/app';(function() {/* Copyright The Closure Library Authors. SPDX-License-Identifier: Apache-2.0 */ var k,aa="function"==typeof Object.defineProperties?Object.defineProperty:function(a,b,c){a!=Array.prototype&&a!=Object.prototype&&(a[b]=c.value)};function ba(a){a=["object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof global&&global,a];for(var b=0;b<a.length;++b){var c=a[b];if(c&&c.Math==Math)return c}return globalThis}var ca=ba(this); function da(a,b){if(b){var c=ca;a=a.split(".");for(var d=0;d<a.length-1;d++){var e=a[d];e in c||(c[e]={});c=c[e]}a=a[a.length-1];d=c[a];b=b(d);b!=d&&null!=b&&aa(c,a,{configurable:!0,writable:!0,value:b})}}function ea(a){var b=0;return function(){return b<a.length?{done:!1,value:a[b++]}:{done:!0}}}function fa(a){var b="undefined"!=typeof Symbol&&Symbol.iterator&&a[Symbol.iterator];return b?b.call(a):{next:ea(a)}} da("Promise",function(a){function b(g){this.b=0;this.c=void 0;this.a=[];var h=this.f();try{g(h.resolve,h.reject)}catch(m){h.reject(m)}}function c(){this.a=null}function d(g){return g instanceof b?g:new b(function(h){h(g)})}if(a)return a;c.prototype.b=function(g){if(null==this.a){this.a=[];var h=this;this.c(function(){h.g()})}this.a.push(g)};var e=ca.setTimeout;c.prototype.c=function(g){e(g,0)};c.prototype.g=function(){for(;this.a&&this.a.length;){var g=this.a;this.a=[];for(var h=0;h<g.length;++h){var m= g[h];g[h]=null;try{m()}catch(p){this.f(p)}}}this.a=null};c.prototype.f=function(g){this.c(function(){throw g;})};b.prototype.f=function(){function g(p){return function(v){m||(m=!0,p.call(h,v))}}var h=this,m=!1;return{resolve:g(this.m),reject:g(this.g)}};b.prototype.m=function(g){if(g===this)this.g(new TypeError("A Promise cannot resolve to itself"));else if(g instanceof b)this.s(g);else{a:switch(typeof g){case "object":var h=null!=g;break a;case "function":h=!0;break a;default:h=!1}h?this.u(g):this.h(g)}}; b.prototype.u=function(g){var h=void 0;try{h=g.then}catch(m){this.g(m);return}"function"==typeof h?this.w(h,g):this.h(g)};b.prototype.g=function(g){this.i(2,g)};b.prototype.h=function(g){this.i(1,g)};b.prototype.i=function(g,h){if(0!=this.b)throw Error("Cannot settle("+g+", "+h+"): Promise already settled in state"+this.b);this.b=g;this.c=h;this.l()};b.prototype.l=function(){if(null!=this.a){for(var g=0;g<this.a.length;++g)f.b(this.a[g]);this.a=null}};var f=new c;b.prototype.s=function(g){var h=this.f(); g.Oa(h.resolve,h.reject)};b.prototype.w=function(g,h){var m=this.f();try{g.call(h,m.resolve,m.reject)}catch(p){m.reject(p)}};b.prototype.then=function(g,h){function m(A,Q){return"function"==typeof A?function(xa){try{p(A(xa))}catch(ud){v(ud)}}:Q}var p,v,C=new b(function(A,Q){p=A;v=Q});this.Oa(m(g,p),m(h,v));return C};b.prototype.catch=function(g){return this.then(void 0,g)};b.prototype.Oa=function(g,h){function m(){switch(p.b){case 1:g(p.c);break;case 2:h(p.c);break;default:throw Error("Unexpected state: "+ p.b);}}var p=this;null==this.a?f.b(m):this.a.push(m)};b.resolve=d;b.reject=function(g){return new b(function(h,m){m(g)})};b.race=function(g){return new b(function(h,m){for(var p=fa(g),v=p.next();!v.done;v=p.next())d(v.value).Oa(h,m)})};b.all=function(g){var h=fa(g),m=h.next();return m.done?d([]):new b(function(p,v){function C(xa){return function(ud){A[xa]=ud;Q--;0==Q&&p(A)}}var A=[],Q=0;do A.push(void 0),Q++,d(m.value).Oa(C(A.length-1),v),m=h.next();while(!m.done)})};return b}); var ha=ha||{},l=this||self,ia=/^[\w+/_-]+[=]{0,2}$/,ja=null;function ka(){} function la(a){var b=typeof a;if("object"==b)if(a){if(a instanceof Array)return"array";if(a instanceof Object)return b;var c=Object.prototype.toString.call(a);if("[object Window]"==c)return"object";if("[object Array]"==c||"number"==typeof a.length&&"undefined"!=typeof a.splice&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("splice"))return"array";if("[object Function]"==c||"undefined"!=typeof a.call&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("call"))return"function"}else return"null"; else if("function"==b&&"undefined"==typeof a.call)return"object";return b}function ma(a){var b=la(a);return"array"==b||"object"==b&&"number"==typeof a.length}function n(a){return"function"==la(a)}function q(a){var b=typeof a;return"object"==b&&null!=a||"function"==b}function na(a){return Object.prototype.hasOwnProperty.call(a,oa)&&a[oa]||(a[oa]=++pa)}var oa="closure_uid_"+(1E9*Math.random()>>>0),pa=0;function qa(a,b,c){return a.call.apply(a.bind,arguments)} function ra(a,b,c){if(!a)throw Error();if(2<arguments.length){var d=Array.prototype.slice.call(arguments,2);return function(){var e=Array.prototype.slice.call(arguments);Array.prototype.unshift.apply(e,d);return a.apply(b,e)}}return function(){return a.apply(b,arguments)}}function r(a,b,c){Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?r=qa:r=ra;return r.apply(null,arguments)} function sa(a,b){var c=Array.prototype.slice.call(arguments,1);return function(){var d=c.slice();d.push.apply(d,arguments);return a.apply(this,d)}}var ta=Date.now||function(){return+new Date};function t(a,b){function c(){}c.prototype=b.prototype;a.Za=b.prototype;a.prototype=new c;a.prototype.constructor=a};/* Copyright 2017 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ function u(a,b,c){this.code=ua+a;this.message=b||va[a]||"";this.a=c||null}t(u,Error);u.prototype.v=function(){var a={code:this.code,message:this.message};this.a&&(a.serverResponse=this.a);return a};u.prototype.toJSON=function(){return this.v()};function wa(a){var b=a&&a.code;return b?new u(b.substring(ua.length),a.message,a.serverResponse):null} var ua="auth/",va={"admin-restricted-operation":"This operation is restricted to administrators only.","argument-error":"","app-not-authorized":"This app, identified by the domain where it's hosted, is not authorized to use Firebase Authentication with the provided API key. Review your key configuration in the Google API console.","app-not-installed":"The requested mobile application corresponding to the identifier (Android package name or iOS bundle ID) provided is not installed on this device.", "captcha-check-failed":"The reCAPTCHA response token provided is either invalid, expired, already used or the domain associated with it does not match the list of whitelisted domains.","code-expired":"The SMS code has expired. Please re-send the verification code to try again.","cordova-not-ready":"Cordova framework is not ready.","cors-unsupported":"This browser is not supported.","credential-already-in-use":"This credential is already associated with a different user account.","custom-token-mismatch":"The custom token corresponds to a different audience.", "requires-recent-login":"This operation is sensitive and requires recent authentication. Log in again before retrying this request.","dynamic-link-not-activated":"Please activate Dynamic Links in the Firebase Console and agree to the terms and conditions.","email-change-needs-verification":"Multi-factor users must always have a verified email.","email-already-in-use":"The email address is already in use by another account.","expired-action-code":"The action code has expired. ","cancelled-popup-request":"This operation has been cancelled due to another conflicting popup being opened.", "internal-error":"An internal error has occurred.","invalid-app-credential":"The phone verification request contains an invalid application verifier. The reCAPTCHA token response is either invalid or expired.","invalid-app-id":"The mobile app identifier is not registed for the current project.","invalid-user-token":"This user's credential isn't valid for this project. This can happen if the user's token has been tampered with, or if the user isn't for the project associated with this API key.","invalid-auth-event":"An internal error has occurred.", "invalid-verification-code":"The SMS verification code used to create the phone auth credential is invalid. Please resend the verification code sms and be sure use the verification code provided by the user.","invalid-continue-uri":"The continue URL provided in the request is invalid.","invalid-cordova-configuration":"The following Cordova plugins must be installed to enable OAuth sign-in: cordova-plugin-buildinfo, cordova-universal-links-plugin, cordova-plugin-browsertab, cordova-plugin-inappbrowser and cordova-plugin-customurlscheme.", "invalid-custom-token":"The custom token format is incorrect. Please check the documentation.","invalid-dynamic-link-domain":"The provided dynamic link domain is not configured or authorized for the current project.","invalid-email":"The email address is badly formatted.","invalid-api-key":"Your API key is invalid, please check you have copied it correctly.","invalid-cert-hash":"The SHA-1 certificate hash provided is invalid.","invalid-credential":"The supplied auth credential is malformed or has expired.", "invalid-message-payload":"The email template corresponding to this action contains invalid characters in its message. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-multi-factor-session":"The request does not contain a valid proof of first factor successful sign-in.","invalid-oauth-provider":"EmailAuthProvider is not supported for this operation. This operation only supports OAuth providers.","invalid-oauth-client-id":"The OAuth client ID provided is either invalid or does not match the specified API key.", "unauthorized-domain":"This domain is not authorized for OAuth operations for your Firebase project. Edit the list of authorized domains from the Firebase console.","invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","wrong-password":"The password is invalid or the user does not have a password.","invalid-persistence-type":"The specified persistence type is invalid. It can only be local, session or none.","invalid-phone-number":"The format of the phone number provided is incorrect. Please enter the phone number in a format that can be parsed into E.164 format. E.164 phone numbers are written in the format [+][country code][subscriber number including area code].", "invalid-provider-id":"The specified provider ID is invalid.","invalid-recipient-email":"The email corresponding to this action failed to send as the provided recipient email address is invalid.","invalid-sender":"The email template corresponding to this action contains an invalid sender email or name. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-verification-id":"The verification ID used to create the phone auth credential is invalid.","invalid-tenant-id":"The Auth instance's tenant ID is invalid.", "multi-factor-info-not-found":"The user does not have a second factor matching the identifier provided.","multi-factor-auth-required":"Proof of ownership of a second factor is required to complete sign-in.","missing-android-pkg-name":"An Android Package Name must be provided if the Android App is required to be installed.","auth-domain-config-required":"Be sure to include authDomain when calling firebase.initializeApp(), by following the instructions in the Firebase console.","missing-app-credential":"The phone verification request is missing an application verifier assertion. A reCAPTCHA response token needs to be provided.", "missing-verification-code":"The phone auth credential was created with an empty SMS verification code.","missing-continue-uri":"A continue URL must be provided in the request.","missing-iframe-start":"An internal error has occurred.","missing-ios-bundle-id":"An iOS Bundle ID must be provided if an App Store ID is provided.","missing-multi-factor-info":"No second factor identifier is provided.","missing-multi-factor-session":"The request is missing proof of first factor successful sign-in.","missing-or-invalid-nonce":"The request does not contain a valid nonce. This can occur if the SHA-256 hash of the provided raw nonce does not match the hashed nonce in the ID token payload.", "missing-phone-number":"To send verification codes, provide a phone number for the recipient.","missing-verification-id":"The phone auth credential was created with an empty verification ID.","app-deleted":"This instance of FirebaseApp has been deleted.","account-exists-with-different-credential":"An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address.","network-request-failed":"A network error (such as timeout, interrupted connection or unreachable host) has occurred.", "no-auth-event":"An internal error has occurred.","no-such-provider":"User was not linked to an account with the given provider.","null-user":"A null user object was provided as the argument for an operation which requires a non-null user object.","operation-not-allowed":"The given sign-in provider is disabled for this Firebase project. Enable it in the Firebase console, under the sign-in method tab of the Auth section.","operation-not-supported-in-this-environment":'This operation is not supported in the environment this application is running on. "location.protocol" must be http, https or chrome-extension and web storage must be enabled.', "popup-blocked":"Unable to establish a connection with the popup. It may have been blocked by the browser.","popup-closed-by-user":"The popup has been closed by the user before finalizing the operation.","provider-already-linked":"User can only be linked to one identity for the given provider.","quota-exceeded":"The project's quota for this operation has been exceeded.","redirect-cancelled-by-user":"The redirect operation has been cancelled by the user before finalizing.","redirect-operation-pending":"A redirect sign-in operation is already pending.", "rejected-credential":"The request contains malformed or mismatching credentials.","second-factor-already-in-use":"The second factor is already enrolled on this account.","maximum-second-factor-count-exceeded":"The maximum allowed number of second factors on a user has been exceeded.","tenant-id-mismatch":"The provided tenant ID does not match the Auth instance's tenant ID",timeout:"The operation has timed out.","user-token-expired":"The user's credential is no longer valid. The user must sign in again.", "too-many-requests":"We have blocked all requests from this device due to unusual activity. Try again later.","unauthorized-continue-uri":"The domain of the continue URL is not whitelisted. Please whitelist the domain in the Firebase console.","unsupported-first-factor":"Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.","unsupported-persistence-type":"The current environment does not support the specified persistence type.","unsupported-tenant-operation":"This operation is not supported in a multi-tenant context.", "unverified-email":"The operation requires a verified email.","user-cancelled":"The user did not grant your application the permissions it requested.","user-not-found":"There is no user record corresponding to this identifier. The user may have been deleted.","user-disabled":"The user account has been disabled by an administrator.","user-mismatch":"The supplied credentials do not correspond to the previously signed in user.","user-signed-out":"","weak-password":"The password must be 6 characters long or more.", "web-storage-unsupported":"This browser is not supported or 3rd party cookies and data may be disabled."};var ya={hd:{Ra:"https://staging-identitytoolkit.sandbox.googleapis.com/identitytoolkit/v3/relyingparty/",Xa:"https://staging-securetoken.sandbox.googleapis.com/v1/token",Ua:"https://staging-identitytoolkit.sandbox.googleapis.com/v2/",id:"b"},pd:{Ra:"https://www.googleapis.com/identitytoolkit/v3/relyingparty/",Xa:"https://securetoken.googleapis.com/v1/token",Ua:"https://identitytoolkit.googleapis.com/v2/",id:"p"},rd:{Ra:"https://staging-www.sandbox.googleapis.com/identitytoolkit/v3/relyingparty/", Xa:"https://staging-securetoken.sandbox.googleapis.com/v1/token",Ua:"https://staging-identitytoolkit.sandbox.googleapis.com/v2/",id:"s"},sd:{Ra:"https://www-googleapis-test.sandbox.google.com/identitytoolkit/v3/relyingparty/",Xa:"https://test-securetoken.sandbox.googleapis.com/v1/token",Ua:"https://test-identitytoolkit.sandbox.googleapis.com/v2/",id:"t"}}; function za(a){for(var b in ya)if(ya[b].id===a)return a=ya[b],{firebaseEndpoint:a.Ra,secureTokenEndpoint:a.Xa,identityPlatformEndpoint:a.Ua};return null}var Aa;Aa=za("__EID__")?"__EID__":void 0;function Ba(a){if(!a)return!1;try{return!!a.$goog_Thenable}catch(b){return!1}};function w(a){if(Error.captureStackTrace)Error.captureStackTrace(this,w);else{var b=Error().stack;b&&(this.stack=b)}a&&(this.message=String(a))}t(w,Error);w.prototype.name="CustomError";function Ca(a,b){a=a.split("%s");for(var c="",d=a.length-1,e=0;e<d;e++)c+=a[e]+(e<b.length?b[e]:"%s");w.call(this,c+a[d])}t(Ca,w);Ca.prototype.name="AssertionError";function Da(a,b){throw new Ca("Failure"+(a?": "+a:""),Array.prototype.slice.call(arguments,1));};function Ea(a,b){this.c=a;this.f=b;this.b=0;this.a=null}Ea.prototype.get=function(){if(0<this.b){this.b--;var a=this.a;this.a=a.next;a.next=null}else a=this.c();return a};function Fa(a,b){a.f(b);100>a.b&&(a.b++,b.next=a.a,a.a=b)};function Ga(){this.b=this.a=null}var Ia=new Ea(function(){return new Ha},function(a){a.reset()});Ga.prototype.add=function(a,b){var c=Ia.get();c.set(a,b);this.b?this.b.next=c:this.a=c;this.b=c};function Ja(){var a=Ka,b=null;a.a&&(b=a.a,a.a=a.a.next,a.a||(a.b=null),b.next=null);return b}function Ha(){this.next=this.b=this.a=null}Ha.prototype.set=function(a,b){this.a=a;this.b=b;this.next=null};Ha.prototype.reset=function(){this.next=this.b=this.a=null};var La=Array.prototype.indexOf?function(a,b){return Array.prototype.indexOf.call(a,b,void 0)}:function(a,b){if("string"===typeof a)return"string"!==typeof b||1!=b.length?-1:a.indexOf(b,0);for(var c=0;c<a.length;c++)if(c in a&&a[c]===b)return c;return-1},x=Array.prototype.forEach?function(a,b,c){Array.prototype.forEach.call(a,b,c)}:function(a,b,c){for(var d=a.length,e="string"===typeof a?a.split(""):a,f=0;f<d;f++)f in e&&b.call(c,e[f],f,a)}; function Ma(a,b){for(var c="string"===typeof a?a.split(""):a,d=a.length-1;0<=d;--d)d in c&&b.call(void 0,c[d],d,a)} var Na=Array.prototype.filter?function(a,b){return Array.prototype.filter.call(a,b,void 0)}:function(a,b){for(var c=a.length,d=[],e=0,f="string"===typeof a?a.split(""):a,g=0;g<c;g++)if(g in f){var h=f[g];b.call(void 0,h,g,a)&&(d[e++]=h)}return d},Oa=Array.prototype.map?function(a,b){return Array.prototype.map.call(a,b,void 0)}:function(a,b){for(var c=a.length,d=Array(c),e="string"===typeof a?a.split(""):a,f=0;f<c;f++)f in e&&(d[f]=b.call(void 0,e[f],f,a));return d},Pa=Array.prototype.some?function(a, b){return Array.prototype.some.call(a,b,void 0)}:function(a,b){for(var c=a.length,d="string"===typeof a?a.split(""):a,e=0;e<c;e++)if(e in d&&b.call(void 0,d[e],e,a))return!0;return!1};function Qa(a){a:{var b=Ra;for(var c=a.length,d="string"===typeof a?a.split(""):a,e=0;e<c;e++)if(e in d&&b.call(void 0,d[e],e,a)){b=e;break a}b=-1}return 0>b?null:"string"===typeof a?a.charAt(b):a[b]}function Sa(a,b){return 0<=La(a,b)} function Ta(a,b){b=La(a,b);var c;(c=0<=b)&&Array.prototype.splice.call(a,b,1);return c}function Ua(a,b){var c=0;Ma(a,function(d,e){b.call(void 0,d,e,a)&&1==Array.prototype.splice.call(a,e,1).length&&c++})}function Va(a){return Array.prototype.concat.apply([],arguments)}function Wa(a){var b=a.length;if(0<b){for(var c=Array(b),d=0;d<b;d++)c[d]=a[d];return c}return[]};var Xa=String.prototype.trim?function(a){return a.trim()}:function(a){return/^[\s\xa0]*([\s\S]*?)[\s\xa0]*$/.exec(a)[1]},Ya=/&/g,Za=/</g,$a=/>/g,ab=/"/g,bb=/'/g,cb=/\x00/g,db=/[\x00&<>"']/;function y(a,b){return-1!=a.indexOf(b)}function eb(a,b){return a<b?-1:a>b?1:0};var fb;a:{var gb=l.navigator;if(gb){var hb=gb.userAgent;if(hb){fb=hb;break a}}fb=""}function z(a){return y(fb,a)};function ib(a,b){for(var c in a)b.call(void 0,a[c],c,a)}function jb(a){for(var b in a)return!1;return!0}function kb(a){var b={},c;for(c in a)b[c]=a[c];return b}var lb="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function B(a,b){for(var c,d,e=1;e<arguments.length;e++){d=arguments[e];for(c in d)a[c]=d[c];for(var f=0;f<lb.length;f++)c=lb[f],Object.prototype.hasOwnProperty.call(d,c)&&(a[c]=d[c])}};function mb(a,b){a:{try{var c=a&&a.ownerDocument,d=c&&(c.defaultView||c.parentWindow);d=d||l;if(d.Element&&d.Location){var e=d;break a}}catch(g){}e=null}if(e&&"undefined"!=typeof e[b]&&(!a||!(a instanceof e[b])&&(a instanceof e.Location||a instanceof e.Element))){if(q(a))try{var f=a.constructor.displayName||a.constructor.name||Object.prototype.toString.call(a)}catch(g){f="<object could not be stringified>"}else f=void 0===a?"undefined":null===a?"null":typeof a;Da("Argument is not a %s (or a non-Element, non-Location mock); got: %s", b,f)}};function nb(a,b){this.a=a===ob&&b||"";this.b=pb}nb.prototype.ra=!0;nb.prototype.qa=function(){return this.a};nb.prototype.toString=function(){return"Const{"+this.a+"}"};function qb(a){if(a instanceof nb&&a.constructor===nb&&a.b===pb)return a.a;Da("expected object of type Const, got '"+a+"'");return"type_error:Const"}var pb={},ob={},rb=new nb(ob,"");function sb(a,b){this.a=a===tb&&b||"";this.b=ub}sb.prototype.ra=!0;sb.prototype.qa=function(){return this.a.toString()};sb.prototype.toString=function(){return"TrustedResourceUrl{"+this.a+"}"};function vb(a){if(a instanceof sb&&a.constructor===sb&&a.b===ub)return a.a;Da("expected object of type TrustedResourceUrl, got '"+a+"' of type "+la(a));return"type_error:TrustedResourceUrl"} function wb(a,b){var c=qb(a);if(!xb.test(c))throw Error("Invalid TrustedResourceUrl format: "+c);a=c.replace(yb,function(d,e){if(!Object.prototype.hasOwnProperty.call(b,e))throw Error('Found marker, "'+e+'", in format string, "'+c+'", but no valid label mapping found in args: '+JSON.stringify(b));d=b[e];return d instanceof nb?qb(d):encodeURIComponent(String(d))});return new sb(tb,a)} var yb=/%{(\w+)}/g,xb=/^((https:)?\/\/[0-9a-z.:[\]-]+\/|\/[^/\\]|[^:/\\%]+\/|[^:/\\%]*[?#]|about:blank#)/i,ub={},tb={};function zb(a,b){this.a=a===Ab&&b||"";this.b=Bb}zb.prototype.ra=!0;zb.prototype.qa=function(){return this.a.toString()};zb.prototype.toString=function(){return"SafeUrl{"+this.a+"}"};function Cb(a){if(a instanceof zb&&a.constructor===zb&&a.b===Bb)return a.a;Da("expected object of type SafeUrl, got '"+a+"' of type "+la(a));return"type_error:SafeUrl"}var Db=/^(?:(?:https?|mailto|ftp):|[^:/?#]*(?:[/?#]|$))/i; function Eb(a){if(a instanceof zb)return a;a="object"==typeof a&&a.ra?a.qa():String(a);Db.test(a)||(a="about:invalid#zClosurez");return new zb(Ab,a)}var Bb={},Ab={};function Fb(){this.a="";this.b=Gb}Fb.prototype.ra=!0;Fb.prototype.qa=function(){return this.a.toString()};Fb.prototype.toString=function(){return"SafeHtml{"+this.a+"}"};function Hb(a){if(a instanceof Fb&&a.constructor===Fb&&a.b===Gb)return a.a;Da("expected object of type SafeHtml, got '"+a+"' of type "+la(a));return"type_error:SafeHtml"}var Gb={};function Ib(a){var b=new Fb;b.a=a;return b}Ib("<!DOCTYPE html>");var Jb=Ib("");Ib("<br>");function Kb(a){var b=new sb(tb,qb(rb));mb(a,"HTMLIFrameElement");a.src=vb(b).toString()}function Lb(a,b){mb(a,"HTMLScriptElement");a.src=vb(b);if(null===ja)b:{b=l.document;if((b=b.querySelector&&b.querySelector("script[nonce]"))&&(b=b.nonce||b.getAttribute("nonce"))&&ia.test(b)){ja=b;break b}ja=""}b=ja;b&&a.setAttribute("nonce",b)};function Mb(a,b){for(var c=a.split("%s"),d="",e=Array.prototype.slice.call(arguments,1);e.length&&1<c.length;)d+=c.shift()+e.shift();return d+c.join("%s")}function Nb(a){db.test(a)&&(-1!=a.indexOf("&")&&(a=a.replace(Ya,"&amp;")),-1!=a.indexOf("<")&&(a=a.replace(Za,"&lt;")),-1!=a.indexOf(">")&&(a=a.replace($a,"&gt;")),-1!=a.indexOf('"')&&(a=a.replace(ab,"&quot;")),-1!=a.indexOf("'")&&(a=a.replace(bb,"&#39;")),-1!=a.indexOf("\x00")&&(a=a.replace(cb,"&#0;")));return a};function Ob(a){Ob[" "](a);return a}Ob[" "]=ka;function Pb(a,b){var c=Qb;return Object.prototype.hasOwnProperty.call(c,a)?c[a]:c[a]=b(a)};var Rb=z("Opera"),Sb=z("Trident")||z("MSIE"),Tb=z("Edge"),Ub=Tb||Sb,Vb=z("Gecko")&&!(y(fb.toLowerCase(),"webkit")&&!z("Edge"))&&!(z("Trident")||z("MSIE"))&&!z("Edge"),Wb=y(fb.toLowerCase(),"webkit")&&!z("Edge");function Xb(){var a=l.document;return a?a.documentMode:void 0}var Yb; a:{var Zb="",$b=function(){var a=fb;if(Vb)return/rv:([^\);]+)(\)|;)/.exec(a);if(Tb)return/Edge\/([\d\.]+)/.exec(a);if(Sb)return/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(a);if(Wb)return/WebKit\/(\S+)/.exec(a);if(Rb)return/(?:Version)[ \/]?(\S+)/.exec(a)}();$b&&(Zb=$b?$b[1]:"");if(Sb){var ac=Xb();if(null!=ac&&ac>parseFloat(Zb)){Yb=String(ac);break a}}Yb=Zb}var Qb={}; function bc(a){return Pb(a,function(){for(var b=0,c=Xa(String(Yb)).split("."),d=Xa(String(a)).split("."),e=Math.max(c.length,d.length),f=0;0==b&&f<e;f++){var g=c[f]||"",h=d[f]||"";do{g=/(\d*)(\D*)(.*)/.exec(g)||["","","",""];h=/(\d*)(\D*)(.*)/.exec(h)||["","","",""];if(0==g[0].length&&0==h[0].length)break;b=eb(0==g[1].length?0:parseInt(g[1],10),0==h[1].length?0:parseInt(h[1],10))||eb(0==g[2].length,0==h[2].length)||eb(g[2],h[2]);g=g[3];h=h[3]}while(0==b)}return 0<=b})}var cc; cc=l.document&&Sb?Xb():void 0;try{(new self.OffscreenCanvas(0,0)).getContext("2d")}catch(a){}var dc=!Sb||9<=Number(cc);function ec(a){var b=document;return"string"===typeof a?b.getElementById(a):a}function fc(a,b){ib(b,function(c,d){c&&"object"==typeof c&&c.ra&&(c=c.qa());"style"==d?a.style.cssText=c:"class"==d?a.className=c:"for"==d?a.htmlFor=c:gc.hasOwnProperty(d)?a.setAttribute(gc[d],c):0==d.lastIndexOf("aria-",0)||0==d.lastIndexOf("data-",0)?a.setAttribute(d,c):a[d]=c})} var gc={cellpadding:"cellPadding",cellspacing:"cellSpacing",colspan:"colSpan",frameborder:"frameBorder",height:"height",maxlength:"maxLength",nonce:"nonce",role:"role",rowspan:"rowSpan",type:"type",usemap:"useMap",valign:"vAlign",width:"width"}; function hc(a,b,c){var d=arguments,e=document,f=String(d[0]),g=d[1];if(!dc&&g&&(g.name||g.type)){f=["<",f];g.name&&f.push(' name="',Nb(g.name),'"');if(g.type){f.push(' type="',Nb(g.type),'"');var h={};B(h,g);delete h.type;g=h}f.push(">");f=f.join("")}f=ic(e,f);g&&("string"===typeof g?f.className=g:Array.isArray(g)?f.className=g.join(" "):fc(f,g));2<d.length&&jc(e,f,d);return f} function jc(a,b,c){function d(g){g&&b.appendChild("string"===typeof g?a.createTextNode(g):g)}for(var e=2;e<c.length;e++){var f=c[e];!ma(f)||q(f)&&0<f.nodeType?d(f):x(kc(f)?Wa(f):f,d)}}function ic(a,b){b=String(b);"application/xhtml+xml"===a.contentType&&(b=b.toLowerCase());return a.createElement(b)}function kc(a){if(a&&"number"==typeof a.length){if(q(a))return"function"==typeof a.item||"string"==typeof a.item;if(n(a))return"function"==typeof a.item}return!1};function lc(a){l.setTimeout(function(){throw a;},0)}var mc; function nc(){var a=l.MessageChannel;"undefined"===typeof a&&"undefined"!==typeof window&&window.postMessage&&window.addEventListener&&!z("Presto")&&(a=function(){var e=ic(document,"IFRAME");e.style.display="none";Kb(e);document.documentElement.appendChild(e);var f=e.contentWindow;e=f.document;e.open();e.write(Hb(Jb));e.close();var g="callImmediate"+Math.random(),h="file:"==f.location.protocol?"*":f.location.protocol+"//"+f.location.host;e=r(function(m){if(("*"==h||m.origin==h)&&m.data==g)this.port1.onmessage()}, this);f.addEventListener("message",e,!1);this.port1={};this.port2={postMessage:function(){f.postMessage(g,h)}}});if("undefined"!==typeof a&&!z("Trident")&&!z("MSIE")){var b=new a,c={},d=c;b.port1.onmessage=function(){if(void 0!==c.next){c=c.next;var e=c.Db;c.Db=null;e()}};return function(e){d.next={Db:e};d=d.next;b.port2.postMessage(0)}}return function(e){l.setTimeout(e,0)}};function oc(a,b){pc||qc();rc||(pc(),rc=!0);Ka.add(a,b)}var pc;function qc(){if(l.Promise&&l.Promise.resolve){var a=l.Promise.resolve(void 0);pc=function(){a.then(sc)}}else pc=function(){var b=sc;!n(l.setImmediate)||l.Window&&l.Window.prototype&&!z("Edge")&&l.Window.prototype.setImmediate==l.setImmediate?(mc||(mc=nc()),mc(b)):l.setImmediate(b)}}var rc=!1,Ka=new Ga;function sc(){for(var a;a=Ja();){try{a.a.call(a.b)}catch(b){lc(b)}Fa(Ia,a)}rc=!1};function D(a,b){this.a=tc;this.i=void 0;this.f=this.b=this.c=null;this.g=this.h=!1;if(a!=ka)try{var c=this;a.call(b,function(d){uc(c,vc,d)},function(d){if(!(d instanceof wc))try{if(d instanceof Error)throw d;throw Error("Promise rejected.");}catch(e){}uc(c,xc,d)})}catch(d){uc(this,xc,d)}}var tc=0,vc=2,xc=3;function yc(){this.next=this.f=this.b=this.g=this.a=null;this.c=!1}yc.prototype.reset=function(){this.f=this.b=this.g=this.a=null;this.c=!1};var zc=new Ea(function(){return new yc},function(a){a.reset()}); function Ac(a,b,c){var d=zc.get();d.g=a;d.b=b;d.f=c;return d}function E(a){if(a instanceof D)return a;var b=new D(ka);uc(b,vc,a);return b}function F(a){return new D(function(b,c){c(a)})}function Bc(a,b,c){Cc(a,b,c,null)||oc(sa(b,a))}function Dc(a){return new D(function(b,c){var d=a.length,e=[];if(d)for(var f=function(p,v){d--;e[p]=v;0==d&&b(e)},g=function(p){c(p)},h=0,m;h<a.length;h++)m=a[h],Bc(m,sa(f,h),g);else b(e)})} function Ec(a){return new D(function(b){var c=a.length,d=[];if(c)for(var e=function(h,m,p){c--;d[h]=m?{Mb:!0,value:p}:{Mb:!1,reason:p};0==c&&b(d)},f=0,g;f<a.length;f++)g=a[f],Bc(g,sa(e,f,!0),sa(e,f,!1));else b(d)})}D.prototype.then=function(a,b,c){return Fc(this,n(a)?a:null,n(b)?b:null,c)};D.prototype.$goog_Thenable=!0;k=D.prototype;k.ma=function(a,b){a=Ac(a,a,b);a.c=!0;Gc(this,a);return this};k.o=function(a,b){return Fc(this,null,a,b)}; k.cancel=function(a){if(this.a==tc){var b=new wc(a);oc(function(){Hc(this,b)},this)}};function Hc(a,b){if(a.a==tc)if(a.c){var c=a.c;if(c.b){for(var d=0,e=null,f=null,g=c.b;g&&(g.c||(d++,g.a==a&&(e=g),!(e&&1<d)));g=g.next)e||(f=g);e&&(c.a==tc&&1==d?Hc(c,b):(f?(d=f,d.next==c.f&&(c.f=d),d.next=d.next.next):Ic(c),Jc(c,e,xc,b)))}a.c=null}else uc(a,xc,b)}function Gc(a,b){a.b||a.a!=vc&&a.a!=xc||Kc(a);a.f?a.f.next=b:a.b=b;a.f=b} function Fc(a,b,c,d){var e=Ac(null,null,null);e.a=new D(function(f,g){e.g=b?function(h){try{var m=b.call(d,h);f(m)}catch(p){g(p)}}:f;e.b=c?function(h){try{var m=c.call(d,h);void 0===m&&h instanceof wc?g(h):f(m)}catch(p){g(p)}}:g});e.a.c=a;Gc(a,e);return e.a}k.Yc=function(a){this.a=tc;uc(this,vc,a)};k.Zc=function(a){this.a=tc;uc(this,xc,a)}; function uc(a,b,c){a.a==tc&&(a===c&&(b=xc,c=new TypeError("Promise cannot resolve to itself")),a.a=1,Cc(c,a.Yc,a.Zc,a)||(a.i=c,a.a=b,a.c=null,Kc(a),b!=xc||c instanceof wc||Lc(a,c)))}function Cc(a,b,c,d){if(a instanceof D)return Gc(a,Ac(b||ka,c||null,d)),!0;if(Ba(a))return a.then(b,c,d),!0;if(q(a))try{var e=a.then;if(n(e))return Mc(a,e,b,c,d),!0}catch(f){return c.call(d,f),!0}return!1} function Mc(a,b,c,d,e){function f(m){h||(h=!0,d.call(e,m))}function g(m){h||(h=!0,c.call(e,m))}var h=!1;try{b.call(a,g,f)}catch(m){f(m)}}function Kc(a){a.h||(a.h=!0,oc(a.ec,a))}function Ic(a){var b=null;a.b&&(b=a.b,a.b=b.next,b.next=null);a.b||(a.f=null);return b}k.ec=function(){for(var a;a=Ic(this);)Jc(this,a,this.a,this.i);this.h=!1}; function Jc(a,b,c,d){if(c==xc&&b.b&&!b.c)for(;a&&a.g;a=a.c)a.g=!1;if(b.a)b.a.c=null,Nc(b,c,d);else try{b.c?b.g.call(b.f):Nc(b,c,d)}catch(e){Oc.call(null,e)}Fa(zc,b)}function Nc(a,b,c){b==vc?a.g.call(a.f,c):a.b&&a.b.call(a.f,c)}function Lc(a,b){a.g=!0;oc(function(){a.g&&Oc.call(null,b)})}var Oc=lc;function wc(a){w.call(this,a)}t(wc,w);wc.prototype.name="cancel";function Pc(){0!=Qc&&(Rc[na(this)]=this);this.wa=this.wa;this.na=this.na}var Qc=0,Rc={};Pc.prototype.wa=!1;function Sc(a){if(!a.wa&&(a.wa=!0,a.Ba(),0!=Qc)){var b=na(a);if(0!=Qc&&a.na&&0<a.na.length)throw Error(a+" did not empty its onDisposeCallbacks queue. This probably means it overrode dispose() or disposeInternal() without calling the superclass' method.");delete Rc[b]}}Pc.prototype.Ba=function(){if(this.na)for(;this.na.length;)this.na.shift()()};var Tc=Object.freeze||function(a){return a};var Uc=!Sb||9<=Number(cc),Vc=Sb&&!bc("9"),Wc=function(){if(!l.addEventListener||!Object.defineProperty)return!1;var a=!1,b=Object.defineProperty({},"passive",{get:function(){a=!0}});try{l.addEventListener("test",ka,b),l.removeEventListener("test",ka,b)}catch(c){}return a}();function Xc(a,b){this.type=a;this.b=this.target=b;this.defaultPrevented=!1}Xc.prototype.preventDefault=function(){this.defaultPrevented=!0};function Yc(a,b){Xc.call(this,a?a.type:"");this.relatedTarget=this.b=this.target=null;this.button=this.screenY=this.screenX=this.clientY=this.clientX=0;this.key="";this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1;this.pointerId=0;this.pointerType="";this.a=null;if(a){var c=this.type=a.type,d=a.changedTouches&&a.changedTouches.length?a.changedTouches[0]:null;this.target=a.target||a.srcElement;this.b=b;if(b=a.relatedTarget){if(Vb){a:{try{Ob(b.nodeName);var e=!0;break a}catch(f){}e=!1}e||(b=null)}}else"mouseover"== c?b=a.fromElement:"mouseout"==c&&(b=a.toElement);this.relatedTarget=b;d?(this.clientX=void 0!==d.clientX?d.clientX:d.pageX,this.clientY=void 0!==d.clientY?d.clientY:d.pageY,this.screenX=d.screenX||0,this.screenY=d.screenY||0):(this.clientX=void 0!==a.clientX?a.clientX:a.pageX,this.clientY=void 0!==a.clientY?a.clientY:a.pageY,this.screenX=a.screenX||0,this.screenY=a.screenY||0);this.button=a.button;this.key=a.key||"";this.ctrlKey=a.ctrlKey;this.altKey=a.altKey;this.shiftKey=a.shiftKey;this.metaKey= a.metaKey;this.pointerId=a.pointerId||0;this.pointerType="string"===typeof a.pointerType?a.pointerType:Zc[a.pointerType]||"";this.a=a;a.defaultPrevented&&this.preventDefault()}}t(Yc,Xc);var Zc=Tc({2:"touch",3:"pen",4:"mouse"});Yc.prototype.preventDefault=function(){Yc.Za.preventDefault.call(this);var a=this.a;if(a.preventDefault)a.preventDefault();else if(a.returnValue=!1,Vc)try{if(a.ctrlKey||112<=a.keyCode&&123>=a.keyCode)a.keyCode=-1}catch(b){}};Yc.prototype.f=function(){return this.a};var $c="closure_listenable_"+(1E6*Math.random()|0),ad=0;function bd(a,b,c,d,e){this.listener=a;this.proxy=null;this.src=b;this.type=c;this.capture=!!d;this.Ta=e;this.key=++ad;this.ua=this.Na=!1}function cd(a){a.ua=!0;a.listener=null;a.proxy=null;a.src=null;a.Ta=null};function dd(a){this.src=a;this.a={};this.b=0}dd.prototype.add=function(a,b,c,d,e){var f=a.toString();a=this.a[f];a||(a=this.a[f]=[],this.b++);var g=ed(a,b,d,e);-1<g?(b=a[g],c||(b.Na=!1)):(b=new bd(b,this.src,f,!!d,e),b.Na=c,a.push(b));return b};function fd(a,b){var c=b.type;c in a.a&&Ta(a.a[c],b)&&(cd(b),0==a.a[c].length&&(delete a.a[c],a.b--))}function ed(a,b,c,d){for(var e=0;e<a.length;++e){var f=a[e];if(!f.ua&&f.listener==b&&f.capture==!!c&&f.Ta==d)return e}return-1};var gd="closure_lm_"+(1E6*Math.random()|0),hd={},id=0;function jd(a,b,c,d,e){if(d&&d.once)kd(a,b,c,d,e);else if(Array.isArray(b))for(var f=0;f<b.length;f++)jd(a,b[f],c,d,e);else c=ld(c),a&&a[$c]?md(a,b,c,q(d)?!!d.capture:!!d,e):nd(a,b,c,!1,d,e)} function nd(a,b,c,d,e,f){if(!b)throw Error("Invalid event type");var g=q(e)?!!e.capture:!!e,h=od(a);h||(a[gd]=h=new dd(a));c=h.add(b,c,d,g,f);if(!c.proxy){d=pd();c.proxy=d;d.src=a;d.listener=c;if(a.addEventListener)Wc||(e=g),void 0===e&&(e=!1),a.addEventListener(b.toString(),d,e);else if(a.attachEvent)a.attachEvent(qd(b.toString()),d);else if(a.addListener&&a.removeListener)a.addListener(d);else throw Error("addEventListener and attachEvent are unavailable.");id++}} function pd(){var a=rd,b=Uc?function(c){return a.call(b.src,b.listener,c)}:function(c){c=a.call(b.src,b.listener,c);if(!c)return c};return b}function kd(a,b,c,d,e){if(Array.isArray(b))for(var f=0;f<b.length;f++)kd(a,b[f],c,d,e);else c=ld(c),a&&a[$c]?sd(a,b,c,q(d)?!!d.capture:!!d,e):nd(a,b,c,!0,d,e)} function td(a,b,c,d,e){if(Array.isArray(b))for(var f=0;f<b.length;f++)td(a,b[f],c,d,e);else(d=q(d)?!!d.capture:!!d,c=ld(c),a&&a[$c])?(a=a.u,b=String(b).toString(),b in a.a&&(f=a.a[b],c=ed(f,c,d,e),-1<c&&(cd(f[c]),Array.prototype.splice.call(f,c,1),0==f.length&&(delete a.a[b],a.b--)))):a&&(a=od(a))&&(b=a.a[b.toString()],a=-1,b&&(a=ed(b,c,d,e)),(c=-1<a?b[a]:null)&&vd(c))} function vd(a){if("number"!==typeof a&&a&&!a.ua){var b=a.src;if(b&&b[$c])fd(b.u,a);else{var c=a.type,d=a.proxy;b.removeEventListener?b.removeEventListener(c,d,a.capture):b.detachEvent?b.detachEvent(qd(c),d):b.addListener&&b.removeListener&&b.removeListener(d);id--;(c=od(b))?(fd(c,a),0==c.b&&(c.src=null,b[gd]=null)):cd(a)}}}function qd(a){return a in hd?hd[a]:hd[a]="on"+a} function wd(a,b,c,d){var e=!0;if(a=od(a))if(b=a.a[b.toString()])for(b=b.concat(),a=0;a<b.length;a++){var f=b[a];f&&f.capture==c&&!f.ua&&(f=xd(f,d),e=e&&!1!==f)}return e}function xd(a,b){var c=a.listener,d=a.Ta||a.src;a.Na&&vd(a);return c.call(d,b)} function rd(a,b){if(a.ua)return!0;if(!Uc){if(!b)a:{b=["window","event"];for(var c=l,d=0;d<b.length;d++)if(c=c[b[d]],null==c){b=null;break a}b=c}d=b;b=new Yc(d,this);c=!0;if(!(0>d.keyCode||void 0!=d.returnValue)){a:{var e=!1;if(0==d.keyCode)try{d.keyCode=-1;break a}catch(g){e=!0}if(e||void 0==d.returnValue)d.returnValue=!0}d=[];for(e=b.b;e;e=e.parentNode)d.push(e);a=a.type;for(e=d.length-1;0<=e;e--){b.b=d[e];var f=wd(d[e],a,!0,b);c=c&&f}for(e=0;e<d.length;e++)b.b=d[e],f=wd(d[e],a,!1,b),c=c&&f}return c}return xd(a, new Yc(b,this))}function od(a){a=a[gd];return a instanceof dd?a:null}var yd="__closure_events_fn_"+(1E9*Math.random()>>>0);function ld(a){if(n(a))return a;a[yd]||(a[yd]=function(b){return a.handleEvent(b)});return a[yd]};function G(){Pc.call(this);this.u=new dd(this);this.Yb=this;this.eb=null}t(G,Pc);G.prototype[$c]=!0;G.prototype.addEventListener=function(a,b,c,d){jd(this,a,b,c,d)};G.prototype.removeEventListener=function(a,b,c,d){td(this,a,b,c,d)}; G.prototype.dispatchEvent=function(a){var b,c=this.eb;if(c)for(b=[];c;c=c.eb)b.push(c);c=this.Yb;var d=a.type||a;if("string"===typeof a)a=new Xc(a,c);else if(a instanceof Xc)a.target=a.target||c;else{var e=a;a=new Xc(d,c);B(a,e)}e=!0;if(b)for(var f=b.length-1;0<=f;f--){var g=a.b=b[f];e=zd(g,d,!0,a)&&e}g=a.b=c;e=zd(g,d,!0,a)&&e;e=zd(g,d,!1,a)&&e;if(b)for(f=0;f<b.length;f++)g=a.b=b[f],e=zd(g,d,!1,a)&&e;return e}; G.prototype.Ba=function(){G.Za.Ba.call(this);if(this.u){var a=this.u,b=0,c;for(c in a.a){for(var d=a.a[c],e=0;e<d.length;e++)++b,cd(d[e]);delete a.a[c];a.b--}}this.eb=null};function md(a,b,c,d,e){a.u.add(String(b),c,!1,d,e)}function sd(a,b,c,d,e){a.u.add(String(b),c,!0,d,e)} function zd(a,b,c,d){b=a.u.a[String(b)];if(!b)return!0;b=b.concat();for(var e=!0,f=0;f<b.length;++f){var g=b[f];if(g&&!g.ua&&g.capture==c){var h=g.listener,m=g.Ta||g.src;g.Na&&fd(a.u,g);e=!1!==h.call(m,d)&&e}}return e&&!d.defaultPrevented};function Ad(a,b,c){if(n(a))c&&(a=r(a,c));else if(a&&"function"==typeof a.handleEvent)a=r(a.handleEvent,a);else throw Error("Invalid listener argument");return 2147483647<Number(b)?-1:l.setTimeout(a,b||0)}function Bd(a){var b=null;return(new D(function(c,d){b=Ad(function(){c(void 0)},a);-1==b&&d(Error("Failed to schedule timer."))})).o(function(c){l.clearTimeout(b);throw c;})};function Cd(a){if(a.V&&"function"==typeof a.V)return a.V();if("string"===typeof a)return a.split("");if(ma(a)){for(var b=[],c=a.length,d=0;d<c;d++)b.push(a[d]);return b}b=[];c=0;for(d in a)b[c++]=a[d];return b}function Dd(a){if(a.X&&"function"==typeof a.X)return a.X();if(!a.V||"function"!=typeof a.V){if(ma(a)||"string"===typeof a){var b=[];a=a.length;for(var c=0;c<a;c++)b.push(c);return b}b=[];c=0;for(var d in a)b[c++]=d;return b}} function Ed(a,b){if(a.forEach&&"function"==typeof a.forEach)a.forEach(b,void 0);else if(ma(a)||"string"===typeof a)x(a,b,void 0);else for(var c=Dd(a),d=Cd(a),e=d.length,f=0;f<e;f++)b.call(void 0,d[f],c&&c[f],a)};function Fd(a,b){this.b={};this.a=[];this.c=0;var c=arguments.length;if(1<c){if(c%2)throw Error("Uneven number of arguments");for(var d=0;d<c;d+=2)this.set(arguments[d],arguments[d+1])}else if(a)if(a instanceof Fd)for(c=a.X(),d=0;d<c.length;d++)this.set(c[d],a.get(c[d]));else for(d in a)this.set(d,a[d])}k=Fd.prototype;k.V=function(){Gd(this);for(var a=[],b=0;b<this.a.length;b++)a.push(this.b[this.a[b]]);return a};k.X=function(){Gd(this);return this.a.concat()}; k.clear=function(){this.b={};this.c=this.a.length=0};function Gd(a){if(a.c!=a.a.length){for(var b=0,c=0;b<a.a.length;){var d=a.a[b];Hd(a.b,d)&&(a.a[c++]=d);b++}a.a.length=c}if(a.c!=a.a.length){var e={};for(c=b=0;b<a.a.length;)d=a.a[b],Hd(e,d)||(a.a[c++]=d,e[d]=1),b++;a.a.length=c}}k.get=function(a,b){return Hd(this.b,a)?this.b[a]:b};k.set=function(a,b){Hd(this.b,a)||(this.c++,this.a.push(a));this.b[a]=b}; k.forEach=function(a,b){for(var c=this.X(),d=0;d<c.length;d++){var e=c[d],f=this.get(e);a.call(b,f,e,this)}};function Hd(a,b){return Object.prototype.hasOwnProperty.call(a,b)};var Id=/^(?:([^:/?#.]+):)?(?:\/\/(?:([^/?#]*)@)?([^/#?]*?)(?::([0-9]+))?(?=[/\\#?]|$))?([^?#]+)?(?:\?([^#]*))?(?:#([\s\S]*))?$/;function Jd(a,b){if(a){a=a.split("&");for(var c=0;c<a.length;c++){var d=a[c].indexOf("="),e=null;if(0<=d){var f=a[c].substring(0,d);e=a[c].substring(d+1)}else f=a[c];b(f,e?decodeURIComponent(e.replace(/\+/g," ")):"")}}};function Kd(a,b){this.b=this.i=this.f="";this.l=null;this.g=this.c="";this.h=!1;var c;a instanceof Kd?(this.h=void 0!==b?b:a.h,Ld(this,a.f),this.i=a.i,this.b=a.b,Md(this,a.l),this.c=a.c,Nd(this,Od(a.a)),this.g=a.g):a&&(c=String(a).match(Id))?(this.h=!!b,Ld(this,c[1]||"",!0),this.i=Pd(c[2]||""),this.b=Pd(c[3]||"",!0),Md(this,c[4]),this.c=Pd(c[5]||"",!0),Nd(this,c[6]||"",!0),this.g=Pd(c[7]||"")):(this.h=!!b,this.a=new Qd(null,this.h))} Kd.prototype.toString=function(){var a=[],b=this.f;b&&a.push(Rd(b,Sd,!0),":");var c=this.b;if(c||"file"==b)a.push("//"),(b=this.i)&&a.push(Rd(b,Sd,!0),"@"),a.push(encodeURIComponent(String(c)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),c=this.l,null!=c&&a.push(":",String(c));if(c=this.c)this.b&&"/"!=c.charAt(0)&&a.push("/"),a.push(Rd(c,"/"==c.charAt(0)?Td:Ud,!0));(c=this.a.toString())&&a.push("?",c);(c=this.g)&&a.push("#",Rd(c,Vd));return a.join("")}; Kd.prototype.resolve=function(a){var b=new Kd(this),c=!!a.f;c?Ld(b,a.f):c=!!a.i;c?b.i=a.i:c=!!a.b;c?b.b=a.b:c=null!=a.l;var d=a.c;if(c)Md(b,a.l);else if(c=!!a.c){if("/"!=d.charAt(0))if(this.b&&!this.c)d="/"+d;else{var e=b.c.lastIndexOf("/");-1!=e&&(d=b.c.substr(0,e+1)+d)}e=d;if(".."==e||"."==e)d="";else if(y(e,"./")||y(e,"/.")){d=0==e.lastIndexOf("/",0);e=e.split("/");for(var f=[],g=0;g<e.length;){var h=e[g++];"."==h?d&&g==e.length&&f.push(""):".."==h?((1<f.length||1==f.length&&""!=f[0])&&f.pop(), d&&g==e.length&&f.push("")):(f.push(h),d=!0)}d=f.join("/")}else d=e}c?b.c=d:c=""!==a.a.toString();c?Nd(b,Od(a.a)):c=!!a.g;c&&(b.g=a.g);return b};function Ld(a,b,c){a.f=c?Pd(b,!0):b;a.f&&(a.f=a.f.replace(/:$/,""))}function Md(a,b){if(b){b=Number(b);if(isNaN(b)||0>b)throw Error("Bad port number "+b);a.l=b}else a.l=null}function Nd(a,b,c){b instanceof Qd?(a.a=b,Wd(a.a,a.h)):(c||(b=Rd(b,Xd)),a.a=new Qd(b,a.h))}function H(a,b,c){a.a.set(b,c)}function Yd(a,b){return a.a.get(b)} function Zd(a){return a instanceof Kd?new Kd(a):new Kd(a,void 0)}function $d(a,b){var c=new Kd(null,void 0);Ld(c,"https");a&&(c.b=a);b&&(c.c=b);return c}function Pd(a,b){return a?b?decodeURI(a.replace(/%25/g,"%2525")):decodeURIComponent(a):""}function Rd(a,b,c){return"string"===typeof a?(a=encodeURI(a).replace(b,ae),c&&(a=a.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),a):null}function ae(a){a=a.charCodeAt(0);return"%"+(a>>4&15).toString(16)+(a&15).toString(16)} var Sd=/[#\/\?@]/g,Ud=/[#\?:]/g,Td=/[#\?]/g,Xd=/[#\?@]/g,Vd=/#/g;function Qd(a,b){this.b=this.a=null;this.c=a||null;this.f=!!b}function be(a){a.a||(a.a=new Fd,a.b=0,a.c&&Jd(a.c,function(b,c){a.add(decodeURIComponent(b.replace(/\+/g," ")),c)}))}function ce(a){var b=Dd(a);if("undefined"==typeof b)throw Error("Keys are undefined");var c=new Qd(null,void 0);a=Cd(a);for(var d=0;d<b.length;d++){var e=b[d],f=a[d];Array.isArray(f)?de(c,e,f):c.add(e,f)}return c}k=Qd.prototype; k.add=function(a,b){be(this);this.c=null;a=ee(this,a);var c=this.a.get(a);c||this.a.set(a,c=[]);c.push(b);this.b+=1;return this};function fe(a,b){be(a);b=ee(a,b);Hd(a.a.b,b)&&(a.c=null,a.b-=a.a.get(b).length,a=a.a,Hd(a.b,b)&&(delete a.b[b],a.c--,a.a.length>2*a.c&&Gd(a)))}k.clear=function(){this.a=this.c=null;this.b=0};function ge(a,b){be(a);b=ee(a,b);return Hd(a.a.b,b)}k.forEach=function(a,b){be(this);this.a.forEach(function(c,d){x(c,function(e){a.call(b,e,d,this)},this)},this)}; k.X=function(){be(this);for(var a=this.a.V(),b=this.a.X(),c=[],d=0;d<b.length;d++)for(var e=a[d],f=0;f<e.length;f++)c.push(b[d]);return c};k.V=function(a){be(this);var b=[];if("string"===typeof a)ge(this,a)&&(b=Va(b,this.a.get(ee(this,a))));else{a=this.a.V();for(var c=0;c<a.length;c++)b=Va(b,a[c])}return b};k.set=function(a,b){be(this);this.c=null;a=ee(this,a);ge(this,a)&&(this.b-=this.a.get(a).length);this.a.set(a,[b]);this.b+=1;return this}; k.get=function(a,b){if(!a)return b;a=this.V(a);return 0<a.length?String(a[0]):b};function de(a,b,c){fe(a,b);0<c.length&&(a.c=null,a.a.set(ee(a,b),Wa(c)),a.b+=c.length)}k.toString=function(){if(this.c)return this.c;if(!this.a)return"";for(var a=[],b=this.a.X(),c=0;c<b.length;c++){var d=b[c],e=encodeURIComponent(String(d));d=this.V(d);for(var f=0;f<d.length;f++){var g=e;""!==d[f]&&(g+="="+encodeURIComponent(String(d[f])));a.push(g)}}return this.c=a.join("&")}; function Od(a){var b=new Qd;b.c=a.c;a.a&&(b.a=new Fd(a.a),b.b=a.b);return b}function ee(a,b){b=String(b);a.f&&(b=b.toLowerCase());return b}function Wd(a,b){b&&!a.f&&(be(a),a.c=null,a.a.forEach(function(c,d){var e=d.toLowerCase();d!=e&&(fe(this,d),de(this,e,c))},a));a.f=b};function he(a){var b=[];ie(new je,a,b);return b.join("")}function je(){} function ie(a,b,c){if(null==b)c.push("null");else{if("object"==typeof b){if(Array.isArray(b)){var d=b;b=d.length;c.push("[");for(var e="",f=0;f<b;f++)c.push(e),ie(a,d[f],c),e=",";c.push("]");return}if(b instanceof String||b instanceof Number||b instanceof Boolean)b=b.valueOf();else{c.push("{");e="";for(d in b)Object.prototype.hasOwnProperty.call(b,d)&&(f=b[d],"function"!=typeof f&&(c.push(e),ke(d,c),c.push(":"),ie(a,f,c),e=","));c.push("}");return}}switch(typeof b){case "string":ke(b,c);break;case "number":c.push(isFinite(b)&& !isNaN(b)?String(b):"null");break;case "boolean":c.push(String(b));break;case "function":c.push("null");break;default:throw Error("Unknown type: "+typeof b);}}}var le={'"':'\\"',"\\":"\\\\","/":"\\/","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\x0B":"\\u000b"},me=/\uffff/.test("\uffff")?/[\\"\x00-\x1f\x7f-\uffff]/g:/[\\"\x00-\x1f\x7f-\xff]/g; function ke(a,b){b.push('"',a.replace(me,function(c){var d=le[c];d||(d="\\u"+(c.charCodeAt(0)|65536).toString(16).substr(1),le[c]=d);return d}),'"')};function ne(){var a=I();return Sb&&!!cc&&11==cc||/Edge\/\d+/.test(a)}function oe(){return l.window&&l.window.location.href||self&&self.location&&self.location.href||""}function pe(a,b){b=b||l.window;var c="about:blank";a&&(c=Cb(Eb(a)));b.location.href=c}function qe(a,b){var c=[],d;for(d in a)d in b?typeof a[d]!=typeof b[d]?c.push(d):"object"==typeof a[d]&&null!=a[d]&&null!=b[d]?0<qe(a[d],b[d]).length&&c.push(d):a[d]!==b[d]&&c.push(d):c.push(d);for(d in b)d in a||c.push(d);return c} function re(){var a=I();a=se(a)!=te?null:(a=a.match(/\sChrome\/(\d+)/i))&&2==a.length?parseInt(a[1],10):null;return a&&30>a?!1:!Sb||!cc||9<cc}function ue(a){a=(a||I()).toLowerCase();return a.match(/android/)||a.match(/webos/)||a.match(/iphone|ipad|ipod/)||a.match(/blackberry/)||a.match(/windows phone/)||a.match(/iemobile/)?!0:!1}function ve(a){a=a||l.window;try{a.close()}catch(b){}} function we(a,b,c){var d=Math.floor(1E9*Math.random()).toString();b=b||500;c=c||600;var e=(window.screen.availHeight-c)/2,f=(window.screen.availWidth-b)/2;b={width:b,height:c,top:0<e?e:0,left:0<f?f:0,location:!0,resizable:!0,statusbar:!0,toolbar:!1};c=I().toLowerCase();d&&(b.target=d,y(c,"crios/")&&(b.target="_blank"));se(I())==xe&&(a=a||"http://localhost",b.scrollbars=!0);c=a||"";(a=b)||(a={});d=window;b=c instanceof zb?c:Eb("undefined"!=typeof c.href?c.href:String(c));c=a.target||c.target;e=[]; for(g in a)switch(g){case "width":case "height":case "top":case "left":e.push(g+"="+a[g]);break;case "target":case "noopener":case "noreferrer":break;default:e.push(g+"="+(a[g]?1:0))}var g=e.join(",");if((z("iPhone")&&!z("iPod")&&!z("iPad")||z("iPad")||z("iPod"))&&d.navigator&&d.navigator.standalone&&c&&"_self"!=c)g=ic(document,"A"),mb(g,"HTMLAnchorElement"),b instanceof zb||b instanceof zb||(b="object"==typeof b&&b.ra?b.qa():String(b),Db.test(b)||(b="about:invalid#zClosurez"),b=new zb(Ab,b)),g.href= Cb(b),g.setAttribute("target",c),a.noreferrer&&g.setAttribute("rel","noreferrer"),a=document.createEvent("MouseEvent"),a.initMouseEvent("click",!0,!0,d,1),g.dispatchEvent(a),g={};else if(a.noreferrer){if(g=d.open("",c,g),a=Cb(b),g&&(Ub&&y(a,";")&&(a="'"+a.replace(/'/g,"%27")+"'"),g.opener=null,a=Ib('<meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0; url='+Nb(a)+'">'),d=g.document))d.write(Hb(a)),d.close()}else(g=d.open(Cb(b),c,g))&&a.noopener&&(g.opener=null);if(g)try{g.focus()}catch(h){}return g} function ye(a){return new D(function(b){function c(){Bd(2E3).then(function(){if(!a||a.closed)b();else return c()})}return c()})}var ze=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,Ae=/^[^@]+@[^@]+$/;function Be(){var a=null;return(new D(function(b){"complete"==l.document.readyState?b():(a=function(){b()},kd(window,"load",a))})).o(function(b){td(window,"load",a);throw b;})} function Ce(){return De(void 0)?Be().then(function(){return new D(function(a,b){var c=l.document,d=setTimeout(function(){b(Error("Cordova framework is not ready."))},1E3);c.addEventListener("deviceready",function(){clearTimeout(d);a()},!1)})}):F(Error("Cordova must run in an Android or iOS file scheme."))}function De(a){a=a||I();return!("file:"!==Ee()&&"ionic:"!==Ee()||!a.toLowerCase().match(/iphone|ipad|ipod|android/))}function Fe(){var a=l.window;try{return!(!a||a==a.top)}catch(b){return!1}} function Ge(){return"undefined"!==typeof l.WorkerGlobalScope&&"function"===typeof l.importScripts}function He(){return firebase.INTERNAL.hasOwnProperty("reactNative")?"ReactNative":firebase.INTERNAL.hasOwnProperty("node")?"Node":Ge()?"Worker":"Browser"}function Ie(){var a=He();return"ReactNative"===a||"Node"===a}function Je(){for(var a=50,b=[];0<a;)b.push("1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(Math.floor(62*Math.random()))),a--;return b.join("")} var xe="Firefox",te="Chrome"; function se(a){var b=a.toLowerCase();if(y(b,"opera/")||y(b,"opr/")||y(b,"opios/"))return"Opera";if(y(b,"iemobile"))return"IEMobile";if(y(b,"msie")||y(b,"trident/"))return"IE";if(y(b,"edge/"))return"Edge";if(y(b,"firefox/"))return xe;if(y(b,"silk/"))return"Silk";if(y(b,"blackberry"))return"Blackberry";if(y(b,"webos"))return"Webos";if(!y(b,"safari/")||y(b,"chrome/")||y(b,"crios/")||y(b,"android"))if(!y(b,"chrome/")&&!y(b,"crios/")||y(b,"edge/")){if(y(b,"android"))return"Android";if((a=a.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/))&& 2==a.length)return a[1]}else return te;else return"Safari";return"Other"}var Ke={jd:"FirebaseCore-web",ld:"FirebaseUI-web"};function Le(a,b){b=b||[];var c=[],d={},e;for(e in Ke)d[Ke[e]]=!0;for(e=0;e<b.length;e++)"undefined"!==typeof d[b[e]]&&(delete d[b[e]],c.push(b[e]));c.sort();b=c;b.length||(b=["FirebaseCore-web"]);c=He();"Browser"===c?(d=I(),c=se(d)):"Worker"===c&&(d=I(),c=se(d)+"-"+c);return c+"/JsCore/"+a+"/"+b.join(",")}function I(){return l.navigator&&l.navigator.userAgent||""} function J(a,b){a=a.split(".");b=b||l;for(var c=0;c<a.length&&"object"==typeof b&&null!=b;c++)b=b[a[c]];c!=a.length&&(b=void 0);return b}function Me(){try{var a=l.localStorage,b=Ne();if(a)return a.setItem(b,"1"),a.removeItem(b),ne()?!!l.indexedDB:!0}catch(c){return Ge()&&!!l.indexedDB}return!1}function Oe(){return(Pe()||"chrome-extension:"===Ee()||De())&&!Ie()&&Me()&&!Ge()}function Pe(){return"http:"===Ee()||"https:"===Ee()}function Ee(){return l.location&&l.location.protocol||null} function Qe(a){a=a||I();return ue(a)||se(a)==xe?!1:!0}function Re(a){return"undefined"===typeof a?null:he(a)}function Se(a){var b={},c;for(c in a)a.hasOwnProperty(c)&&null!==a[c]&&void 0!==a[c]&&(b[c]=a[c]);return b}function Te(a){if(null!==a)return JSON.parse(a)}function Ne(a){return a?a:Math.floor(1E9*Math.random()).toString()}function Ue(a){a=a||I();return"Safari"==se(a)||a.toLowerCase().match(/iphone|ipad|ipod/)?!1:!0} function Ve(){var a=l.___jsl;if(a&&a.H)for(var b in a.H)if(a.H[b].r=a.H[b].r||[],a.H[b].L=a.H[b].L||[],a.H[b].r=a.H[b].L.concat(),a.CP)for(var c=0;c<a.CP.length;c++)a.CP[c]=null}function We(a,b){if(a>b)throw Error("Short delay should be less than long delay!");this.a=a;this.c=b;a=I();b=He();this.b=ue(a)||"ReactNative"===b} We.prototype.get=function(){var a=l.navigator;return(a&&"boolean"===typeof a.onLine&&(Pe()||"chrome-extension:"===Ee()||"undefined"!==typeof a.connection)?a.onLine:1)?this.b?this.c:this.a:Math.min(5E3,this.a)};function Xe(){var a=l.document;return a&&"undefined"!==typeof a.visibilityState?"visible"==a.visibilityState:!0} function Ye(){var a=l.document,b=null;return Xe()||!a?E():(new D(function(c){b=function(){Xe()&&(a.removeEventListener("visibilitychange",b,!1),c())};a.addEventListener("visibilitychange",b,!1)})).o(function(c){a.removeEventListener("visibilitychange",b,!1);throw c;})}function Ze(a){try{var b=new Date(parseInt(a,10));if(!isNaN(b.getTime())&&!/[^0-9]/.test(a))return b.toUTCString()}catch(c){}return null}function $e(){return!(!J("fireauth.oauthhelper",l)&&!J("fireauth.iframe",l))} function af(){var a=l.navigator;return a&&a.serviceWorker&&a.serviceWorker.controller||null}function bf(){var a=l.navigator;return a&&a.serviceWorker?E().then(function(){return a.serviceWorker.ready}).then(function(b){return b.active||null}).o(function(){return null}):E(null)};var cf={};function df(a){cf[a]||(cf[a]=!0,"undefined"!==typeof console&&"function"===typeof console.warn&&console.warn(a))};var ef;try{var ff={};Object.defineProperty(ff,"abcd",{configurable:!0,enumerable:!0,value:1});Object.defineProperty(ff,"abcd",{configurable:!0,enumerable:!0,value:2});ef=2==ff.abcd}catch(a){ef=!1}function K(a,b,c){ef?Object.defineProperty(a,b,{configurable:!0,enumerable:!0,value:c}):a[b]=c}function L(a,b){if(b)for(var c in b)b.hasOwnProperty(c)&&K(a,c,b[c])}function gf(a){var b={};L(b,a);return b}function hf(a){var b={},c;for(c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);return b} function jf(a,b){if(!b||!b.length)return!0;if(!a)return!1;for(var c=0;c<b.length;c++){var d=a[b[c]];if(void 0===d||null===d||""===d)return!1}return!0}function kf(a){var b=a;if("object"==typeof a&&null!=a){b="length"in a?[]:{};for(var c in a)K(b,c,kf(a[c]))}return b};/* Copyright 2019 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ function lf(a){var b=a&&(a[mf]?"phone":null);if(b&&a&&a[nf]){K(this,"uid",a[nf]);K(this,"displayName",a[of]||null);var c=null;a[pf]&&(c=(new Date(a[pf])).toUTCString());K(this,"enrollmentTime",c);K(this,"factorId",b)}else throw new u("internal-error","Internal assert: invalid MultiFactorInfo object");}lf.prototype.v=function(){return{uid:this.uid,displayName:this.displayName,factorId:this.factorId,enrollmentTime:this.enrollmentTime}};function qf(a){try{var b=new rf(a)}catch(c){b=null}return b} var of="displayName",pf="enrolledAt",nf="mfaEnrollmentId",mf="phoneInfo";function rf(a){lf.call(this,a);K(this,"phoneNumber",a[mf])}t(rf,lf);rf.prototype.v=function(){var a=rf.Za.v.call(this);a.phoneNumber=this.phoneNumber;return a};function sf(a){var b={},c=a[tf],d=a[uf],e=a[vf];a=qf(a[wf]);if(!e||e!=xf&&e!=yf&&!c||e==yf&&!d||e==zf&&!a)throw Error("Invalid checkActionCode response!");e==yf?(b[Af]=c||null,b[Bf]=c||null,b[Cf]=d):(b[Af]=d||null,b[Bf]=d||null,b[Cf]=c||null);b[Df]=a||null;K(this,Ef,e);K(this,Ff,kf(b))} var zf="REVERT_SECOND_FACTOR_ADDITION",xf="EMAIL_SIGNIN",yf="VERIFY_AND_CHANGE_EMAIL",tf="email",wf="mfaInfo",uf="newEmail",vf="requestType",Cf="email",Af="fromEmail",Df="multiFactorInfo",Bf="previousEmail",Ff="data",Ef="operation";function Gf(a){a=Zd(a);var b=Yd(a,Hf)||null,c=Yd(a,If)||null,d=Yd(a,Jf)||null;d=d?Kf[d]||null:null;if(!b||!c||!d)throw new u("argument-error",Hf+", "+If+"and "+Jf+" are required in a valid action code URL.");L(this,{apiKey:b,operation:d,code:c,continueUrl:Yd(a,Lf)||null,languageCode:Yd(a,Mf)||null,tenantId:Yd(a,Nf)||null})} var Hf="apiKey",If="oobCode",Lf="continueUrl",Mf="languageCode",Jf="mode",Nf="tenantId",Kf={recoverEmail:"RECOVER_EMAIL",resetPassword:"PASSWORD_RESET",revertSecondFactorAddition:zf,signIn:xf,verifyAndChangeEmail:yf,verifyEmail:"VERIFY_EMAIL"};function Of(a){try{return new Gf(a)}catch(b){return null}};function Pf(a){var b=a[Qf];if("undefined"===typeof b)throw new u("missing-continue-uri");if("string"!==typeof b||"string"===typeof b&&!b.length)throw new u("invalid-continue-uri");this.h=b;this.b=this.a=null;this.g=!1;var c=a[Rf];if(c&&"object"===typeof c){b=c[Sf];var d=c[Tf];c=c[Uf];if("string"===typeof b&&b.length){this.a=b;if("undefined"!==typeof d&&"boolean"!==typeof d)throw new u("argument-error",Tf+" property must be a boolean when specified.");this.g=!!d;if("undefined"!==typeof c&&("string"!== typeof c||"string"===typeof c&&!c.length))throw new u("argument-error",Uf+" property must be a non empty string when specified.");this.b=c||null}else{if("undefined"!==typeof b)throw new u("argument-error",Sf+" property must be a non empty string when specified.");if("undefined"!==typeof d||"undefined"!==typeof c)throw new u("missing-android-pkg-name");}}else if("undefined"!==typeof c)throw new u("argument-error",Rf+" property must be a non null object when specified.");this.f=null;if((b=a[Vf])&&"object"=== typeof b)if(b=b[Wf],"string"===typeof b&&b.length)this.f=b;else{if("undefined"!==typeof b)throw new u("argument-error",Wf+" property must be a non empty string when specified.");}else if("undefined"!==typeof b)throw new u("argument-error",Vf+" property must be a non null object when specified.");b=a[Xf];if("undefined"!==typeof b&&"boolean"!==typeof b)throw new u("argument-error",Xf+" property must be a boolean when specified.");this.c=!!b;a=a[Yf];if("undefined"!==typeof a&&("string"!==typeof a||"string"=== typeof a&&!a.length))throw new u("argument-error",Yf+" property must be a non empty string when specified.");this.i=a||null}var Rf="android",Yf="dynamicLinkDomain",Xf="handleCodeInApp",Vf="iOS",Qf="url",Tf="installApp",Uf="minimumVersion",Sf="packageName",Wf="bundleId"; function Zf(a){var b={};b.continueUrl=a.h;b.canHandleCodeInApp=a.c;if(b.androidPackageName=a.a)b.androidMinimumVersion=a.b,b.androidInstallApp=a.g;b.iOSBundleId=a.f;b.dynamicLinkDomain=a.i;for(var c in b)null===b[c]&&delete b[c];return b};function $f(a){return Oa(a,function(b){b=b.toString(16);return 1<b.length?b:"0"+b}).join("")};var ag=null;function bg(a){var b="";cg(a,function(c){b+=String.fromCharCode(c)});return b}function cg(a,b){function c(m){for(;d<a.length;){var p=a.charAt(d++),v=ag[p];if(null!=v)return v;if(!/^[\s\xa0]*$/.test(p))throw Error("Unknown base64 encoding at char: "+p);}return m}dg();for(var d=0;;){var e=c(-1),f=c(0),g=c(64),h=c(64);if(64===h&&-1===e)break;b(e<<2|f>>4);64!=g&&(b(f<<4&240|g>>2),64!=h&&b(g<<6&192|h))}} function dg(){if(!ag){ag={};for(var a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),b=["+/=","+/","-_=","-_.","-_"],c=0;5>c;c++)for(var d=a.concat(b[c].split("")),e=0;e<d.length;e++){var f=d[e];void 0===ag[f]&&(ag[f]=e)}}};function eg(a){var b=fg(a);if(!(b&&b.sub&&b.iss&&b.aud&&b.exp))throw Error("Invalid JWT");this.g=a;this.c=b.exp;this.h=b.sub;ta();this.a=b.provider_id||b.firebase&&b.firebase.sign_in_provider||null;this.f=b.firebase&&b.firebase.tenant||null;this.b=!!b.is_anonymous||"anonymous"==this.a}eg.prototype.S=function(){return this.f};eg.prototype.i=function(){return this.b};eg.prototype.toString=function(){return this.g};function gg(a){try{return new eg(a)}catch(b){return null}} function fg(a){if(!a)return null;a=a.split(".");if(3!=a.length)return null;a=a[1];for(var b=(4-a.length%4)%4,c=0;c<b;c++)a+=".";try{return JSON.parse(bg(a))}catch(d){}return null};var hg="oauth_consumer_key oauth_nonce oauth_signature oauth_signature_method oauth_timestamp oauth_token oauth_version".split(" "),ig=["client_id","response_type","scope","redirect_uri","state"],jg={kd:{Ha:"locale",ta:700,sa:600,ea:"facebook.com",Va:ig},md:{Ha:null,ta:500,sa:750,ea:"github.com",Va:ig},nd:{Ha:"hl",ta:515,sa:680,ea:"google.com",Va:ig},td:{Ha:"lang",ta:485,sa:705,ea:"twitter.com",Va:hg},gd:{Ha:"locale",ta:600,sa:600,ea:"apple.com",Va:[]}}; function kg(a){for(var b in jg)if(jg[b].ea==a)return jg[b];return null};function lg(a){var b={};b["facebook.com"]=mg;b["google.com"]=ng;b["github.com"]=og;b["twitter.com"]=pg;var c=a&&a[qg];try{if(c)return b[c]?new b[c](a):new rg(a);if("undefined"!==typeof a[sg])return new tg(a)}catch(d){}return null}var sg="idToken",qg="providerId"; function tg(a){var b=a[qg];if(!b&&a[sg]){var c=gg(a[sg]);c&&c.a&&(b=c.a)}if(!b)throw Error("Invalid additional user info!");if("anonymous"==b||"custom"==b)b=null;c=!1;"undefined"!==typeof a.isNewUser?c=!!a.isNewUser:"identitytoolkit#SignupNewUserResponse"===a.kind&&(c=!0);K(this,"providerId",b);K(this,"isNewUser",c)}function rg(a){tg.call(this,a);a=Te(a.rawUserInfo||"{}");K(this,"profile",kf(a||{}))}t(rg,tg); function mg(a){rg.call(this,a);if("facebook.com"!=this.providerId)throw Error("Invalid provider ID!");}t(mg,rg);function og(a){rg.call(this,a);if("github.com"!=this.providerId)throw Error("Invalid provider ID!");K(this,"username",this.profile&&this.profile.login||null)}t(og,rg);function ng(a){rg.call(this,a);if("google.com"!=this.providerId)throw Error("Invalid provider ID!");}t(ng,rg); function pg(a){rg.call(this,a);if("twitter.com"!=this.providerId)throw Error("Invalid provider ID!");K(this,"username",a.screenName||null)}t(pg,rg);function ug(a){var b=Zd(a),c=Yd(b,"link"),d=Yd(Zd(c),"link");b=Yd(b,"deep_link_id");return Yd(Zd(b),"link")||b||d||c||a};function vg(a,b){if(!a&&!b)throw new u("internal-error","Internal assert: no raw session string available");if(a&&b)throw new u("internal-error","Internal assert: unable to determine the session type");this.a=a||null;this.b=b||null;this.type=this.a?wg:xg}var wg="enroll",xg="signin";vg.prototype.Fa=function(){return this.a?E(this.a):E(this.b)};vg.prototype.v=function(){return this.type==wg?{multiFactorSession:{idToken:this.a}}:{multiFactorSession:{pendingCredential:this.b}}};function yg(){}yg.prototype.ia=function(){};yg.prototype.b=function(){};yg.prototype.c=function(){};yg.prototype.v=function(){};function zg(a,b){return a.then(function(c){if(c[Ag]){var d=gg(c[Ag]);if(!d||b!=d.h)throw new u("user-mismatch");return c}throw new u("user-mismatch");}).o(function(c){throw c&&c.code&&c.code==ua+"user-not-found"?new u("user-mismatch"):c;})} function Bg(a,b){if(b)this.a=b;else throw new u("internal-error","failed to construct a credential");K(this,"providerId",a);K(this,"signInMethod",a)}Bg.prototype.ia=function(a){return Cg(a,Dg(this))};Bg.prototype.b=function(a,b){var c=Dg(this);c.idToken=b;return Eg(a,c)};Bg.prototype.c=function(a,b){return zg(Fg(a,Dg(this)),b)};function Dg(a){return{pendingToken:a.a,requestUri:"http://localhost"}}Bg.prototype.v=function(){return{providerId:this.providerId,signInMethod:this.signInMethod,pendingToken:this.a}}; function Gg(a){if(a&&a.providerId&&a.signInMethod&&0==a.providerId.indexOf("saml.")&&a.pendingToken)try{return new Bg(a.providerId,a.pendingToken)}catch(b){}return null} function Hg(a,b,c){this.a=null;if(b.idToken||b.accessToken)b.idToken&&K(this,"idToken",b.idToken),b.accessToken&&K(this,"accessToken",b.accessToken),b.nonce&&!b.pendingToken&&K(this,"nonce",b.nonce),b.pendingToken&&(this.a=b.pendingToken);else if(b.oauthToken&&b.oauthTokenSecret)K(this,"accessToken",b.oauthToken),K(this,"secret",b.oauthTokenSecret);else throw new u("internal-error","failed to construct a credential");K(this,"providerId",a);K(this,"signInMethod",c)} Hg.prototype.ia=function(a){return Cg(a,Ig(this))};Hg.prototype.b=function(a,b){var c=Ig(this);c.idToken=b;return Eg(a,c)};Hg.prototype.c=function(a,b){var c=Ig(this);return zg(Fg(a,c),b)}; function Ig(a){var b={};a.idToken&&(b.id_token=a.idToken);a.accessToken&&(b.access_token=a.accessToken);a.secret&&(b.oauth_token_secret=a.secret);b.providerId=a.providerId;a.nonce&&!a.a&&(b.nonce=a.nonce);b={postBody:ce(b).toString(),requestUri:"http://localhost"};a.a&&(delete b.postBody,b.pendingToken=a.a);return b} Hg.prototype.v=function(){var a={providerId:this.providerId,signInMethod:this.signInMethod};this.idToken&&(a.oauthIdToken=this.idToken);this.accessToken&&(a.oauthAccessToken=this.accessToken);this.secret&&(a.oauthTokenSecret=this.secret);this.nonce&&(a.nonce=this.nonce);this.a&&(a.pendingToken=this.a);return a}; function Jg(a){if(a&&a.providerId&&a.signInMethod){var b={idToken:a.oauthIdToken,accessToken:a.oauthTokenSecret?null:a.oauthAccessToken,oauthTokenSecret:a.oauthTokenSecret,oauthToken:a.oauthTokenSecret&&a.oauthAccessToken,nonce:a.nonce,pendingToken:a.pendingToken};try{return new Hg(a.providerId,b,a.signInMethod)}catch(c){}}return null}function Kg(a,b){this.Oc=b||[];L(this,{providerId:a,isOAuthProvider:!0});this.Fb={};this.lb=(kg(a)||{}).Ha||null;this.kb=null} Kg.prototype.Ia=function(a){this.Fb=kb(a);return this};function Lg(a){if("string"!==typeof a||0!=a.indexOf("saml."))throw new u("argument-error",'SAML provider IDs must be prefixed with "saml."');Kg.call(this,a,[])}t(Lg,Kg);function M(a){Kg.call(this,a,ig);this.a=[]}t(M,Kg);M.prototype.Aa=function(a){Sa(this.a,a)||this.a.push(a);return this};M.prototype.Nb=function(){return Wa(this.a)}; M.prototype.credential=function(a,b){var c;q(a)?c={idToken:a.idToken||null,accessToken:a.accessToken||null,nonce:a.rawNonce||null}:c={idToken:a||null,accessToken:b||null};if(!c.idToken&&!c.accessToken)throw new u("argument-error","credential failed: must provide the ID token and/or the access token.");return new Hg(this.providerId,c,this.providerId)};function Mg(){M.call(this,"facebook.com")}t(Mg,M);K(Mg,"PROVIDER_ID","facebook.com");K(Mg,"FACEBOOK_SIGN_IN_METHOD","facebook.com"); function Ng(a){if(!a)throw new u("argument-error","credential failed: expected 1 argument (the OAuth access token).");var b=a;q(a)&&(b=a.accessToken);return(new Mg).credential({accessToken:b})}function Og(){M.call(this,"github.com")}t(Og,M);K(Og,"PROVIDER_ID","github.com");K(Og,"GITHUB_SIGN_IN_METHOD","github.com"); function Pg(a){if(!a)throw new u("argument-error","credential failed: expected 1 argument (the OAuth access token).");var b=a;q(a)&&(b=a.accessToken);return(new Og).credential({accessToken:b})}function Qg(){M.call(this,"google.com");this.Aa("profile")}t(Qg,M);K(Qg,"PROVIDER_ID","google.com");K(Qg,"GOOGLE_SIGN_IN_METHOD","google.com");function Rg(a,b){var c=a;q(a)&&(c=a.idToken,b=a.accessToken);return(new Qg).credential({idToken:c,accessToken:b})}function Sg(){Kg.call(this,"twitter.com",hg)}t(Sg,Kg); K(Sg,"PROVIDER_ID","twitter.com");K(Sg,"TWITTER_SIGN_IN_METHOD","twitter.com");function Tg(a,b){var c=a;q(c)||(c={oauthToken:a,oauthTokenSecret:b});if(!c.oauthToken||!c.oauthTokenSecret)throw new u("argument-error","credential failed: expected 2 arguments (the OAuth access token and secret).");return new Hg("twitter.com",c,"twitter.com")} function Ug(a,b,c){this.a=a;this.f=b;K(this,"providerId","password");K(this,"signInMethod",c===Vg.EMAIL_LINK_SIGN_IN_METHOD?Vg.EMAIL_LINK_SIGN_IN_METHOD:Vg.EMAIL_PASSWORD_SIGN_IN_METHOD)}Ug.prototype.ia=function(a){return this.signInMethod==Vg.EMAIL_LINK_SIGN_IN_METHOD?N(a,Wg,{email:this.a,oobCode:this.f}):N(a,Xg,{email:this.a,password:this.f})}; Ug.prototype.b=function(a,b){return this.signInMethod==Vg.EMAIL_LINK_SIGN_IN_METHOD?N(a,Yg,{idToken:b,email:this.a,oobCode:this.f}):N(a,Zg,{idToken:b,email:this.a,password:this.f})};Ug.prototype.c=function(a,b){return zg(this.ia(a),b)};Ug.prototype.v=function(){return{email:this.a,password:this.f,signInMethod:this.signInMethod}};function $g(a){return a&&a.email&&a.password?new Ug(a.email,a.password,a.signInMethod):null}function Vg(){L(this,{providerId:"password",isOAuthProvider:!1})} function ah(a,b){b=bh(b);if(!b)throw new u("argument-error","Invalid email link!");return new Ug(a,b.code,Vg.EMAIL_LINK_SIGN_IN_METHOD)}function bh(a){a=ug(a);return(a=Of(a))&&a.operation===xf?a:null}L(Vg,{PROVIDER_ID:"password"});L(Vg,{EMAIL_LINK_SIGN_IN_METHOD:"emailLink"});L(Vg,{EMAIL_PASSWORD_SIGN_IN_METHOD:"password"});function ch(a){if(!(a.bb&&a.ab||a.Ja&&a.da))throw new u("internal-error");this.a=a;K(this,"providerId","phone");this.ea="phone";K(this,"signInMethod","phone")} ch.prototype.ia=function(a){return a.cb(dh(this))};ch.prototype.b=function(a,b){var c=dh(this);c.idToken=b;return N(a,eh,c)};ch.prototype.c=function(a,b){var c=dh(this);c.operation="REAUTH";a=N(a,fh,c);return zg(a,b)};ch.prototype.v=function(){var a={providerId:"phone"};this.a.bb&&(a.verificationId=this.a.bb);this.a.ab&&(a.verificationCode=this.a.ab);this.a.Ja&&(a.temporaryProof=this.a.Ja);this.a.da&&(a.phoneNumber=this.a.da);return a}; function gh(a){if(a&&"phone"===a.providerId&&(a.verificationId&&a.verificationCode||a.temporaryProof&&a.phoneNumber)){var b={};x(["verificationId","verificationCode","temporaryProof","phoneNumber"],function(c){a[c]&&(b[c]=a[c])});return new ch(b)}return null}function dh(a){return a.a.Ja&&a.a.da?{temporaryProof:a.a.Ja,phoneNumber:a.a.da}:{sessionInfo:a.a.bb,code:a.a.ab}} function hh(a){try{this.a=a||firebase.auth()}catch(b){throw new u("argument-error","Either an instance of firebase.auth.Auth must be passed as an argument to the firebase.auth.PhoneAuthProvider constructor, or the default firebase App instance must be initialized via firebase.initializeApp().");}L(this,{providerId:"phone",isOAuthProvider:!1})} hh.prototype.cb=function(a,b){var c=this.a.b;return E(b.verify()).then(function(d){if("string"!==typeof d)throw new u("argument-error","An implementation of firebase.auth.ApplicationVerifier.prototype.verify() must return a firebase.Promise that resolves with a string.");switch(b.type){case "recaptcha":var e=q(a)?a.session:null,f=q(a)?a.phoneNumber:a,g;e&&e.type==wg?g=e.Fa().then(function(h){return ih(c,{idToken:h,phoneEnrollmentInfo:{phoneNumber:f,recaptchaToken:d}})}):e&&e.type==xg?g=e.Fa().then(function(h){return jh(c, {mfaPendingCredential:h,mfaEnrollmentId:a.multiFactorHint&&a.multiFactorHint.uid||a.multiFactorUid,phoneSignInInfo:{recaptchaToken:d}})}):g=kh(c,{phoneNumber:f,recaptchaToken:d});return g.then(function(h){"function"===typeof b.reset&&b.reset();return h},function(h){"function"===typeof b.reset&&b.reset();throw h;});default:throw new u("argument-error",'Only firebase.auth.ApplicationVerifiers with type="recaptcha" are currently supported.');}})}; function lh(a,b){if(!a)throw new u("missing-verification-id");if(!b)throw new u("missing-verification-code");return new ch({bb:a,ab:b})}L(hh,{PROVIDER_ID:"phone"});L(hh,{PHONE_SIGN_IN_METHOD:"phone"}); function mh(a){if(a.temporaryProof&&a.phoneNumber)return new ch({Ja:a.temporaryProof,da:a.phoneNumber});var b=a&&a.providerId;if(!b||"password"===b)return null;var c=a&&a.oauthAccessToken,d=a&&a.oauthTokenSecret,e=a&&a.nonce,f=a&&a.oauthIdToken,g=a&&a.pendingToken;try{switch(b){case "google.com":return Rg(f,c);case "facebook.com":return Ng(c);case "github.com":return Pg(c);case "twitter.com":return Tg(c,d);default:return c||d||f||g?g?0==b.indexOf("saml.")?new Bg(b,g):new Hg(b,{pendingToken:g,idToken:a.oauthIdToken, accessToken:a.oauthAccessToken},b):(new M(b)).credential({idToken:f,accessToken:c,rawNonce:e}):null}}catch(h){return null}}function nh(a){if(!a.isOAuthProvider)throw new u("invalid-oauth-provider");};function oh(a,b,c,d,e,f,g){this.c=a;this.b=b||null;this.g=c||null;this.f=d||null;this.i=f||null;this.h=g||null;this.a=e||null;if(this.g||this.a){if(this.g&&this.a)throw new u("invalid-auth-event");if(this.g&&!this.f)throw new u("invalid-auth-event");}else throw new u("invalid-auth-event");}oh.prototype.getUid=function(){var a=[];a.push(this.c);this.b&&a.push(this.b);this.f&&a.push(this.f);this.h&&a.push(this.h);return a.join("-")};oh.prototype.S=function(){return this.h}; oh.prototype.v=function(){return{type:this.c,eventId:this.b,urlResponse:this.g,sessionId:this.f,postBody:this.i,tenantId:this.h,error:this.a&&this.a.v()}};function ph(a){a=a||{};return a.type?new oh(a.type,a.eventId,a.urlResponse,a.sessionId,a.error&&wa(a.error),a.postBody,a.tenantId):null};/* Copyright 2018 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ function qh(){this.b=null;this.a=[]}var rh=null;function sh(a){var b=rh;b.a.push(a);b.b||(b.b=function(c){for(var d=0;d<b.a.length;d++)b.a[d](c)},a=J("universalLinks.subscribe",l),"function"===typeof a&&a(null,b.b))};function th(a){var b="unauthorized-domain",c=void 0,d=Zd(a);a=d.b;d=d.f;"chrome-extension"==d?c=Mb("This chrome extension ID (chrome-extension://%s) is not authorized to run this operation. Add it to the OAuth redirect domains list in the Firebase console -> Auth section -> Sign in method tab.",a):"http"==d||"https"==d?c=Mb("This domain (%s) is not authorized to run this operation. Add it to the OAuth redirect domains list in the Firebase console -> Auth section -> Sign in method tab.",a):b="operation-not-supported-in-this-environment"; u.call(this,b,c)}t(th,u);function uh(a,b,c){u.call(this,a,c);a=b||{};a.Gb&&K(this,"email",a.Gb);a.da&&K(this,"phoneNumber",a.da);a.credential&&K(this,"credential",a.credential);a.Wb&&K(this,"tenantId",a.Wb)}t(uh,u);uh.prototype.v=function(){var a={code:this.code,message:this.message};this.email&&(a.email=this.email);this.phoneNumber&&(a.phoneNumber=this.phoneNumber);this.tenantId&&(a.tenantId=this.tenantId);var b=this.credential&&this.credential.v();b&&B(a,b);return a};uh.prototype.toJSON=function(){return this.v()}; function vh(a){if(a.code){var b=a.code||"";0==b.indexOf(ua)&&(b=b.substring(ua.length));var c={credential:mh(a),Wb:a.tenantId};if(a.email)c.Gb=a.email;else if(a.phoneNumber)c.da=a.phoneNumber;else if(!c.credential)return new u(b,a.message||void 0);return new uh(b,c,a.message)}return null};function wh(){}wh.prototype.c=null;function xh(a){return a.c||(a.c=a.b())};var yh;function zh(){}t(zh,wh);zh.prototype.a=function(){var a=Ah(this);return a?new ActiveXObject(a):new XMLHttpRequest};zh.prototype.b=function(){var a={};Ah(this)&&(a[0]=!0,a[1]=!0);return a}; function Ah(a){if(!a.f&&"undefined"==typeof XMLHttpRequest&&"undefined"!=typeof ActiveXObject){for(var b=["MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP"],c=0;c<b.length;c++){var d=b[c];try{return new ActiveXObject(d),a.f=d}catch(e){}}throw Error("Could not create ActiveXObject. ActiveX might be disabled, or MSXML might not be installed");}return a.f}yh=new zh;function Bh(){}t(Bh,wh);Bh.prototype.a=function(){var a=new XMLHttpRequest;if("withCredentials"in a)return a;if("undefined"!=typeof XDomainRequest)return new Ch;throw Error("Unsupported browser");};Bh.prototype.b=function(){return{}}; function Ch(){this.a=new XDomainRequest;this.readyState=0;this.onreadystatechange=null;this.responseType=this.responseText=this.response="";this.status=-1;this.statusText="";this.a.onload=r(this.oc,this);this.a.onerror=r(this.Pb,this);this.a.onprogress=r(this.pc,this);this.a.ontimeout=r(this.tc,this)}k=Ch.prototype;k.open=function(a,b,c){if(null!=c&&!c)throw Error("Only async requests are supported.");this.a.open(a,b)}; k.send=function(a){if(a)if("string"==typeof a)this.a.send(a);else throw Error("Only string data is supported");else this.a.send()};k.abort=function(){this.a.abort()};k.setRequestHeader=function(){};k.getResponseHeader=function(a){return"content-type"==a.toLowerCase()?this.a.contentType:""};k.oc=function(){this.status=200;this.response=this.responseText=this.a.responseText;Dh(this,4)};k.Pb=function(){this.status=500;this.response=this.responseText="";Dh(this,4)};k.tc=function(){this.Pb()}; k.pc=function(){this.status=200;Dh(this,1)};function Dh(a,b){a.readyState=b;if(a.onreadystatechange)a.onreadystatechange()}k.getAllResponseHeaders=function(){return"content-type: "+this.a.contentType};function Eh(a,b,c){this.reset(a,b,c,void 0,void 0)}Eh.prototype.a=null;var Fh=0;Eh.prototype.reset=function(a,b,c,d,e){"number"==typeof e||Fh++;d||ta();delete this.a};function Gh(a){this.f=a;this.b=this.c=this.a=null}function Hh(a,b){this.name=a;this.value=b}Hh.prototype.toString=function(){return this.name};var Ih=new Hh("SEVERE",1E3),Jh=new Hh("WARNING",900),Kh=new Hh("CONFIG",700),Lh=new Hh("FINE",500);function Mh(a){if(a.c)return a.c;if(a.a)return Mh(a.a);Da("Root logger has no level set.");return null}Gh.prototype.log=function(a,b,c){if(a.value>=Mh(this).value)for(n(b)&&(b=b()),a=new Eh(a,String(b),this.f),c&&(a.a=c),c=this;c;)c=c.a};var Nh={},Oh=null; function Ph(a){Oh||(Oh=new Gh(""),Nh[""]=Oh,Oh.c=Kh);var b;if(!(b=Nh[a])){b=new Gh(a);var c=a.lastIndexOf("."),d=a.substr(c+1);c=Ph(a.substr(0,c));c.b||(c.b={});c.b[d]=b;b.a=c;Nh[a]=b}return b};function Qh(a,b){a&&a.log(Lh,b,void 0)};function Rh(a){this.f=a}t(Rh,wh);Rh.prototype.a=function(){return new Sh(this.f)};Rh.prototype.b=function(a){return function(){return a}}({});function Sh(a){G.call(this);this.s=a;this.readyState=Th;this.status=0;this.responseType=this.responseText=this.response=this.statusText="";this.onreadystatechange=null;this.i=new Headers;this.b=null;this.m="GET";this.g="";this.a=!1;this.h=Ph("goog.net.FetchXmlHttp");this.l=this.c=this.f=null}t(Sh,G);var Th=0;k=Sh.prototype; k.open=function(a,b){if(this.readyState!=Th)throw this.abort(),Error("Error reopening a connection");this.m=a;this.g=b;this.readyState=1;Uh(this)};k.send=function(a){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.a=!0;var b={headers:this.i,method:this.m,credentials:void 0,cache:void 0};a&&(b.body=a);this.s.fetch(new Request(this.g,b)).then(this.sc.bind(this),this.Sa.bind(this))}; k.abort=function(){this.response=this.responseText="";this.i=new Headers;this.status=0;this.c&&this.c.cancel("Request was aborted.");1<=this.readyState&&this.a&&4!=this.readyState&&(this.a=!1,Vh(this,!1));this.readyState=Th}; k.sc=function(a){this.a&&(this.f=a,this.b||(this.b=a.headers,this.readyState=2,Uh(this)),this.a&&(this.readyState=3,Uh(this),this.a&&("arraybuffer"===this.responseType?a.arrayBuffer().then(this.qc.bind(this),this.Sa.bind(this)):"undefined"!==typeof l.ReadableStream&&"body"in a?(this.response=this.responseText="",this.c=a.body.getReader(),this.l=new TextDecoder,Wh(this)):a.text().then(this.rc.bind(this),this.Sa.bind(this)))))};function Wh(a){a.c.read().then(a.nc.bind(a)).catch(a.Sa.bind(a))} k.nc=function(a){if(this.a){var b=this.l.decode(a.value?a.value:new Uint8Array(0),{stream:!a.done});b&&(this.response=this.responseText+=b);a.done?Vh(this,!0):Uh(this);3==this.readyState&&Wh(this)}};k.rc=function(a){this.a&&(this.response=this.responseText=a,Vh(this,!0))};k.qc=function(a){this.a&&(this.response=a,Vh(this,!0))};k.Sa=function(a){var b=this.h;b&&b.log(Jh,"Failed to fetch url "+this.g,a instanceof Error?a:Error(a));this.a&&Vh(this,!0)}; function Vh(a,b){b&&a.f&&(a.status=a.f.status,a.statusText=a.f.statusText);a.readyState=4;a.f=null;a.c=null;a.l=null;Uh(a)}k.setRequestHeader=function(a,b){this.i.append(a,b)};k.getResponseHeader=function(a){return this.b?this.b.get(a.toLowerCase())||"":((a=this.h)&&a.log(Jh,"Attempting to get response header but no headers have been received for url: "+this.g,void 0),"")}; k.getAllResponseHeaders=function(){if(!this.b){var a=this.h;a&&a.log(Jh,"Attempting to get all response headers but no headers have been received for url: "+this.g,void 0);return""}a=[];for(var b=this.b.entries(),c=b.next();!c.done;)c=c.value,a.push(c[0]+": "+c[1]),c=b.next();return a.join("\r\n")};function Uh(a){a.onreadystatechange&&a.onreadystatechange.call(a)};function Xh(a){G.call(this);this.headers=new Fd;this.D=a||null;this.c=!1;this.B=this.a=null;this.h=this.P=this.l="";this.f=this.O=this.i=this.N=!1;this.g=0;this.s=null;this.m=Yh;this.w=this.R=!1}t(Xh,G);var Yh="";Xh.prototype.b=Ph("goog.net.XhrIo");var Zh=/^https?$/i,$h=["POST","PUT"]; function ai(a,b,c,d,e){if(a.a)throw Error("[goog.net.XhrIo] Object is active with another request="+a.l+"; newUri="+b);c=c?c.toUpperCase():"GET";a.l=b;a.h="";a.P=c;a.N=!1;a.c=!0;a.a=a.D?a.D.a():yh.a();a.B=a.D?xh(a.D):xh(yh);a.a.onreadystatechange=r(a.Sb,a);try{Qh(a.b,bi(a,"Opening Xhr")),a.O=!0,a.a.open(c,String(b),!0),a.O=!1}catch(g){Qh(a.b,bi(a,"Error opening Xhr: "+g.message));ci(a,g);return}b=d||"";var f=new Fd(a.headers);e&&Ed(e,function(g,h){f.set(h,g)});e=Qa(f.X());d=l.FormData&&b instanceof l.FormData;!Sa($h,c)||e||d||f.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");f.forEach(function(g,h){this.a.setRequestHeader(h,g)},a);a.m&&(a.a.responseType=a.m);"withCredentials"in a.a&&a.a.withCredentials!==a.R&&(a.a.withCredentials=a.R);try{di(a),0<a.g&&(a.w=ei(a.a),Qh(a.b,bi(a,"Will abort after "+a.g+"ms if incomplete, xhr2 "+a.w)),a.w?(a.a.timeout=a.g,a.a.ontimeout=r(a.Ka,a)):a.s=Ad(a.Ka,a.g,a)),Qh(a.b,bi(a,"Sending request")),a.i=!0,a.a.send(b),a.i=!1}catch(g){Qh(a.b, bi(a,"Send error: "+g.message)),ci(a,g)}}function ei(a){return Sb&&bc(9)&&"number"===typeof a.timeout&&void 0!==a.ontimeout}function Ra(a){return"content-type"==a.toLowerCase()}k=Xh.prototype;k.Ka=function(){"undefined"!=typeof ha&&this.a&&(this.h="Timed out after "+this.g+"ms, aborting",Qh(this.b,bi(this,this.h)),this.dispatchEvent("timeout"),this.abort(8))};function ci(a,b){a.c=!1;a.a&&(a.f=!0,a.a.abort(),a.f=!1);a.h=b;fi(a);gi(a)} function fi(a){a.N||(a.N=!0,a.dispatchEvent("complete"),a.dispatchEvent("error"))}k.abort=function(){this.a&&this.c&&(Qh(this.b,bi(this,"Aborting")),this.c=!1,this.f=!0,this.a.abort(),this.f=!1,this.dispatchEvent("complete"),this.dispatchEvent("abort"),gi(this))};k.Ba=function(){this.a&&(this.c&&(this.c=!1,this.f=!0,this.a.abort(),this.f=!1),gi(this,!0));Xh.Za.Ba.call(this)};k.Sb=function(){this.wa||(this.O||this.i||this.f?hi(this):this.Hc())};k.Hc=function(){hi(this)}; function hi(a){if(a.c&&"undefined"!=typeof ha)if(a.B[1]&&4==ii(a)&&2==ji(a))Qh(a.b,bi(a,"Local request error detected and ignored"));else if(a.i&&4==ii(a))Ad(a.Sb,0,a);else if(a.dispatchEvent("readystatechange"),4==ii(a)){Qh(a.b,bi(a,"Request complete"));a.c=!1;try{var b=ji(a);a:switch(b){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var c=!0;break a;default:c=!1}var d;if(!(d=c)){var e;if(e=0===b){var f=String(a.l).match(Id)[1]||null;if(!f&&l.self&&l.self.location){var g=l.self.location.protocol; f=g.substr(0,g.length-1)}e=!Zh.test(f?f.toLowerCase():"")}d=e}if(d)a.dispatchEvent("complete"),a.dispatchEvent("success");else{try{var h=2<ii(a)?a.a.statusText:""}catch(m){Qh(a.b,"Can not get status: "+m.message),h=""}a.h=h+" ["+ji(a)+"]";fi(a)}}finally{gi(a)}}}function gi(a,b){if(a.a){di(a);var c=a.a,d=a.B[0]?ka:null;a.a=null;a.B=null;b||a.dispatchEvent("ready");try{c.onreadystatechange=d}catch(e){(a=a.b)&&a.log(Ih,"Problem encountered resetting onreadystatechange: "+e.message,void 0)}}} function di(a){a.a&&a.w&&(a.a.ontimeout=null);a.s&&(l.clearTimeout(a.s),a.s=null)}function ii(a){return a.a?a.a.readyState:0}function ji(a){try{return 2<ii(a)?a.a.status:-1}catch(b){return-1}}function ki(a){try{return a.a?a.a.responseText:""}catch(b){return Qh(a.b,"Can not get responseText: "+b.message),""}} k.getResponse=function(){try{if(!this.a)return null;if("response"in this.a)return this.a.response;switch(this.m){case Yh:case "text":return this.a.responseText;case "arraybuffer":if("mozResponseArrayBuffer"in this.a)return this.a.mozResponseArrayBuffer}var a=this.b;a&&a.log(Ih,"Response type "+this.m+" is not supported on this browser",void 0);return null}catch(b){return Qh(this.b,"Can not get response: "+b.message),null}};function bi(a,b){return b+" ["+a.P+" "+a.l+" "+ji(a)+"]"};/* Portions of this code are from MochiKit, received by The Closure Authors under the MIT license. All other code is Copyright 2005-2009 The Closure Authors. All Rights Reserved. */ function li(a){var b=mi;this.g=[];this.w=b;this.s=a||null;this.f=this.a=!1;this.c=void 0;this.u=this.B=this.i=!1;this.h=0;this.b=null;this.l=0}li.prototype.cancel=function(a){if(this.a)this.c instanceof li&&this.c.cancel();else{if(this.b){var b=this.b;delete this.b;a?b.cancel(a):(b.l--,0>=b.l&&b.cancel())}this.w?this.w.call(this.s,this):this.u=!0;this.a||(a=new ni(this),oi(this),pi(this,!1,a))}};li.prototype.m=function(a,b){this.i=!1;pi(this,a,b)};function pi(a,b,c){a.a=!0;a.c=c;a.f=!b;qi(a)} function oi(a){if(a.a){if(!a.u)throw new ri(a);a.u=!1}}function si(a,b){ti(a,null,b,void 0)}function ti(a,b,c,d){a.g.push([b,c,d]);a.a&&qi(a)}li.prototype.then=function(a,b,c){var d,e,f=new D(function(g,h){d=g;e=h});ti(this,d,function(g){g instanceof ni?f.cancel():e(g)});return f.then(a,b,c)};li.prototype.$goog_Thenable=!0;function ui(a){return Pa(a.g,function(b){return n(b[1])})} function qi(a){if(a.h&&a.a&&ui(a)){var b=a.h,c=vi[b];c&&(l.clearTimeout(c.a),delete vi[b]);a.h=0}a.b&&(a.b.l--,delete a.b);b=a.c;for(var d=c=!1;a.g.length&&!a.i;){var e=a.g.shift(),f=e[0],g=e[1];e=e[2];if(f=a.f?g:f)try{var h=f.call(e||a.s,b);void 0!==h&&(a.f=a.f&&(h==b||h instanceof Error),a.c=b=h);if(Ba(b)||"function"===typeof l.Promise&&b instanceof l.Promise)d=!0,a.i=!0}catch(m){b=m,a.f=!0,ui(a)||(c=!0)}}a.c=b;d&&(h=r(a.m,a,!0),d=r(a.m,a,!1),b instanceof li?(ti(b,h,d),b.B=!0):b.then(h,d));c&&(b= new wi(b),vi[b.a]=b,a.h=b.a)}function ri(){w.call(this)}t(ri,w);ri.prototype.message="Deferred has already fired";ri.prototype.name="AlreadyCalledError";function ni(){w.call(this)}t(ni,w);ni.prototype.message="Deferred was canceled";ni.prototype.name="CanceledError";function wi(a){this.a=l.setTimeout(r(this.c,this),0);this.b=a}wi.prototype.c=function(){delete vi[this.a];throw this.b;};var vi={};function xi(a){var b={},c=b.document||document,d=vb(a).toString(),e=ic(document,"SCRIPT"),f={Tb:e,Ka:void 0},g=new li(f),h=null,m=null!=b.timeout?b.timeout:5E3;0<m&&(h=window.setTimeout(function(){yi(e,!0);var p=new zi(Ai,"Timeout reached for loading script "+d);oi(g);pi(g,!1,p)},m),f.Ka=h);e.onload=e.onreadystatechange=function(){e.readyState&&"loaded"!=e.readyState&&"complete"!=e.readyState||(yi(e,b.ud||!1,h),oi(g),pi(g,!0,null))};e.onerror=function(){yi(e,!0,h);var p=new zi(Bi,"Error while loading script "+ d);oi(g);pi(g,!1,p)};f=b.attributes||{};B(f,{type:"text/javascript",charset:"UTF-8"});fc(e,f);Lb(e,a);Ci(c).appendChild(e);return g}function Ci(a){var b;return(b=(a||document).getElementsByTagName("HEAD"))&&0!=b.length?b[0]:a.documentElement}function mi(){if(this&&this.Tb){var a=this.Tb;a&&"SCRIPT"==a.tagName&&yi(a,!0,this.Ka)}} function yi(a,b,c){null!=c&&l.clearTimeout(c);a.onload=ka;a.onerror=ka;a.onreadystatechange=ka;b&&window.setTimeout(function(){a&&a.parentNode&&a.parentNode.removeChild(a)},0)}var Bi=0,Ai=1;function zi(a,b){var c="Jsloader error (code #"+a+")";b&&(c+=": "+b);w.call(this,c);this.code=a}t(zi,w);function Di(a){this.f=a}t(Di,wh);Di.prototype.a=function(){return new this.f};Di.prototype.b=function(){return{}}; function Ei(a,b,c){this.c=a;a=b||{};this.u=a.secureTokenEndpoint||"https://securetoken.googleapis.com/v1/token";this.m=a.secureTokenTimeout||Fi;this.g=kb(a.secureTokenHeaders||Gi);this.h=a.firebaseEndpoint||"https://www.googleapis.com/identitytoolkit/v3/relyingparty/";this.l=a.identityPlatformEndpoint||"https://identitytoolkit.googleapis.com/v2/";this.i=a.firebaseTimeout||Hi;this.a=kb(a.firebaseHeaders||Ii);c&&(this.a["X-Client-Version"]=c,this.g["X-Client-Version"]=c);c="Node"==He();c=l.XMLHttpRequest|| c&&firebase.INTERNAL.node&&firebase.INTERNAL.node.XMLHttpRequest;if(!c&&!Ge())throw new u("internal-error","The XMLHttpRequest compatibility library was not found.");this.f=void 0;Ge()?this.f=new Rh(self):Ie()?this.f=new Di(c):this.f=new Bh;this.b=null}var Ji,Ag="idToken",Fi=new We(3E4,6E4),Gi={"Content-Type":"application/x-www-form-urlencoded"},Hi=new We(3E4,6E4),Ii={"Content-Type":"application/json"};function Ki(a,b){b?a.a["X-Firebase-Locale"]=b:delete a.a["X-Firebase-Locale"]} function Li(a,b){b?(a.a["X-Client-Version"]=b,a.g["X-Client-Version"]=b):(delete a.a["X-Client-Version"],delete a.g["X-Client-Version"])}Ei.prototype.S=function(){return this.b};function Mi(a,b,c,d,e,f,g){re()||Ge()?a=r(a.w,a):(Ji||(Ji=new D(function(h,m){Ni(h,m)})),a=r(a.s,a));a(b,c,d,e,f,g)} Ei.prototype.w=function(a,b,c,d,e,f){if(Ge()&&("undefined"===typeof l.fetch||"undefined"===typeof l.Headers||"undefined"===typeof l.Request))throw new u("operation-not-supported-in-this-environment","fetch, Headers and Request native APIs or equivalent Polyfills must be available to support HTTP requests from a Worker environment.");var g=new Xh(this.f);if(f){g.g=Math.max(0,f);var h=setTimeout(function(){g.dispatchEvent("timeout")},f)}md(g,"complete",function(){h&&clearTimeout(h);var m=null;try{m= JSON.parse(ki(this))||null}catch(p){m=null}b&&b(m)});sd(g,"ready",function(){h&&clearTimeout(h);Sc(this)});sd(g,"timeout",function(){h&&clearTimeout(h);Sc(this);b&&b(null)});ai(g,a,c,d,e)};var Oi=new nb(ob,"https://apis.google.com/js/client.js?onload=%{onload}"),Pi="__fcb"+Math.floor(1E6*Math.random()).toString(); function Ni(a,b){if(((window.gapi||{}).client||{}).request)a();else{l[Pi]=function(){((window.gapi||{}).client||{}).request?a():b(Error("CORS_UNSUPPORTED"))};var c=wb(Oi,{onload:Pi});si(xi(c),function(){b(Error("CORS_UNSUPPORTED"))})}} Ei.prototype.s=function(a,b,c,d,e){var f=this;Ji.then(function(){window.gapi.client.setApiKey(f.c);var g=window.gapi.auth.getToken();window.gapi.auth.setToken(null);window.gapi.client.request({path:a,method:c,body:d,headers:e,authType:"none",callback:function(h){window.gapi.auth.setToken(g);b&&b(h)}})}).o(function(g){b&&b({error:{message:g&&g.message||"CORS_UNSUPPORTED"}})})}; function Qi(a,b){return new D(function(c,d){"refresh_token"==b.grant_type&&b.refresh_token||"authorization_code"==b.grant_type&&b.code?Mi(a,a.u+"?key="+encodeURIComponent(a.c),function(e){e?e.error?d(Ri(e)):e.access_token&&e.refresh_token?c(e):d(new u("internal-error")):d(new u("network-request-failed"))},"POST",ce(b).toString(),a.g,a.m.get()):d(new u("internal-error"))})} function Si(a,b,c,d,e,f,g){var h=Zd(b+c);H(h,"key",a.c);g&&H(h,"cb",ta().toString());var m="GET"==d;if(m)for(var p in e)e.hasOwnProperty(p)&&H(h,p,e[p]);return new D(function(v,C){Mi(a,h.toString(),function(A){A?A.error?C(Ri(A,f||{})):v(A):C(new u("network-request-failed"))},d,m?void 0:he(Se(e)),a.a,a.i.get())})}function Ti(a){a=a.email;if("string"!==typeof a||!Ae.test(a))throw new u("invalid-email");}function Ui(a){"email"in a&&Ti(a)} function Vi(a,b){return N(a,Wi,{identifier:b,continueUri:Pe()?oe():"http://localhost"}).then(function(c){return c.signinMethods||[]})}function Xi(a){return N(a,Yi,{}).then(function(b){return b.authorizedDomains||[]})}function O(a){if(!a[Ag]){if(a.mfaPendingCredential)throw new u("multi-factor-auth-required",null,kb(a));throw new u("internal-error");}} function Zi(a){if(a.phoneNumber||a.temporaryProof){if(!a.phoneNumber||!a.temporaryProof)throw new u("internal-error");}else{if(!a.sessionInfo)throw new u("missing-verification-id");if(!a.code)throw new u("missing-verification-code");}}Ei.prototype.vb=function(){return N(this,$i,{})};Ei.prototype.xb=function(a,b){return N(this,aj,{idToken:a,email:b})};Ei.prototype.yb=function(a,b){return N(this,Zg,{idToken:a,password:b})};var bj={displayName:"DISPLAY_NAME",photoUrl:"PHOTO_URL"};k=Ei.prototype; k.zb=function(a,b){var c={idToken:a},d=[];ib(bj,function(e,f){var g=b[f];null===g?d.push(e):f in b&&(c[f]=g)});d.length&&(c.deleteAttribute=d);return N(this,aj,c)};k.rb=function(a,b){a={requestType:"PASSWORD_RESET",email:a};B(a,b);return N(this,cj,a)};k.sb=function(a,b){a={requestType:"EMAIL_SIGNIN",email:a};B(a,b);return N(this,dj,a)};k.qb=function(a,b){a={requestType:"VERIFY_EMAIL",idToken:a};B(a,b);return N(this,ej,a)}; k.Ab=function(a,b,c){a={requestType:"VERIFY_AND_CHANGE_EMAIL",idToken:a,newEmail:b};B(a,c);return N(this,fj,a)};function kh(a,b){return N(a,gj,b)}k.cb=function(a){return N(this,hj,a)};function ih(a,b){return N(a,ij,b).then(function(c){return c.phoneSessionInfo.sessionInfo})} function jj(a){if(!a.phoneVerificationInfo)throw new u("internal-error");if(!a.phoneVerificationInfo.sessionInfo)throw new u("missing-verification-id");if(!a.phoneVerificationInfo.code)throw new u("missing-verification-code");}function jh(a,b){return N(a,kj,b).then(function(c){return c.phoneResponseInfo.sessionInfo})}function lj(a,b,c){return N(a,mj,{idToken:b,deleteProvider:c})}function nj(a){if(!a.requestUri||!a.sessionId&&!a.postBody&&!a.pendingToken)throw new u("internal-error");} function oj(a,b){b.oauthIdToken&&b.providerId&&0==b.providerId.indexOf("oidc.")&&!b.pendingToken&&(a.sessionId?b.nonce=a.sessionId:a.postBody&&(a=new Qd(a.postBody),ge(a,"nonce")&&(b.nonce=a.get("nonce"))));return b} function pj(a){var b=null;a.needConfirmation?(a.code="account-exists-with-different-credential",b=vh(a)):"FEDERATED_USER_ID_ALREADY_LINKED"==a.errorMessage?(a.code="credential-already-in-use",b=vh(a)):"EMAIL_EXISTS"==a.errorMessage?(a.code="email-already-in-use",b=vh(a)):a.errorMessage&&(b=qj(a.errorMessage));if(b)throw b;O(a)}function Cg(a,b){b.returnIdpCredential=!0;return N(a,rj,b)}function Eg(a,b){b.returnIdpCredential=!0;return N(a,sj,b)} function Fg(a,b){b.returnIdpCredential=!0;b.autoCreate=!1;return N(a,tj,b)}function uj(a){if(!a.oobCode)throw new u("invalid-action-code");}k.jb=function(a,b){return N(this,vj,{oobCode:a,newPassword:b})};k.Pa=function(a){return N(this,wj,{oobCode:a})};k.fb=function(a){return N(this,xj,{oobCode:a})}; var xj={endpoint:"setAccountInfo",A:uj,Y:"email",C:!0},wj={endpoint:"resetPassword",A:uj,G:function(a){var b=a.requestType;if(!b||!a.email&&"EMAIL_SIGNIN"!=b&&"VERIFY_AND_CHANGE_EMAIL"!=b)throw new u("internal-error");},C:!0},yj={endpoint:"signupNewUser",A:function(a){Ti(a);if(!a.password)throw new u("weak-password");},G:O,U:!0,C:!0},Wi={endpoint:"createAuthUri",C:!0},zj={endpoint:"deleteAccount",M:["idToken"]},mj={endpoint:"setAccountInfo",M:["idToken","deleteProvider"],A:function(a){if("array"!= la(a.deleteProvider))throw new u("internal-error");}},Wg={endpoint:"emailLinkSignin",M:["email","oobCode"],A:Ti,G:O,U:!0,C:!0},Yg={endpoint:"emailLinkSignin",M:["idToken","email","oobCode"],A:Ti,G:O,U:!0},Aj={endpoint:"accounts/mfaEnrollment:finalize",M:["idToken","phoneVerificationInfo"],A:jj,G:O,C:!0,La:!0},Bj={endpoint:"accounts/mfaSignIn:finalize",M:["mfaPendingCredential","phoneVerificationInfo"],A:jj,G:O,C:!0,La:!0},Cj={endpoint:"getAccountInfo"},dj={endpoint:"getOobConfirmationCode",M:["requestType"], A:function(a){if("EMAIL_SIGNIN"!=a.requestType)throw new u("internal-error");Ti(a)},Y:"email",C:!0},ej={endpoint:"getOobConfirmationCode",M:["idToken","requestType"],A:function(a){if("VERIFY_EMAIL"!=a.requestType)throw new u("internal-error");},Y:"email",C:!0},fj={endpoint:"getOobConfirmationCode",M:["idToken","newEmail","requestType"],A:function(a){if("VERIFY_AND_CHANGE_EMAIL"!=a.requestType)throw new u("internal-error");},Y:"email",C:!0},cj={endpoint:"getOobConfirmationCode",M:["requestType"],A:function(a){if("PASSWORD_RESET"!= a.requestType)throw new u("internal-error");Ti(a)},Y:"email",C:!0},Yi={hb:!0,endpoint:"getProjectConfig",Rb:"GET"},Dj={hb:!0,endpoint:"getRecaptchaParam",Rb:"GET",G:function(a){if(!a.recaptchaSiteKey)throw new u("internal-error");}},vj={endpoint:"resetPassword",A:uj,Y:"email",C:!0},gj={endpoint:"sendVerificationCode",M:["phoneNumber","recaptchaToken"],Y:"sessionInfo",C:!0},aj={endpoint:"setAccountInfo",M:["idToken"],A:Ui,U:!0},Zg={endpoint:"setAccountInfo",M:["idToken"],A:function(a){Ui(a);if(!a.password)throw new u("weak-password"); },G:O,U:!0},$i={endpoint:"signupNewUser",G:O,U:!0,C:!0},ij={endpoint:"accounts/mfaEnrollment:start",M:["idToken","phoneEnrollmentInfo"],A:function(a){if(!a.phoneEnrollmentInfo)throw new u("internal-error");if(!a.phoneEnrollmentInfo.phoneNumber)throw new u("missing-phone-number");if(!a.phoneEnrollmentInfo.recaptchaToken)throw new u("missing-app-credential");},G:function(a){if(!a.phoneSessionInfo||!a.phoneSessionInfo.sessionInfo)throw new u("internal-error");},C:!0,La:!0},kj={endpoint:"accounts/mfaSignIn:start", M:["mfaPendingCredential","mfaEnrollmentId","phoneSignInInfo"],A:function(a){if(!a.phoneSignInInfo||!a.phoneSignInInfo.recaptchaToken)throw new u("missing-app-credential");},G:function(a){if(!a.phoneResponseInfo||!a.phoneResponseInfo.sessionInfo)throw new u("internal-error");},C:!0,La:!0},rj={endpoint:"verifyAssertion",A:nj,Wa:oj,G:pj,U:!0,C:!0},tj={endpoint:"verifyAssertion",A:nj,Wa:oj,G:function(a){if(a.errorMessage&&"USER_NOT_FOUND"==a.errorMessage)throw new u("user-not-found");if(a.errorMessage)throw qj(a.errorMessage); O(a)},U:!0,C:!0},sj={endpoint:"verifyAssertion",A:function(a){nj(a);if(!a.idToken)throw new u("internal-error");},Wa:oj,G:pj,U:!0},Ej={endpoint:"verifyCustomToken",A:function(a){if(!a.token)throw new u("invalid-custom-token");},G:O,U:!0,C:!0},Xg={endpoint:"verifyPassword",A:function(a){Ti(a);if(!a.password)throw new u("wrong-password");},G:O,U:!0,C:!0},hj={endpoint:"verifyPhoneNumber",A:Zi,G:O,C:!0},eh={endpoint:"verifyPhoneNumber",A:function(a){if(!a.idToken)throw new u("internal-error");Zi(a)}, G:function(a){if(a.temporaryProof)throw a.code="credential-already-in-use",vh(a);O(a)}},fh={Eb:{USER_NOT_FOUND:"user-not-found"},endpoint:"verifyPhoneNumber",A:Zi,G:O,C:!0},Fj={endpoint:"accounts/mfaEnrollment:withdraw",M:["idToken","mfaEnrollmentId"],G:function(a){if(!!a[Ag]^!!a.refreshToken)throw new u("internal-error");},C:!0,La:!0}; function N(a,b,c){if(!jf(c,b.M))return F(new u("internal-error"));var d=!!b.La,e=b.Rb||"POST",f;return E(c).then(b.A).then(function(){b.U&&(c.returnSecureToken=!0);b.C&&a.b&&"undefined"===typeof c.tenantId&&(c.tenantId=a.b);return d?Si(a,a.l,b.endpoint,e,c,b.Eb,b.hb||!1):Si(a,a.h,b.endpoint,e,c,b.Eb,b.hb||!1)}).then(function(g){f=g;return b.Wa?b.Wa(c,f):f}).then(b.G).then(function(){if(!b.Y)return f;if(!(b.Y in f))throw new u("internal-error");return f[b.Y]})} function qj(a){return Ri({error:{errors:[{message:a}],code:400,message:a}})} function Ri(a,b){var c=(a.error&&a.error.errors&&a.error.errors[0]||{}).reason||"";var d={keyInvalid:"invalid-api-key",ipRefererBlocked:"app-not-authorized"};if(c=d[c]?new u(d[c]):null)return c;c=a.error&&a.error.message||"";d={INVALID_CUSTOM_TOKEN:"invalid-custom-token",CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_EMAIL:"invalid-email",INVALID_PASSWORD:"wrong-password",USER_DISABLED:"user-disabled", MISSING_PASSWORD:"internal-error",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",INVALID_PENDING_TOKEN:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",MISSING_OR_INVALID_NONCE:"missing-or-invalid-nonce",INVALID_MESSAGE_PAYLOAD:"invalid-message-payload",INVALID_RECIPIENT_EMAIL:"invalid-recipient-email",INVALID_SENDER:"invalid-sender",EMAIL_NOT_FOUND:"user-not-found",RESET_PASSWORD_EXCEED_LIMIT:"too-many-requests", EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",INVALID_PROVIDER_ID:"invalid-provider-id",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",CORS_UNSUPPORTED:"cors-unsupported",DYNAMIC_LINK_NOT_ACTIVATED:"dynamic-link-not-activated",INVALID_APP_ID:"invalid-app-id",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",WEAK_PASSWORD:"weak-password", OPERATION_NOT_ALLOWED:"operation-not-allowed",USER_CANCELLED:"user-cancelled",CAPTCHA_CHECK_FAILED:"captcha-check-failed",INVALID_APP_CREDENTIAL:"invalid-app-credential",INVALID_CODE:"invalid-verification-code",INVALID_PHONE_NUMBER:"invalid-phone-number",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_APP_CREDENTIAL:"missing-app-credential",MISSING_CODE:"missing-verification-code",MISSING_PHONE_NUMBER:"missing-phone-number",MISSING_SESSION_INFO:"missing-verification-id", QUOTA_EXCEEDED:"quota-exceeded",SESSION_EXPIRED:"code-expired",REJECTED_CREDENTIAL:"rejected-credential",INVALID_CONTINUE_URI:"invalid-continue-uri",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",MISSING_IOS_BUNDLE_ID:"missing-ios-bundle-id",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_DYNAMIC_LINK_DOMAIN:"invalid-dynamic-link-domain",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",INVALID_CERT_HASH:"invalid-cert-hash",UNSUPPORTED_TENANT_OPERATION:"unsupported-tenant-operation", INVALID_TENANT_ID:"invalid-tenant-id",TENANT_ID_MISMATCH:"tenant-id-mismatch",ADMIN_ONLY_OPERATION:"admin-restricted-operation",INVALID_MFA_PENDING_CREDENTIAL:"invalid-multi-factor-session",MFA_ENROLLMENT_NOT_FOUND:"multi-factor-info-not-found",MISSING_MFA_PENDING_CREDENTIAL:"missing-multi-factor-session",MISSING_MFA_ENROLLMENT_ID:"missing-multi-factor-info",EMAIL_CHANGE_NEEDS_VERIFICATION:"email-change-needs-verification",SECOND_FACTOR_EXISTS:"second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"maximum-second-factor-count-exceeded", UNSUPPORTED_FIRST_FACTOR:"unsupported-first-factor",UNVERIFIED_EMAIL:"unverified-email"};B(d,b||{});b=(b=c.match(/^[^\s]+\s*:\s*([\s\S]*)$/))&&1<b.length?b[1]:void 0;for(var e in d)if(0===c.indexOf(e))return new u(d[e],b);!b&&a&&(b=Re(a));return new u("internal-error",b)};function Gj(a){this.b=a;this.a=null;this.nb=Hj(this)} function Hj(a){return Ij().then(function(){return new D(function(b,c){J("gapi.iframes.getContext")().open({where:document.body,url:a.b,messageHandlersFilter:J("gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER"),attributes:{style:{position:"absolute",top:"-100px",width:"1px",height:"1px"}},dontclear:!0},function(d){function e(){clearTimeout(f);b()}a.a=d;a.a.restyle({setHideOnLeave:!1});var f=setTimeout(function(){c(Error("Network Error"))},Jj.get());d.ping(e).then(e,function(){c(Error("Network Error"))})})})})} function Kj(a,b){return a.nb.then(function(){return new D(function(c){a.a.send(b.type,b,c,J("gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER"))})})}function Lj(a,b){a.nb.then(function(){a.a.register("authEvent",b,J("gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER"))})}var Mj=new nb(ob,"https://apis.google.com/js/api.js?onload=%{onload}"),Nj=new We(3E4,6E4),Jj=new We(5E3,15E3),Oj=null; function Ij(){return Oj?Oj:Oj=(new D(function(a,b){function c(){Ve();J("gapi.load")("gapi.iframes",{callback:a,ontimeout:function(){Ve();b(Error("Network Error"))},timeout:Nj.get()})}if(J("gapi.iframes.Iframe"))a();else if(J("gapi.load"))c();else{var d="__iframefcb"+Math.floor(1E6*Math.random()).toString();l[d]=function(){J("gapi.load")?c():b(Error("Network Error"))};d=wb(Mj,{onload:d});E(xi(d)).o(function(){b(Error("Network Error"))})}})).o(function(a){Oj=null;throw a;})};function Pj(a,b,c){this.i=a;this.g=b;this.h=c;this.f=null;this.a=$d(this.i,"/__/auth/iframe");H(this.a,"apiKey",this.g);H(this.a,"appName",this.h);this.b=null;this.c=[]}Pj.prototype.toString=function(){this.f?H(this.a,"v",this.f):fe(this.a.a,"v");this.b?H(this.a,"eid",this.b):fe(this.a.a,"eid");this.c.length?H(this.a,"fw",this.c.join(",")):fe(this.a.a,"fw");return this.a.toString()};function Qj(a,b,c,d,e){this.s=a;this.m=b;this.c=c;this.u=d;this.i=this.g=this.l=null;this.a=e;this.h=this.f=null} Qj.prototype.ub=function(a){this.h=a;return this}; Qj.prototype.toString=function(){var a=$d(this.s,"/__/auth/handler");H(a,"apiKey",this.m);H(a,"appName",this.c);H(a,"authType",this.u);if(this.a.isOAuthProvider){var b=this.a;try{var c=firebase.app(this.c).auth().ja()}catch(h){c=null}b.kb=c;H(a,"providerId",this.a.providerId);b=this.a;c=Se(b.Fb);for(var d in c)c[d]=c[d].toString();d=b.Oc;c=kb(c);for(var e=0;e<d.length;e++){var f=d[e];f in c&&delete c[f]}b.lb&&b.kb&&!c[b.lb]&&(c[b.lb]=b.kb);jb(c)||H(a,"customParameters",Re(c))}"function"===typeof this.a.Nb&& (b=this.a.Nb(),b.length&&H(a,"scopes",b.join(",")));this.l?H(a,"redirectUrl",this.l):fe(a.a,"redirectUrl");this.g?H(a,"eventId",this.g):fe(a.a,"eventId");this.i?H(a,"v",this.i):fe(a.a,"v");if(this.b)for(var g in this.b)this.b.hasOwnProperty(g)&&!Yd(a,g)&&H(a,g,this.b[g]);this.h?H(a,"tid",this.h):fe(a.a,"tid");this.f?H(a,"eid",this.f):fe(a.a,"eid");g=Rj(this.c);g.length&&H(a,"fw",g.join(","));return a.toString()};function Rj(a){try{return firebase.app(a).auth().Ea()}catch(b){return[]}} function Sj(a,b,c,d,e){this.u=a;this.f=b;this.b=c;this.c=d||null;this.h=e||null;this.m=this.s=this.w=null;this.g=[];this.l=this.a=null} function Tj(a){var b=oe();return Xi(a).then(function(c){a:{var d=Zd(b),e=d.f;d=d.b;for(var f=0;f<c.length;f++){var g=c[f];var h=d;var m=e;0==g.indexOf("chrome-extension://")?h=Zd(g).b==h&&"chrome-extension"==m:"http"!=m&&"https"!=m?h=!1:ze.test(g)?h=h==g:(g=g.split(".").join("\\."),h=(new RegExp("^(.+\\."+g+"|"+g+")$","i")).test(h));if(h){c=!0;break a}}c=!1}if(!c)throw new th(oe());})} function Uj(a){if(a.l)return a.l;a.l=Be().then(function(){if(!a.s){var b=a.c,c=a.h,d=Rj(a.b),e=new Pj(a.u,a.f,a.b);e.f=b;e.b=c;e.c=Wa(d||[]);a.s=e.toString()}a.i=new Gj(a.s);Vj(a)});return a.l}k=Sj.prototype;k.Lb=function(a,b,c){var d=new u("popup-closed-by-user"),e=new u("web-storage-unsupported"),f=this,g=!1;return this.ka().then(function(){Wj(f).then(function(h){h||(a&&ve(a),b(e),g=!0)})}).o(function(){}).then(function(){if(!g)return ye(a)}).then(function(){if(!g)return Bd(c).then(function(){b(d)})})}; k.Ub=function(){var a=I();return!Qe(a)&&!Ue(a)};k.Qb=function(){return!1}; k.Jb=function(a,b,c,d,e,f,g,h){if(!a)return F(new u("popup-blocked"));if(g&&!Qe())return this.ka().o(function(p){ve(a);e(p)}),d(),E();this.a||(this.a=Tj(Xj(this)));var m=this;return this.a.then(function(){var p=m.ka().o(function(v){ve(a);e(v);throw v;});d();return p}).then(function(){nh(c);if(!g){var p=Yj(m.u,m.f,m.b,b,c,null,f,m.c,void 0,m.h,h);pe(p,a)}}).o(function(p){"auth/network-request-failed"==p.code&&(m.a=null);throw p;})}; function Xj(a){a.m||(a.w=a.c?Le(a.c,Rj(a.b)):null,a.m=new Ei(a.f,za(a.h),a.w));return a.m}k.Kb=function(a,b,c,d){this.a||(this.a=Tj(Xj(this)));var e=this;return this.a.then(function(){nh(b);var f=Yj(e.u,e.f,e.b,a,b,oe(),c,e.c,void 0,e.h,d);pe(f)}).o(function(f){"auth/network-request-failed"==f.code&&(e.a=null);throw f;})};k.ka=function(){var a=this;return Uj(this).then(function(){return a.i.nb}).o(function(){a.a=null;throw new u("network-request-failed");})};k.Xb=function(){return!0}; function Yj(a,b,c,d,e,f,g,h,m,p,v){a=new Qj(a,b,c,d,e);a.l=f;a.g=g;a.i=h;a.b=kb(m||null);a.f=p;return a.ub(v).toString()}function Vj(a){if(!a.i)throw Error("IfcHandler must be initialized!");Lj(a.i,function(b){var c={};if(b&&b.authEvent){var d=!1;b=ph(b.authEvent);for(c=0;c<a.g.length;c++)d=a.g[c](b)||d;c={};c.status=d?"ACK":"ERROR";return E(c)}c.status="ERROR";return E(c)})} function Wj(a){var b={type:"webStorageSupport"};return Uj(a).then(function(){return Kj(a.i,b)}).then(function(c){if(c&&c.length&&"undefined"!==typeof c[0].webStorageSupport)return c[0].webStorageSupport;throw Error();})}k.Ca=function(a){this.g.push(a)};k.Qa=function(a){Ua(this.g,function(b){return b==a})};function Zj(a){this.a=a||firebase.INTERNAL.reactNative&&firebase.INTERNAL.reactNative.AsyncStorage;if(!this.a)throw new u("internal-error","The React Native compatibility library was not found.");this.type="asyncStorage"}k=Zj.prototype;k.get=function(a){return E(this.a.getItem(a)).then(function(b){return b&&Te(b)})};k.set=function(a,b){return E(this.a.setItem(a,Re(b)))};k.T=function(a){return E(this.a.removeItem(a))};k.ba=function(){};k.ha=function(){};function ak(a){this.b=a;this.a={};this.f=r(this.c,this)}var bk=[];function ck(){var a=Ge()?self:null;x(bk,function(c){c.b==a&&(b=c)});if(!b){var b=new ak(a);bk.push(b)}return b} ak.prototype.c=function(a){var b=a.data.eventType,c=a.data.eventId,d=this.a[b];if(d&&0<d.length){a.ports[0].postMessage({status:"ack",eventId:c,eventType:b,response:null});var e=[];x(d,function(f){e.push(E().then(function(){return f(a.origin,a.data.data)}))});Ec(e).then(function(f){var g=[];x(f,function(h){g.push({fulfilled:h.Mb,value:h.value,reason:h.reason?h.reason.message:void 0})});x(g,function(h){for(var m in h)"undefined"===typeof h[m]&&delete h[m]});a.ports[0].postMessage({status:"done",eventId:c, eventType:b,response:g})})}};function dk(a,b,c){jb(a.a)&&a.b.addEventListener("message",a.f);"undefined"===typeof a.a[b]&&(a.a[b]=[]);a.a[b].push(c)};function ek(a){this.a=a}ek.prototype.postMessage=function(a,b){this.a.postMessage(a,b)};function fk(a){this.c=a;this.b=!1;this.a=[]} function gk(a,b,c,d){var e,f=c||{},g,h,m,p=null;if(a.b)return F(Error("connection_unavailable"));var v=d?800:50,C="undefined"!==typeof MessageChannel?new MessageChannel:null;return(new D(function(A,Q){C?(e=Math.floor(Math.random()*Math.pow(10,20)).toString(),C.port1.start(),h=setTimeout(function(){Q(Error("unsupported_event"))},v),g=function(xa){xa.data.eventId===e&&("ack"===xa.data.status?(clearTimeout(h),m=setTimeout(function(){Q(Error("timeout"))},3E3)):"done"===xa.data.status?(clearTimeout(m), "undefined"!==typeof xa.data.response?A(xa.data.response):Q(Error("unknown_error"))):(clearTimeout(h),clearTimeout(m),Q(Error("invalid_response"))))},p={messageChannel:C,onMessage:g},a.a.push(p),C.port1.addEventListener("message",g),a.c.postMessage({eventType:b,eventId:e,data:f},[C.port2])):Q(Error("connection_unavailable"))})).then(function(A){hk(a,p);return A}).o(function(A){hk(a,p);throw A;})} function hk(a,b){if(b){var c=b.messageChannel,d=b.onMessage;c&&(c.port1.removeEventListener("message",d),c.port1.close());Ua(a.a,function(e){return e==b})}}fk.prototype.close=function(){for(;0<this.a.length;)hk(this,this.a[0]);this.b=!0};function ik(){if(!jk())throw new u("web-storage-unsupported");this.c={};this.a=[];this.b=0;this.u=l.indexedDB;this.type="indexedDB";this.g=this.l=this.f=this.i=null;this.s=!1;this.h=null;var a=this;Ge()&&self?(this.l=ck(),dk(this.l,"keyChanged",function(b,c){return kk(a).then(function(d){0<d.length&&x(a.a,function(e){e(d)});return{keyProcessed:Sa(d,c.key)}})}),dk(this.l,"ping",function(){return E(["keyChanged"])})):bf().then(function(b){if(a.h=b)a.g=new fk(new ek(b)),gk(a.g,"ping",null,!0).then(function(c){c[0].fulfilled&& Sa(c[0].value,"keyChanged")&&(a.s=!0)}).o(function(){})})}var lk;function mk(a){return new D(function(b,c){var d=a.u.deleteDatabase("firebaseLocalStorageDb");d.onsuccess=function(){b()};d.onerror=function(e){c(Error(e.target.error))}})} function nk(a){return new D(function(b,c){var d=a.u.open("firebaseLocalStorageDb",1);d.onerror=function(e){try{e.preventDefault()}catch(f){}c(Error(e.target.error))};d.onupgradeneeded=function(e){e=e.target.result;try{e.createObjectStore("firebaseLocalStorage",{keyPath:"fbase_key"})}catch(f){c(f)}};d.onsuccess=function(e){e=e.target.result;e.objectStoreNames.contains("firebaseLocalStorage")?b(e):mk(a).then(function(){return nk(a)}).then(function(f){b(f)}).o(function(f){c(f)})}})} function ok(a){a.m||(a.m=nk(a));return a.m}function jk(){try{return!!l.indexedDB}catch(a){return!1}}function pk(a){return a.objectStore("firebaseLocalStorage")}function qk(a,b){return a.transaction(["firebaseLocalStorage"],b?"readwrite":"readonly")}function rk(a){return new D(function(b,c){a.onsuccess=function(d){d&&d.target?b(d.target.result):b()};a.onerror=function(d){c(d.target.error)}})}k=ik.prototype; k.set=function(a,b){var c=!1,d,e=this;return ok(this).then(function(f){d=f;f=pk(qk(d,!0));return rk(f.get(a))}).then(function(f){var g=pk(qk(d,!0));if(f)return f.value=b,rk(g.put(f));e.b++;c=!0;f={};f.fbase_key=a;f.value=b;return rk(g.add(f))}).then(function(){e.c[a]=b;return sk(e,a)}).ma(function(){c&&e.b--})};function sk(a,b){return a.g&&a.h&&af()===a.h?gk(a.g,"keyChanged",{key:b},a.s).then(function(){}).o(function(){}):E()} k.get=function(a){return ok(this).then(function(b){return rk(pk(qk(b,!1)).get(a))}).then(function(b){return b&&b.value})};k.T=function(a){var b=!1,c=this;return ok(this).then(function(d){b=!0;c.b++;return rk(pk(qk(d,!0))["delete"](a))}).then(function(){delete c.c[a];return sk(c,a)}).ma(function(){b&&c.b--})}; function kk(a){return ok(a).then(function(b){var c=pk(qk(b,!1));return c.getAll?rk(c.getAll()):new D(function(d,e){var f=[],g=c.openCursor();g.onsuccess=function(h){(h=h.target.result)?(f.push(h.value),h["continue"]()):d(f)};g.onerror=function(h){e(h.target.error)}})}).then(function(b){var c={},d=[];if(0==a.b){for(d=0;d<b.length;d++)c[b[d].fbase_key]=b[d].value;d=qe(a.c,c);a.c=c}return d})}k.ba=function(a){0==this.a.length&&tk(this);this.a.push(a)}; k.ha=function(a){Ua(this.a,function(b){return b==a});0==this.a.length&&uk(this)};function tk(a){function b(){a.f=setTimeout(function(){a.i=kk(a).then(function(c){0<c.length&&x(a.a,function(d){d(c)})}).then(function(){b()}).o(function(c){"STOP_EVENT"!=c.message&&b()})},800)}uk(a);b()}function uk(a){a.i&&a.i.cancel("STOP_EVENT");a.f&&(clearTimeout(a.f),a.f=null)};function vk(a){var b=this,c=null;this.a=[];this.type="indexedDB";this.c=a;this.b=E().then(function(){if(jk()){var d=Ne(),e="__sak"+d;lk||(lk=new ik);c=lk;return c.set(e,d).then(function(){return c.get(e)}).then(function(f){if(f!==d)throw Error("indexedDB not supported!");return c.T(e)}).then(function(){return c}).o(function(){return b.c})}return b.c}).then(function(d){b.type=d.type;d.ba(function(e){x(b.a,function(f){f(e)})});return d})}k=vk.prototype;k.get=function(a){return this.b.then(function(b){return b.get(a)})}; k.set=function(a,b){return this.b.then(function(c){return c.set(a,b)})};k.T=function(a){return this.b.then(function(b){return b.T(a)})};k.ba=function(a){this.a.push(a)};k.ha=function(a){Ua(this.a,function(b){return b==a})};function wk(){this.a={};this.type="inMemory"}k=wk.prototype;k.get=function(a){return E(this.a[a])};k.set=function(a,b){this.a[a]=b;return E()};k.T=function(a){delete this.a[a];return E()};k.ba=function(){};k.ha=function(){};function xk(){if(!yk()){if("Node"==He())throw new u("internal-error","The LocalStorage compatibility library was not found.");throw new u("web-storage-unsupported");}this.a=zk()||firebase.INTERNAL.node.localStorage;this.type="localStorage"}function zk(){try{var a=l.localStorage,b=Ne();a&&(a.setItem(b,"1"),a.removeItem(b));return a}catch(c){return null}} function yk(){var a="Node"==He();a=zk()||a&&firebase.INTERNAL.node&&firebase.INTERNAL.node.localStorage;if(!a)return!1;try{return a.setItem("__sak","1"),a.removeItem("__sak"),!0}catch(b){return!1}}k=xk.prototype;k.get=function(a){var b=this;return E().then(function(){var c=b.a.getItem(a);return Te(c)})};k.set=function(a,b){var c=this;return E().then(function(){var d=Re(b);null===d?c.T(a):c.a.setItem(a,d)})};k.T=function(a){var b=this;return E().then(function(){b.a.removeItem(a)})}; k.ba=function(a){l.window&&jd(l.window,"storage",a)};k.ha=function(a){l.window&&td(l.window,"storage",a)};function Ak(){this.type="nullStorage"}k=Ak.prototype;k.get=function(){return E(null)};k.set=function(){return E()};k.T=function(){return E()};k.ba=function(){};k.ha=function(){};function Bk(){if(!Ck()){if("Node"==He())throw new u("internal-error","The SessionStorage compatibility library was not found.");throw new u("web-storage-unsupported");}this.a=Dk()||firebase.INTERNAL.node.sessionStorage;this.type="sessionStorage"}function Dk(){try{var a=l.sessionStorage,b=Ne();a&&(a.setItem(b,"1"),a.removeItem(b));return a}catch(c){return null}} function Ck(){var a="Node"==He();a=Dk()||a&&firebase.INTERNAL.node&&firebase.INTERNAL.node.sessionStorage;if(!a)return!1;try{return a.setItem("__sak","1"),a.removeItem("__sak"),!0}catch(b){return!1}}k=Bk.prototype;k.get=function(a){var b=this;return E().then(function(){var c=b.a.getItem(a);return Te(c)})};k.set=function(a,b){var c=this;return E().then(function(){var d=Re(b);null===d?c.T(a):c.a.setItem(a,d)})};k.T=function(a){var b=this;return E().then(function(){b.a.removeItem(a)})};k.ba=function(){}; k.ha=function(){};function Ek(){var a={};a.Browser=Fk;a.Node=Gk;a.ReactNative=Hk;a.Worker=Ik;this.a=a[He()]}var Jk,Fk={F:xk,$a:Bk},Gk={F:xk,$a:Bk},Hk={F:Zj,$a:Ak},Ik={F:xk,$a:Ak};var Kk={od:"local",NONE:"none",qd:"session"};function Lk(a){var b=new u("invalid-persistence-type"),c=new u("unsupported-persistence-type");a:{for(d in Kk)if(Kk[d]==a){var d=!0;break a}d=!1}if(!d||"string"!==typeof a)throw b;switch(He()){case "ReactNative":if("session"===a)throw c;break;case "Node":if("none"!==a)throw c;break;default:if(!Me()&&"none"!==a)throw c;}} function Mk(){var a=!Ue(I())&&Fe()?!0:!1,b=Qe(),c=Me();this.m=a;this.h=b;this.l=c;this.a={};Jk||(Jk=new Ek);a=Jk;try{this.g=!ne()&&$e()||!l.indexedDB?new a.a.F:new vk(Ge()?new wk:new a.a.F)}catch(d){this.g=new wk,this.h=!0}try{this.i=new a.a.$a}catch(d){this.i=new wk}this.u=new wk;this.f=r(this.Vb,this);this.b={}}var Nk;function Ok(){Nk||(Nk=new Mk);return Nk}function Pk(a,b){switch(b){case "session":return a.i;case "none":return a.u;default:return a.g}} function Qk(a,b){return"firebase:"+a.name+(b?":"+b:"")}function Rk(a,b,c){var d=Qk(b,c),e=Pk(a,b.F);return a.get(b,c).then(function(f){var g=null;try{g=Te(l.localStorage.getItem(d))}catch(h){}if(g&&!f)return l.localStorage.removeItem(d),a.set(b,g,c);g&&f&&"localStorage"!=e.type&&l.localStorage.removeItem(d)})}k=Mk.prototype;k.get=function(a,b){return Pk(this,a.F).get(Qk(a,b))};function Sk(a,b,c){c=Qk(b,c);"local"==b.F&&(a.b[c]=null);return Pk(a,b.F).T(c)} k.set=function(a,b,c){var d=Qk(a,c),e=this,f=Pk(this,a.F);return f.set(d,b).then(function(){return f.get(d)}).then(function(g){"local"==a.F&&(e.b[d]=g)})};k.addListener=function(a,b,c){a=Qk(a,b);this.l&&(this.b[a]=l.localStorage.getItem(a));jb(this.a)&&(Pk(this,"local").ba(this.f),this.h||(ne()||!$e())&&l.indexedDB||!this.l||Tk(this));this.a[a]||(this.a[a]=[]);this.a[a].push(c)}; k.removeListener=function(a,b,c){a=Qk(a,b);this.a[a]&&(Ua(this.a[a],function(d){return d==c}),0==this.a[a].length&&delete this.a[a]);jb(this.a)&&(Pk(this,"local").ha(this.f),Uk(this))};function Tk(a){Uk(a);a.c=setInterval(function(){for(var b in a.a){var c=l.localStorage.getItem(b),d=a.b[b];c!=d&&(a.b[b]=c,c=new Yc({type:"storage",key:b,target:window,oldValue:d,newValue:c,a:!0}),a.Vb(c))}},1E3)}function Uk(a){a.c&&(clearInterval(a.c),a.c=null)} k.Vb=function(a){if(a&&a.f){var b=a.a.key;if(null==b)for(var c in this.a){var d=this.b[c];"undefined"===typeof d&&(d=null);var e=l.localStorage.getItem(c);e!==d&&(this.b[c]=e,this.ib(c))}else if(0==b.indexOf("firebase:")&&this.a[b]){"undefined"!==typeof a.a.a?Pk(this,"local").ha(this.f):Uk(this);if(this.m)if(c=l.localStorage.getItem(b),d=a.a.newValue,d!==c)null!==d?l.localStorage.setItem(b,d):l.localStorage.removeItem(b);else if(this.b[b]===d&&"undefined"===typeof a.a.a)return;var f=this;c=function(){if("undefined"!== typeof a.a.a||f.b[b]!==l.localStorage.getItem(b))f.b[b]=l.localStorage.getItem(b),f.ib(b)};Sb&&cc&&10==cc&&l.localStorage.getItem(b)!==a.a.newValue&&a.a.newValue!==a.a.oldValue?setTimeout(c,10):c()}}else x(a,r(this.ib,this))};k.ib=function(a){this.a[a]&&x(this.a[a],function(b){b()})};function Vk(a){this.a=a;this.b=Ok()}var Wk={name:"authEvent",F:"local"};function Xk(a){return a.b.get(Wk,a.a).then(function(b){return ph(b)})};function Yk(){this.a=Ok()};function Zk(){this.b=-1};function $k(a,b){this.b=al;this.f=l.Uint8Array?new Uint8Array(this.b):Array(this.b);this.g=this.c=0;this.a=[];this.i=a;this.h=b;this.l=l.Int32Array?new Int32Array(64):Array(64);void 0===bl&&(l.Int32Array?bl=new Int32Array(cl):bl=cl);this.reset()}var bl;t($k,Zk);for(var al=64,dl=al-1,el=[],fl=0;fl<dl;fl++)el[fl]=0;var gl=Va(128,el);$k.prototype.reset=function(){this.g=this.c=0;this.a=l.Int32Array?new Int32Array(this.h):Wa(this.h)}; function hl(a){for(var b=a.f,c=a.l,d=0,e=0;e<b.length;)c[d++]=b[e]<<24|b[e+1]<<16|b[e+2]<<8|b[e+3],e=4*d;for(b=16;64>b;b++){e=c[b-15]|0;d=c[b-2]|0;var f=(c[b-16]|0)+((e>>>7|e<<25)^(e>>>18|e<<14)^e>>>3)|0,g=(c[b-7]|0)+((d>>>17|d<<15)^(d>>>19|d<<13)^d>>>10)|0;c[b]=f+g|0}d=a.a[0]|0;e=a.a[1]|0;var h=a.a[2]|0,m=a.a[3]|0,p=a.a[4]|0,v=a.a[5]|0,C=a.a[6]|0;f=a.a[7]|0;for(b=0;64>b;b++){var A=((d>>>2|d<<30)^(d>>>13|d<<19)^(d>>>22|d<<10))+(d&e^d&h^e&h)|0;g=p&v^~p&C;f=f+((p>>>6|p<<26)^(p>>>11|p<<21)^(p>>>25|p<< 7))|0;g=g+(bl[b]|0)|0;g=f+(g+(c[b]|0)|0)|0;f=C;C=v;v=p;p=m+g|0;m=h;h=e;e=d;d=g+A|0}a.a[0]=a.a[0]+d|0;a.a[1]=a.a[1]+e|0;a.a[2]=a.a[2]+h|0;a.a[3]=a.a[3]+m|0;a.a[4]=a.a[4]+p|0;a.a[5]=a.a[5]+v|0;a.a[6]=a.a[6]+C|0;a.a[7]=a.a[7]+f|0} function il(a,b,c){void 0===c&&(c=b.length);var d=0,e=a.c;if("string"===typeof b)for(;d<c;)a.f[e++]=b.charCodeAt(d++),e==a.b&&(hl(a),e=0);else if(ma(b))for(;d<c;){var f=b[d++];if(!("number"==typeof f&&0<=f&&255>=f&&f==(f|0)))throw Error("message must be a byte array");a.f[e++]=f;e==a.b&&(hl(a),e=0)}else throw Error("message must be string or array");a.c=e;a.g+=c} var cl=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804, 4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function jl(){$k.call(this,8,kl)}t(jl,$k);var kl=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];function ll(a,b,c,d,e){this.u=a;this.i=b;this.l=c;this.m=d||null;this.s=e||null;this.h=b+":"+c;this.w=new Yk;this.g=new Vk(this.h);this.f=null;this.b=[];this.a=this.c=null}function ml(a){return new u("invalid-cordova-configuration",a)}k=ll.prototype; k.ka=function(){return this.Ga?this.Ga:this.Ga=Ce().then(function(){if("function"!==typeof J("universalLinks.subscribe",l))throw ml("cordova-universal-links-plugin-fix is not installed");if("undefined"===typeof J("BuildInfo.packageName",l))throw ml("cordova-plugin-buildinfo is not installed");if("function"!==typeof J("cordova.plugins.browsertab.openUrl",l))throw ml("cordova-plugin-browsertab is not installed");if("function"!==typeof J("cordova.InAppBrowser.open",l))throw ml("cordova-plugin-inappbrowser is not installed"); },function(){throw new u("cordova-not-ready");})};function nl(){for(var a=20,b=[];0<a;)b.push("1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(Math.floor(62*Math.random()))),a--;return b.join("")}function ol(a){var b=new jl;il(b,a);a=[];var c=8*b.g;56>b.c?il(b,gl,56-b.c):il(b,gl,b.b-(b.c-56));for(var d=63;56<=d;d--)b.f[d]=c&255,c/=256;hl(b);for(d=c=0;d<b.i;d++)for(var e=24;0<=e;e-=8)a[c++]=b.a[d]>>e&255;return $f(a)} k.Lb=function(a,b){b(new u("operation-not-supported-in-this-environment"));return E()};k.Jb=function(){return F(new u("operation-not-supported-in-this-environment"))};k.Xb=function(){return!1};k.Ub=function(){return!0};k.Qb=function(){return!0}; k.Kb=function(a,b,c,d){if(this.c)return F(new u("redirect-operation-pending"));var e=this,f=l.document,g=null,h=null,m=null,p=null;return this.c=E().then(function(){nh(b);return pl(e)}).then(function(){return ql(e,a,b,c,d)}).then(function(){return(new D(function(v,C){h=function(){var A=J("cordova.plugins.browsertab.close",l);v();"function"===typeof A&&A();e.a&&"function"===typeof e.a.close&&(e.a.close(),e.a=null);return!1};e.Ca(h);m=function(){g||(g=Bd(2E3).then(function(){C(new u("redirect-cancelled-by-user"))}))}; p=function(){Xe()&&m()};f.addEventListener("resume",m,!1);I().toLowerCase().match(/android/)||f.addEventListener("visibilitychange",p,!1)})).o(function(v){return rl(e).then(function(){throw v;})})}).ma(function(){m&&f.removeEventListener("resume",m,!1);p&&f.removeEventListener("visibilitychange",p,!1);g&&g.cancel();h&&e.Qa(h);e.c=null})}; function ql(a,b,c,d,e){var f=nl(),g=new oh(b,d,null,f,new u("no-auth-event"),null,e),h=J("BuildInfo.packageName",l);if("string"!==typeof h)throw new u("invalid-cordova-configuration");var m=J("BuildInfo.displayName",l),p={};if(I().toLowerCase().match(/iphone|ipad|ipod/))p.ibi=h;else if(I().toLowerCase().match(/android/))p.apn=h;else return F(new u("operation-not-supported-in-this-environment"));m&&(p.appDisplayName=m);f=ol(f);p.sessionId=f;var v=Yj(a.u,a.i,a.l,b,c,null,d,a.m,p,a.s,e);return a.ka().then(function(){var C= a.h;return a.w.a.set(Wk,g.v(),C)}).then(function(){var C=J("cordova.plugins.browsertab.isAvailable",l);if("function"!==typeof C)throw new u("invalid-cordova-configuration");var A=null;C(function(Q){if(Q){A=J("cordova.plugins.browsertab.openUrl",l);if("function"!==typeof A)throw new u("invalid-cordova-configuration");A(v)}else{A=J("cordova.InAppBrowser.open",l);if("function"!==typeof A)throw new u("invalid-cordova-configuration");Q=I();a.a=A(v,Q.match(/(iPad|iPhone|iPod).*OS 7_\d/i)||Q.match(/(iPad|iPhone|iPod).*OS 8_\d/i)? "_blank":"_system","location=yes")}})})}function sl(a,b){for(var c=0;c<a.b.length;c++)try{a.b[c](b)}catch(d){}}function pl(a){a.f||(a.f=a.ka().then(function(){return new D(function(b){function c(d){b(d);a.Qa(c);return!1}a.Ca(c);tl(a)})}));return a.f}function rl(a){var b=null;return Xk(a.g).then(function(c){b=c;c=a.g;return Sk(c.b,Wk,c.a)}).then(function(){return b})} function tl(a){function b(g){d=!0;e&&e.cancel();rl(a).then(function(h){var m=c;if(h&&g&&g.url){var p=null;m=ug(g.url);-1!=m.indexOf("/__/auth/callback")&&(p=Zd(m),p=Te(Yd(p,"firebaseError")||null),p=(p="object"===typeof p?wa(p):null)?new oh(h.c,h.b,null,null,p,null,h.S()):new oh(h.c,h.b,m,h.f,null,null,h.S()));m=p||c}sl(a,m)})}var c=new oh("unknown",null,null,null,new u("no-auth-event")),d=!1,e=Bd(500).then(function(){return rl(a).then(function(){d||sl(a,c)})}),f=l.handleOpenURL;l.handleOpenURL=function(g){0== g.toLowerCase().indexOf(J("BuildInfo.packageName",l).toLowerCase()+"://")&&b({url:g});if("function"===typeof f)try{f(g)}catch(h){console.error(h)}};rh||(rh=new qh);sh(b)}k.Ca=function(a){this.b.push(a);pl(this).o(function(b){"auth/invalid-cordova-configuration"===b.code&&(b=new oh("unknown",null,null,null,new u("no-auth-event")),a(b))})};k.Qa=function(a){Ua(this.b,function(b){return b==a})};function ul(a){this.a=a;this.b=Ok()}var vl={name:"pendingRedirect",F:"session"};function wl(a){return a.b.set(vl,"pending",a.a)}function xl(a){return Sk(a.b,vl,a.a)}function yl(a){return a.b.get(vl,a.a).then(function(b){return"pending"==b})};function zl(a,b,c){this.i={};this.w=0;this.D=a;this.u=b;this.m=c;this.h=[];this.f=!1;this.l=r(this.s,this);this.b=new Al;this.B=new Bl;this.g=new ul(this.u+":"+this.m);this.c={};this.c.unknown=this.b;this.c.signInViaRedirect=this.b;this.c.linkViaRedirect=this.b;this.c.reauthViaRedirect=this.b;this.c.signInViaPopup=this.B;this.c.linkViaPopup=this.B;this.c.reauthViaPopup=this.B;this.a=Cl(this.D,this.u,this.m,Aa)} function Cl(a,b,c,d){var e=firebase.SDK_VERSION||null;return De()?new ll(a,b,c,e,d):new Sj(a,b,c,e,d)}zl.prototype.reset=function(){this.f=!1;this.a.Qa(this.l);this.a=Cl(this.D,this.u,this.m);this.i={}};function Dl(a){a.f||(a.f=!0,a.a.Ca(a.l));var b=a.a;return a.a.ka().o(function(c){a.a==b&&a.reset();throw c;})}function El(a){a.a.Ub()&&Dl(a).o(function(b){var c=new oh("unknown",null,null,null,new u("operation-not-supported-in-this-environment"));Fl(b)&&a.s(c)});a.a.Qb()||Gl(a.b)} function Hl(a,b){Sa(a.h,b)||a.h.push(b);a.f||yl(a.g).then(function(c){c?xl(a.g).then(function(){Dl(a).o(function(d){var e=new oh("unknown",null,null,null,new u("operation-not-supported-in-this-environment"));Fl(d)&&a.s(e)})}):El(a)}).o(function(){El(a)})}function Il(a,b){Ua(a.h,function(c){return c==b})} zl.prototype.s=function(a){if(!a)throw new u("invalid-auth-event");6E5<=ta()-this.w&&(this.i={},this.w=0);if(a&&a.getUid()&&this.i.hasOwnProperty(a.getUid()))return!1;for(var b=!1,c=0;c<this.h.length;c++){var d=this.h[c];if(d.Cb(a.c,a.b)){if(b=this.c[a.c])b.h(a,d),a&&(a.f||a.b)&&(this.i[a.getUid()]=!0,this.w=ta());b=!0;break}}Gl(this.b);return b};var Jl=new We(2E3,1E4),Kl=new We(3E4,6E4);zl.prototype.pa=function(){return this.b.pa()}; function Ll(a,b,c,d,e,f,g){return a.a.Jb(b,c,d,function(){a.f||(a.f=!0,a.a.Ca(a.l))},function(){a.reset()},e,f,g)}function Fl(a){return a&&"auth/cordova-not-ready"==a.code?!0:!1} function Ml(a,b,c,d,e){var f;return wl(a.g).then(function(){return a.a.Kb(b,c,d,e).o(function(g){if(Fl(g))throw new u("operation-not-supported-in-this-environment");f=g;return xl(a.g).then(function(){throw f;})}).then(function(){return a.a.Xb()?new D(function(){}):xl(a.g).then(function(){return a.pa()}).then(function(){}).o(function(){})})})}function Nl(a,b,c,d,e){return a.a.Lb(d,function(f){b.la(c,null,f,e)},Jl.get())}var Ol={}; function Pl(a,b,c){var d=b+":"+c;Ol[d]||(Ol[d]=new zl(a,b,c));return Ol[d]}function Al(){this.b=null;this.f=[];this.c=[];this.a=null;this.i=this.g=!1}Al.prototype.reset=function(){this.b=null;this.a&&(this.a.cancel(),this.a=null)}; Al.prototype.h=function(a,b){if(a){this.reset();this.g=!0;var c=a.c,d=a.b,e=a.a&&"auth/web-storage-unsupported"==a.a.code,f=a.a&&"auth/operation-not-supported-in-this-environment"==a.a.code;this.i=!(!e&&!f);"unknown"!=c||e||f?a.a?(Ql(this,!0,null,a.a),E()):b.Da(c,d)?Rl(this,a,b):F(new u("invalid-auth-event")):(Ql(this,!1,null,null),E())}else F(new u("invalid-auth-event"))};function Gl(a){a.g||(a.g=!0,Ql(a,!1,null,null))}function Sl(a){a.g&&!a.i&&Ql(a,!1,null,null)} function Rl(a,b,c){c=c.Da(b.c,b.b);var d=b.g,e=b.f,f=b.i,g=b.S(),h=!!b.c.match(/Redirect$/);c(d,e,g,f).then(function(m){Ql(a,h,m,null)}).o(function(m){Ql(a,h,null,m)})}function Tl(a,b){a.b=function(){return F(b)};if(a.c.length)for(var c=0;c<a.c.length;c++)a.c[c](b)}function Ul(a,b){a.b=function(){return E(b)};if(a.f.length)for(var c=0;c<a.f.length;c++)a.f[c](b)}function Ql(a,b,c,d){b?d?Tl(a,d):Ul(a,c):Ul(a,{user:null});a.f=[];a.c=[]} Al.prototype.pa=function(){var a=this;return new D(function(b,c){a.b?a.b().then(b,c):(a.f.push(b),a.c.push(c),Vl(a))})};function Vl(a){var b=new u("timeout");a.a&&a.a.cancel();a.a=Bd(Kl.get()).then(function(){a.b||(a.g=!0,Ql(a,!0,null,b))})}function Bl(){}Bl.prototype.h=function(a,b){if(a){var c=a.c,d=a.b;a.a?(b.la(a.c,null,a.a,a.b),E()):b.Da(c,d)?Wl(a,b):F(new u("invalid-auth-event"))}else F(new u("invalid-auth-event"))}; function Wl(a,b){var c=a.b,d=a.c;b.Da(d,c)(a.g,a.f,a.S(),a.i).then(function(e){b.la(d,e,null,c)}).o(function(e){b.la(d,null,e,c)})};function Xl(){this.Bb=!1;Object.defineProperty(this,"appVerificationDisabled",{get:function(){return this.Bb},set:function(a){this.Bb=a},enumerable:!1})};function Yl(a,b){this.a=b;K(this,"verificationId",a)}Yl.prototype.confirm=function(a){a=lh(this.verificationId,a);return this.a(a)};function Zl(a,b,c,d){return(new hh(a)).cb(b,c).then(function(e){return new Yl(e,d)})};function $l(a){var b=fg(a);if(!(b&&b.exp&&b.auth_time&&b.iat))throw new u("internal-error","An internal error occurred. The token obtained by Firebase appears to be malformed. Please retry the operation.");L(this,{token:a,expirationTime:Ze(1E3*b.exp),authTime:Ze(1E3*b.auth_time),issuedAtTime:Ze(1E3*b.iat),signInProvider:b.firebase&&b.firebase.sign_in_provider?b.firebase.sign_in_provider:null,signInSecondFactor:b.firebase&&b.firebase.sign_in_second_factor?b.firebase.sign_in_second_factor:null,claims:b})} ;function am(a,b,c){var d=b&&b[bm];if(!d)throw new u("argument-error","Internal assert: Invalid MultiFactorResolver");this.a=a;this.f=kb(b);this.g=c;this.c=new vg(null,d);this.b=[];var e=this;x(b[cm]||[],function(f){(f=qf(f))&&e.b.push(f)});K(this,"auth",this.a);K(this,"session",this.c);K(this,"hints",this.b)}var cm="mfaInfo",bm="mfaPendingCredential";am.prototype.Pc=function(a){var b=this;return a.ob(this.a.b,this.c).then(function(c){var d=kb(b.f);delete d[cm];delete d[bm];B(d,c);return b.g(d)})};function dm(a,b,c,d){u.call(this,"multi-factor-auth-required",d,b);this.b=new am(a,b,c);K(this,"resolver",this.b)}t(dm,u);function em(a,b,c){if(a&&q(a.serverResponse)&&"auth/multi-factor-auth-required"===a.code)try{return new dm(b,a.serverResponse,c,a.message)}catch(d){}return null};function fm(){}fm.prototype.ob=function(a,b,c){return b.type==wg?gm(this,a,b,c):hm(this,a,b)};function gm(a,b,c,d){return c.Fa().then(function(e){e={idToken:e};"undefined"!==typeof d&&(e.displayName=d);B(e,{phoneVerificationInfo:dh(a.a)});return N(b,Aj,e)})}function hm(a,b,c){return c.Fa().then(function(d){d={mfaPendingCredential:d};B(d,{phoneVerificationInfo:dh(a.a)});return N(b,Bj,d)})}function im(a){K(this,"factorId",a.ea);this.a=a}t(im,fm); function jm(a){im.call(this,a);if(this.a.ea!=hh.PROVIDER_ID)throw new u("argument-error","firebase.auth.PhoneMultiFactorAssertion requires a valid firebase.auth.PhoneAuthCredential");}t(jm,im);function km(a,b){Xc.call(this,a);for(var c in b)this[c]=b[c]}t(km,Xc);function lm(a,b){this.a=a;this.b=[];this.c=r(this.wc,this);jd(this.a,"userReloaded",this.c);var c=[];b&&b.multiFactor&&b.multiFactor.enrolledFactors&&x(b.multiFactor.enrolledFactors,function(d){var e=null,f={};if(d){d.uid&&(f[nf]=d.uid);d.displayName&&(f[of]=d.displayName);d.enrollmentTime&&(f[pf]=(new Date(d.enrollmentTime)).toISOString());d.phoneNumber&&(f[mf]=d.phoneNumber);try{e=new rf(f)}catch(g){}d=e}else d=null;d&&c.push(d)});mm(this,c)} function nm(a){var b=[];x(a.mfaInfo||[],function(c){(c=qf(c))&&b.push(c)});return b}k=lm.prototype;k.wc=function(a){mm(this,nm(a.ed))};function mm(a,b){a.b=b;K(a,"enrolledFactors",b)}k.Ob=function(){return this.a.I().then(function(a){return new vg(a,null)})};k.dc=function(a,b){var c=this,d=this.a.a;return this.Ob().then(function(e){return a.ob(d,e,b)}).then(function(e){om(c.a,e);return c.a.reload()})}; k.$c=function(a){var b=this,c="string"===typeof a?a:a.uid,d=this.a.a;return this.a.I().then(function(e){return N(d,Fj,{idToken:e,mfaEnrollmentId:c})}).then(function(e){var f=Na(b.b,function(g){return g.uid!=c});mm(b,f);om(b.a,e);return b.a.reload().o(function(g){if("auth/user-token-expired"!=g.code)throw g;})})};k.v=function(){return{multiFactor:{enrolledFactors:Oa(this.b,function(a){return a.v()})}}};function pm(a,b,c){this.h=a;this.i=b;this.g=c;this.c=3E4;this.f=96E4;this.b=null;this.a=this.c;if(this.f<this.c)throw Error("Proactive refresh lower bound greater than upper bound!");}pm.prototype.start=function(){this.a=this.c;qm(this,!0)};function rm(a,b){if(b)return a.a=a.c,a.g();b=a.a;a.a*=2;a.a>a.f&&(a.a=a.f);return b}function qm(a,b){a.stop();a.b=Bd(rm(a,b)).then(function(){return Ye()}).then(function(){return a.h()}).then(function(){qm(a,!0)}).o(function(c){a.i(c)&&qm(a,!1)})} pm.prototype.stop=function(){this.b&&(this.b.cancel(),this.b=null)};function sm(a){this.c=a;this.b=this.a=null}sm.prototype.v=function(){return{apiKey:this.c.c,refreshToken:this.a,accessToken:this.b&&this.b.toString(),expirationTime:tm(this)}};function tm(a){return a.b&&1E3*a.b.c||0}function um(a,b){var c=b.refreshToken;a.b=gg(b[Ag]||"");a.a=c}function vm(a,b){a.b=b.b;a.a=b.a} function wm(a,b){return Qi(a.c,b).then(function(c){a.b=gg(c.access_token);a.a=c.refresh_token;return{accessToken:a.b.toString(),refreshToken:a.a}}).o(function(c){"auth/user-token-expired"==c.code&&(a.a=null);throw c;})}sm.prototype.getToken=function(a){a=!!a;return this.b&&!this.a?F(new u("user-token-expired")):a||!this.b||ta()>tm(this)-3E4?this.a?wm(this,{grant_type:"refresh_token",refresh_token:this.a}):E(null):E({accessToken:this.b.toString(),refreshToken:this.a})};function xm(a,b){this.a=a||null;this.b=b||null;L(this,{lastSignInTime:Ze(b||null),creationTime:Ze(a||null)})}function ym(a){return new xm(a.a,a.b)}xm.prototype.v=function(){return{lastLoginAt:this.b,createdAt:this.a}};function zm(a,b,c,d,e,f){L(this,{uid:a,displayName:d||null,photoURL:e||null,email:c||null,phoneNumber:f||null,providerId:b})} function P(a,b,c){this.N=[];this.l=a.apiKey;this.m=a.appName;this.s=a.authDomain||null;a=firebase.SDK_VERSION?Le(firebase.SDK_VERSION):null;this.a=new Ei(this.l,za(Aa),a);this.b=new sm(this.a);Am(this,b[Ag]);um(this.b,b);K(this,"refreshToken",this.b.a);Bm(this,c||{});G.call(this);this.P=!1;this.s&&Oe()&&(this.i=Pl(this.s,this.l,this.m));this.R=[];this.h=null;this.B=Cm(this);this.Z=r(this.Ma,this);var d=this;this.oa=null;this.za=function(e){d.va(e.g)};this.aa=null;this.W=[];this.ya=function(e){Dm(d, e.c)};this.$=null;this.O=new lm(this,c);K(this,"multiFactor",this.O)}t(P,G);P.prototype.va=function(a){this.oa=a;Ki(this.a,a)};P.prototype.ja=function(){return this.oa};function Em(a,b){a.aa&&td(a.aa,"languageCodeChanged",a.za);(a.aa=b)&&jd(b,"languageCodeChanged",a.za)}function Dm(a,b){a.W=b;Li(a.a,firebase.SDK_VERSION?Le(firebase.SDK_VERSION,a.W):null)}P.prototype.Ea=function(){return Wa(this.W)};function Fm(a,b){a.$&&td(a.$,"frameworkChanged",a.ya);(a.$=b)&&jd(b,"frameworkChanged",a.ya)} P.prototype.Ma=function(){this.B.b&&(this.B.stop(),this.B.start())};function Gm(a){try{return firebase.app(a.m).auth()}catch(b){throw new u("internal-error","No firebase.auth.Auth instance is available for the Firebase App '"+a.m+"'!");}}function Cm(a){return new pm(function(){return a.I(!0)},function(b){return b&&"auth/network-request-failed"==b.code?!0:!1},function(){var b=tm(a.b)-ta()-3E5;return 0<b?b:0})} function Hm(a){a.D||a.B.b||(a.B.start(),td(a,"tokenChanged",a.Z),jd(a,"tokenChanged",a.Z))}function Im(a){td(a,"tokenChanged",a.Z);a.B.stop()}function Am(a,b){a.xa=b;K(a,"_lat",b)}function Jm(a,b){Ua(a.R,function(c){return c==b})}function Km(a){for(var b=[],c=0;c<a.R.length;c++)b.push(a.R[c](a));return Ec(b).then(function(){return a})}function Lm(a){a.i&&!a.P&&(a.P=!0,Hl(a.i,a))} function Bm(a,b){L(a,{uid:b.uid,displayName:b.displayName||null,photoURL:b.photoURL||null,email:b.email||null,emailVerified:b.emailVerified||!1,phoneNumber:b.phoneNumber||null,isAnonymous:b.isAnonymous||!1,tenantId:b.tenantId||null,metadata:new xm(b.createdAt,b.lastLoginAt),providerData:[]});a.a.b=a.tenantId}K(P.prototype,"providerId","firebase");function Mm(){}function Nm(a){return E().then(function(){if(a.D)throw new u("app-deleted");})} function Om(a){return Oa(a.providerData,function(b){return b.providerId})}function Pm(a,b){b&&(Qm(a,b.providerId),a.providerData.push(b))}function Qm(a,b){Ua(a.providerData,function(c){return c.providerId==b})}function Rm(a,b,c){("uid"!=b||c)&&a.hasOwnProperty(b)&&K(a,b,c)} function Sm(a,b){a!=b&&(L(a,{uid:b.uid,displayName:b.displayName,photoURL:b.photoURL,email:b.email,emailVerified:b.emailVerified,phoneNumber:b.phoneNumber,isAnonymous:b.isAnonymous,tenantId:b.tenantId,providerData:[]}),b.metadata?K(a,"metadata",ym(b.metadata)):K(a,"metadata",new xm),x(b.providerData,function(c){Pm(a,c)}),vm(a.b,b.b),K(a,"refreshToken",a.b.a),mm(a.O,b.O.b))}k=P.prototype;k.reload=function(){var a=this;return R(this,Nm(this).then(function(){return Tm(a).then(function(){return Km(a)}).then(Mm)}))}; function Tm(a){return a.I().then(function(b){var c=a.isAnonymous;return Um(a,b).then(function(){c||Rm(a,"isAnonymous",!1);return b})})}k.mc=function(a){return this.I(a).then(function(b){return new $l(b)})};k.I=function(a){var b=this;return R(this,Nm(this).then(function(){return b.b.getToken(a)}).then(function(c){if(!c)throw new u("internal-error");c.accessToken!=b.xa&&(Am(b,c.accessToken),b.dispatchEvent(new km("tokenChanged")));Rm(b,"refreshToken",c.refreshToken);return c.accessToken}))}; function om(a,b){b[Ag]&&a.xa!=b[Ag]&&(um(a.b,b),a.dispatchEvent(new km("tokenChanged")),Am(a,b[Ag]),Rm(a,"refreshToken",a.b.a))}function Um(a,b){return N(a.a,Cj,{idToken:b}).then(r(a.Ic,a))} k.Ic=function(a){a=a.users;if(!a||!a.length)throw new u("internal-error");a=a[0];Bm(this,{uid:a.localId,displayName:a.displayName,photoURL:a.photoUrl,email:a.email,emailVerified:!!a.emailVerified,phoneNumber:a.phoneNumber,lastLoginAt:a.lastLoginAt,createdAt:a.createdAt,tenantId:a.tenantId});for(var b=Vm(a),c=0;c<b.length;c++)Pm(this,b[c]);Rm(this,"isAnonymous",!(this.email&&a.passwordHash)&&!(this.providerData&&this.providerData.length));this.dispatchEvent(new km("userReloaded",{ed:a}))}; function Vm(a){return(a=a.providerUserInfo)&&a.length?Oa(a,function(b){return new zm(b.rawId,b.providerId,b.email,b.displayName,b.photoUrl,b.phoneNumber)}):[]}k.Jc=function(a){df("firebase.User.prototype.reauthenticateAndRetrieveDataWithCredential is deprecated. Please use firebase.User.prototype.reauthenticateWithCredential instead.");return this.pb(a)}; k.pb=function(a){var b=this,c=null;return R(this,a.c(this.a,this.uid).then(function(d){om(b,d);c=Wm(b,d,"reauthenticate");b.h=null;return b.reload()}).then(function(){return c}),!0)};function Xm(a,b){return Tm(a).then(function(){if(Sa(Om(a),b))return Km(a).then(function(){throw new u("provider-already-linked");})})}k.Ac=function(a){df("firebase.User.prototype.linkAndRetrieveDataWithCredential is deprecated. Please use firebase.User.prototype.linkWithCredential instead.");return this.mb(a)}; k.mb=function(a){var b=this,c=null;return R(this,Xm(this,a.providerId).then(function(){return b.I()}).then(function(d){return a.b(b.a,d)}).then(function(d){c=Wm(b,d,"link");return Ym(b,d)}).then(function(){return c}))};k.Bc=function(a,b){var c=this;return R(this,Xm(this,"phone").then(function(){return Zl(Gm(c),a,b,r(c.mb,c))}))};k.Kc=function(a,b){var c=this;return R(this,E().then(function(){return Zl(Gm(c),a,b,r(c.pb,c))}),!0)}; function Wm(a,b,c){var d=mh(b);b=lg(b);return gf({user:a,credential:d,additionalUserInfo:b,operationType:c})}function Ym(a,b){om(a,b);return a.reload().then(function(){return a})}k.xb=function(a){var b=this;return R(this,this.I().then(function(c){return b.a.xb(c,a)}).then(function(c){om(b,c);return b.reload()}))};k.cd=function(a){var b=this;return R(this,this.I().then(function(c){return a.b(b.a,c)}).then(function(c){om(b,c);return b.reload()}))}; k.yb=function(a){var b=this;return R(this,this.I().then(function(c){return b.a.yb(c,a)}).then(function(c){om(b,c);return b.reload()}))}; k.zb=function(a){if(void 0===a.displayName&&void 0===a.photoURL)return Nm(this);var b=this;return R(this,this.I().then(function(c){return b.a.zb(c,{displayName:a.displayName,photoUrl:a.photoURL})}).then(function(c){om(b,c);Rm(b,"displayName",c.displayName||null);Rm(b,"photoURL",c.photoUrl||null);x(b.providerData,function(d){"password"===d.providerId&&(K(d,"displayName",b.displayName),K(d,"photoURL",b.photoURL))});return Km(b)}).then(Mm))}; k.ad=function(a){var b=this;return R(this,Tm(this).then(function(c){return Sa(Om(b),a)?lj(b.a,c,[a]).then(function(d){var e={};x(d.providerUserInfo||[],function(f){e[f.providerId]=!0});x(Om(b),function(f){e[f]||Qm(b,f)});e[hh.PROVIDER_ID]||K(b,"phoneNumber",null);return Km(b)}):Km(b).then(function(){throw new u("no-such-provider");})}))}; k.delete=function(){var a=this;return R(this,this.I().then(function(b){return N(a.a,zj,{idToken:b})}).then(function(){a.dispatchEvent(new km("userDeleted"))})).then(function(){for(var b=0;b<a.N.length;b++)a.N[b].cancel("app-deleted");Em(a,null);Fm(a,null);a.N=[];a.D=!0;Im(a);K(a,"refreshToken",null);a.i&&Il(a.i,a)})}; k.Cb=function(a,b){return"linkViaPopup"==a&&(this.g||null)==b&&this.f||"reauthViaPopup"==a&&(this.g||null)==b&&this.f||"linkViaRedirect"==a&&(this.fa||null)==b||"reauthViaRedirect"==a&&(this.fa||null)==b?!0:!1};k.la=function(a,b,c,d){"linkViaPopup"!=a&&"reauthViaPopup"!=a||d!=(this.g||null)||(c&&this.w?this.w(c):b&&!c&&this.f&&this.f(b),this.c&&(this.c.cancel(),this.c=null),delete this.f,delete this.w)}; k.Da=function(a,b){return"linkViaPopup"==a&&b==(this.g||null)?r(this.Hb,this):"reauthViaPopup"==a&&b==(this.g||null)?r(this.Ib,this):"linkViaRedirect"==a&&(this.fa||null)==b?r(this.Hb,this):"reauthViaRedirect"==a&&(this.fa||null)==b?r(this.Ib,this):null};k.Cc=function(a){var b=this;return Zm(this,"linkViaPopup",a,function(){return Xm(b,a.providerId).then(function(){return Km(b)})},!1)};k.Lc=function(a){return Zm(this,"reauthViaPopup",a,function(){return E()},!0)}; function Zm(a,b,c,d,e){if(!Oe())return F(new u("operation-not-supported-in-this-environment"));if(a.h&&!e)return F(a.h);var f=kg(c.providerId),g=Ne(a.uid+":::"),h=null;(!Qe()||Fe())&&a.s&&c.isOAuthProvider&&(h=Yj(a.s,a.l,a.m,b,c,null,g,firebase.SDK_VERSION||null,null,null,a.tenantId));var m=we(h,f&&f.ta,f&&f.sa);d=d().then(function(){$m(a);if(!e)return a.I().then(function(){})}).then(function(){return Ll(a.i,m,b,c,g,!!h,a.tenantId)}).then(function(){return new D(function(p,v){a.la(b,null,new u("cancelled-popup-request"), a.g||null);a.f=p;a.w=v;a.g=g;a.c=Nl(a.i,a,b,m,g)})}).then(function(p){m&&ve(m);return p?gf(p):null}).o(function(p){m&&ve(m);throw p;});return R(a,d,e)}k.Dc=function(a){var b=this;return an(this,"linkViaRedirect",a,function(){return Xm(b,a.providerId)},!1)};k.Mc=function(a){return an(this,"reauthViaRedirect",a,function(){return E()},!0)}; function an(a,b,c,d,e){if(!Oe())return F(new u("operation-not-supported-in-this-environment"));if(a.h&&!e)return F(a.h);var f=null,g=Ne(a.uid+":::");d=d().then(function(){$m(a);if(!e)return a.I().then(function(){})}).then(function(){a.fa=g;return Km(a)}).then(function(h){a.ga&&(h=a.ga,h=h.b.set(bn,a.v(),h.a));return h}).then(function(){return Ml(a.i,b,c,g,a.tenantId)}).o(function(h){f=h;if(a.ga)return cn(a.ga);throw f;}).then(function(){if(f)throw f;});return R(a,d,e)} function $m(a){if(!a.i||!a.P){if(a.i&&!a.P)throw new u("internal-error");throw new u("auth-domain-config-required");}}k.Hb=function(a,b,c,d){var e=this;this.c&&(this.c.cancel(),this.c=null);var f=null;c=this.I().then(function(g){return Eg(e.a,{requestUri:a,postBody:d,sessionId:b,idToken:g})}).then(function(g){f=Wm(e,g,"link");return Ym(e,g)}).then(function(){return f});return R(this,c)}; k.Ib=function(a,b,c,d){var e=this;this.c&&(this.c.cancel(),this.c=null);var f=null,g=E().then(function(){return zg(Fg(e.a,{requestUri:a,sessionId:b,postBody:d,tenantId:c}),e.uid)}).then(function(h){f=Wm(e,h,"reauthenticate");om(e,h);e.h=null;return e.reload()}).then(function(){return f});return R(this,g,!0)}; k.qb=function(a){var b=this,c=null;return R(this,this.I().then(function(d){c=d;return"undefined"===typeof a||jb(a)?{}:Zf(new Pf(a))}).then(function(d){return b.a.qb(c,d)}).then(function(d){if(b.email!=d)return b.reload()}).then(function(){}))};k.Ab=function(a,b){var c=this,d=null;return R(this,this.I().then(function(e){d=e;return"undefined"===typeof b||jb(b)?{}:Zf(new Pf(b))}).then(function(e){return c.a.Ab(d,a,e)}).then(function(e){if(c.email!=e)return c.reload()}).then(function(){}))}; function R(a,b,c){var d=dn(a,b,c);a.N.push(d);d.ma(function(){Ta(a.N,d)});return d.o(function(e){var f=null;e&&"auth/multi-factor-auth-required"===e.code&&(f=em(e.v(),Gm(a),r(a.hc,a)));throw f||e;})}k.hc=function(a){var b=null,c=this;a=zg(E(a),c.uid).then(function(d){b=Wm(c,d,"reauthenticate");om(c,d);c.h=null;return c.reload()}).then(function(){return b});return R(this,a,!0)}; function dn(a,b,c){return a.h&&!c?(b.cancel(),F(a.h)):b.o(function(d){!d||"auth/user-disabled"!=d.code&&"auth/user-token-expired"!=d.code||(a.h||a.dispatchEvent(new km("userInvalidated")),a.h=d);throw d;})}k.toJSON=function(){return this.v()}; k.v=function(){var a={uid:this.uid,displayName:this.displayName,photoURL:this.photoURL,email:this.email,emailVerified:this.emailVerified,phoneNumber:this.phoneNumber,isAnonymous:this.isAnonymous,tenantId:this.tenantId,providerData:[],apiKey:this.l,appName:this.m,authDomain:this.s,stsTokenManager:this.b.v(),redirectEventId:this.fa||null};this.metadata&&B(a,this.metadata.v());x(this.providerData,function(b){a.providerData.push(hf(b))});B(a,this.O.v());return a}; function en(a){if(!a.apiKey)return null;var b={apiKey:a.apiKey,authDomain:a.authDomain,appName:a.appName},c={};if(a.stsTokenManager&&a.stsTokenManager.accessToken)c[Ag]=a.stsTokenManager.accessToken,c.refreshToken=a.stsTokenManager.refreshToken||null;else return null;var d=new P(b,c,a);a.providerData&&x(a.providerData,function(e){e&&Pm(d,gf(e))});a.redirectEventId&&(d.fa=a.redirectEventId);return d} function fn(a,b,c,d){var e=new P(a,b);c&&(e.ga=c);d&&Dm(e,d);return e.reload().then(function(){return e})}function gn(a,b,c,d){var e=a.b,f={};f[Ag]=e.b&&e.b.toString();f.refreshToken=e.a;b=new P(b||{apiKey:a.l,authDomain:a.s,appName:a.m},f);c&&(b.ga=c);d&&Dm(b,d);Sm(b,a);return b};function hn(a){this.a=a;this.b=Ok()}var bn={name:"redirectUser",F:"session"};function cn(a){return Sk(a.b,bn,a.a)}function jn(a,b){return a.b.get(bn,a.a).then(function(c){c&&b&&(c.authDomain=b);return en(c||{})})};function kn(a){this.a=a;this.b=Ok();this.c=null;this.f=ln(this);this.b.addListener(mn("local"),this.a,r(this.g,this))}kn.prototype.g=function(){var a=this,b=mn("local");nn(this,function(){return E().then(function(){return a.c&&"local"!=a.c.F?a.b.get(b,a.a):null}).then(function(c){if(c)return on(a,"local").then(function(){a.c=b})})})};function on(a,b){var c=[],d;for(d in Kk)Kk[d]!==b&&c.push(Sk(a.b,mn(Kk[d]),a.a));c.push(Sk(a.b,pn,a.a));return Dc(c)} function ln(a){var b=mn("local"),c=mn("session"),d=mn("none");return Rk(a.b,b,a.a).then(function(){return a.b.get(c,a.a)}).then(function(e){return e?c:a.b.get(d,a.a).then(function(f){return f?d:a.b.get(b,a.a).then(function(g){return g?b:a.b.get(pn,a.a).then(function(h){return h?mn(h):b})})})}).then(function(e){a.c=e;return on(a,e.F)}).o(function(){a.c||(a.c=b)})}var pn={name:"persistence",F:"session"};function mn(a){return{name:"authUser",F:a}} kn.prototype.tb=function(a){var b=null,c=this;Lk(a);return nn(this,function(){return a!=c.c.F?c.b.get(c.c,c.a).then(function(d){b=d;return on(c,a)}).then(function(){c.c=mn(a);if(b)return c.b.set(c.c,b,c.a)}):E()})};function qn(a){return nn(a,function(){return a.b.set(pn,a.c.F,a.a)})}function rn(a,b){return nn(a,function(){return a.b.set(a.c,b.v(),a.a)})}function sn(a){return nn(a,function(){return Sk(a.b,a.c,a.a)})} function tn(a,b){return nn(a,function(){return a.b.get(a.c,a.a).then(function(c){c&&b&&(c.authDomain=b);return en(c||{})})})}function nn(a,b){a.f=a.f.then(b,b);return a.f};function un(a){this.l=!1;K(this,"settings",new Xl);K(this,"app",a);if(S(this).options&&S(this).options.apiKey)a=firebase.SDK_VERSION?Le(firebase.SDK_VERSION):null,this.b=new Ei(S(this).options&&S(this).options.apiKey,za(Aa),a);else throw new u("invalid-api-key");this.P=[];this.m=[];this.O=[];this.$b=firebase.INTERNAL.createSubscribe(r(this.xc,this));this.W=void 0;this.ac=firebase.INTERNAL.createSubscribe(r(this.yc,this));vn(this,null);this.i=new kn(S(this).options.apiKey+":"+S(this).name);this.B= new hn(S(this).options.apiKey+":"+S(this).name);this.Z=T(this,wn(this));this.h=T(this,xn(this));this.aa=!1;this.oa=r(this.Xc,this);this.Ma=r(this.ca,this);this.xa=r(this.jc,this);this.ya=r(this.uc,this);this.za=r(this.vc,this);this.a=null;yn(this);this.INTERNAL={};this.INTERNAL["delete"]=r(this.delete,this);this.INTERNAL.logFramework=r(this.Ec,this);this.s=0;G.call(this);zn(this);this.N=[]}t(un,G);function An(a){Xc.call(this,"languageCodeChanged");this.g=a}t(An,Xc); function Bn(a){Xc.call(this,"frameworkChanged");this.c=a}t(Bn,Xc);k=un.prototype;k.tb=function(a){a=this.i.tb(a);return T(this,a)};k.va=function(a){this.$===a||this.l||(this.$=a,Ki(this.b,this.$),this.dispatchEvent(new An(this.ja())))};k.ja=function(){return this.$};k.dd=function(){var a=l.navigator;this.va(a?a.languages&&a.languages[0]||a.language||a.userLanguage||null:null)};k.Ec=function(a){this.N.push(a);Li(this.b,firebase.SDK_VERSION?Le(firebase.SDK_VERSION,this.N):null);this.dispatchEvent(new Bn(this.N))}; k.Ea=function(){return Wa(this.N)};k.ub=function(a){this.R===a||this.l||(this.R=a,this.b.b=this.R)};k.S=function(){return this.R};function zn(a){Object.defineProperty(a,"lc",{get:function(){return this.ja()},set:function(b){this.va(b)},enumerable:!1});a.$=null;Object.defineProperty(a,"ti",{get:function(){return this.S()},set:function(b){this.ub(b)},enumerable:!1});a.R=null} k.toJSON=function(){return{apiKey:S(this).options.apiKey,authDomain:S(this).options.authDomain,appName:S(this).name,currentUser:U(this)&&U(this).v()}};function Cn(a){return a.Zb||F(new u("auth-domain-config-required"))}function yn(a){var b=S(a).options.authDomain,c=S(a).options.apiKey;b&&Oe()&&(a.Zb=a.Z.then(function(){if(!a.l){a.a=Pl(b,c,S(a).name);Hl(a.a,a);U(a)&&Lm(U(a));if(a.D){Lm(a.D);var d=a.D;d.va(a.ja());Em(d,a);d=a.D;Dm(d,a.N);Fm(d,a);a.D=null}return a.a}}))} k.Cb=function(a,b){switch(a){case "unknown":case "signInViaRedirect":return!0;case "signInViaPopup":return this.g==b&&!!this.f;default:return!1}};k.la=function(a,b,c,d){"signInViaPopup"==a&&this.g==d&&(c&&this.w?this.w(c):b&&!c&&this.f&&this.f(b),this.c&&(this.c.cancel(),this.c=null),delete this.f,delete this.w)};k.Da=function(a,b){return"signInViaRedirect"==a||"signInViaPopup"==a&&this.g==b&&this.f?r(this.gc,this):null}; k.gc=function(a,b,c,d){var e=this,f={requestUri:a,postBody:d,sessionId:b,tenantId:c};this.c&&(this.c.cancel(),this.c=null);return e.Z.then(function(){return Dn(e,Cg(e.b,f))})}; k.Vc=function(a){if(!Oe())return F(new u("operation-not-supported-in-this-environment"));var b=this,c=kg(a.providerId),d=Ne(),e=null;(!Qe()||Fe())&&S(this).options.authDomain&&a.isOAuthProvider&&(e=Yj(S(this).options.authDomain,S(this).options.apiKey,S(this).name,"signInViaPopup",a,null,d,firebase.SDK_VERSION||null,null,null,this.S()));var f=we(e,c&&c.ta,c&&c.sa);c=Cn(this).then(function(g){return Ll(g,f,"signInViaPopup",a,d,!!e,b.S())}).then(function(){return new D(function(g,h){b.la("signInViaPopup", null,new u("cancelled-popup-request"),b.g);b.f=g;b.w=h;b.g=d;b.c=Nl(b.a,b,"signInViaPopup",f,d)})}).then(function(g){f&&ve(f);return g?gf(g):null}).o(function(g){f&&ve(f);throw g;});return T(this,c)};k.Wc=function(a){if(!Oe())return F(new u("operation-not-supported-in-this-environment"));var b=this,c=Cn(this).then(function(){return qn(b.i)}).then(function(){return Ml(b.a,"signInViaRedirect",a,void 0,b.S())});return T(this,c)}; function En(a){if(!Oe())return F(new u("operation-not-supported-in-this-environment"));var b=Cn(a).then(function(){return a.a.pa()}).then(function(c){return c?gf(c):null});return T(a,b)}k.pa=function(){var a=this;return En(this).then(function(b){a.a&&Sl(a.a.b);return b}).o(function(b){a.a&&Sl(a.a.b);throw b;})}; k.bd=function(a){if(!a)return F(new u("null-user"));if(this.R!=a.tenantId)return F(new u("tenant-id-mismatch"));var b=this,c={};c.apiKey=S(this).options.apiKey;c.authDomain=S(this).options.authDomain;c.appName=S(this).name;var d=gn(a,c,b.B,b.Ea());return T(this,this.h.then(function(){if(S(b).options.apiKey!=a.l)return d.reload()}).then(function(){if(U(b)&&a.uid==U(b).uid)return Sm(U(b),a),b.ca(a);vn(b,d);Lm(d);return b.ca(d)}).then(function(){Fn(b)}))}; function Gn(a,b){var c={};c.apiKey=S(a).options.apiKey;c.authDomain=S(a).options.authDomain;c.appName=S(a).name;return a.Z.then(function(){return fn(c,b,a.B,a.Ea())}).then(function(d){if(U(a)&&d.uid==U(a).uid)return Sm(U(a),d),a.ca(d);vn(a,d);Lm(d);return a.ca(d)}).then(function(){Fn(a)})} function vn(a,b){U(a)&&(Jm(U(a),a.Ma),td(U(a),"tokenChanged",a.xa),td(U(a),"userDeleted",a.ya),td(U(a),"userInvalidated",a.za),Im(U(a)));b&&(b.R.push(a.Ma),jd(b,"tokenChanged",a.xa),jd(b,"userDeleted",a.ya),jd(b,"userInvalidated",a.za),0<a.s&&Hm(b));K(a,"currentUser",b);b&&(b.va(a.ja()),Em(b,a),Dm(b,a.N),Fm(b,a))}k.wb=function(){var a=this,b=this.h.then(function(){a.a&&Sl(a.a.b);if(!U(a))return E();vn(a,null);return sn(a.i).then(function(){Fn(a)})});return T(this,b)}; function Hn(a){var b=jn(a.B,S(a).options.authDomain).then(function(c){if(a.D=c)c.ga=a.B;return cn(a.B)});return T(a,b)}function wn(a){var b=S(a).options.authDomain,c=Hn(a).then(function(){return tn(a.i,b)}).then(function(d){return d?(d.ga=a.B,a.D&&(a.D.fa||null)==(d.fa||null)?d:d.reload().then(function(){return rn(a.i,d).then(function(){return d})}).o(function(e){return"auth/network-request-failed"==e.code?d:sn(a.i)})):null}).then(function(d){vn(a,d||null)});return T(a,c)} function xn(a){return a.Z.then(function(){return En(a)}).o(function(){}).then(function(){if(!a.l)return a.oa()}).o(function(){}).then(function(){if(!a.l){a.aa=!0;var b=a.i;b.b.addListener(mn("local"),b.a,a.oa)}})} k.Xc=function(){var a=this;return tn(this.i,S(this).options.authDomain).then(function(b){if(!a.l){var c;if(c=U(a)&&b){c=U(a).uid;var d=b.uid;c=void 0===c||null===c||""===c||void 0===d||null===d||""===d?!1:c==d}if(c)return Sm(U(a),b),U(a).I();if(U(a)||b)vn(a,b),b&&(Lm(b),b.ga=a.B),a.a&&Hl(a.a,a),Fn(a)}})};k.ca=function(a){return rn(this.i,a)};k.jc=function(){Fn(this);this.ca(U(this))};k.uc=function(){this.wb()};k.vc=function(){this.wb()}; function Dn(a,b){var c=null,d=null;return T(a,b.then(function(e){c=mh(e);d=lg(e);return Gn(a,e)},function(e){var f=null;e&&"auth/multi-factor-auth-required"===e.code&&(f=em(e.v(),a,r(a.ic,a)));throw f||e;}).then(function(){return gf({user:U(a),credential:c,additionalUserInfo:d,operationType:"signIn"})}))}k.ic=function(a){var b=this;return this.h.then(function(){return Dn(b,E(a))})};k.xc=function(a){var b=this;this.addAuthTokenListener(function(){a.next(U(b))})}; k.yc=function(a){var b=this;In(this,function(){a.next(U(b))})};k.Gc=function(a,b,c){var d=this;this.aa&&Promise.resolve().then(function(){n(a)?a(U(d)):n(a.next)&&a.next(U(d))});return this.$b(a,b,c)};k.Fc=function(a,b,c){var d=this;this.aa&&Promise.resolve().then(function(){d.W=d.getUid();n(a)?a(U(d)):n(a.next)&&a.next(U(d))});return this.ac(a,b,c)};k.kc=function(a){var b=this,c=this.h.then(function(){return U(b)?U(b).I(a).then(function(d){return{accessToken:d}}):null});return T(this,c)}; k.Rc=function(a){var b=this;return this.h.then(function(){return Dn(b,N(b.b,Ej,{token:a}))}).then(function(c){var d=c.user;Rm(d,"isAnonymous",!1);b.ca(d);return c})};k.Sc=function(a,b){var c=this;return this.h.then(function(){return Dn(c,N(c.b,Xg,{email:a,password:b}))})};k.cc=function(a,b){var c=this;return this.h.then(function(){return Dn(c,N(c.b,yj,{email:a,password:b}))})};k.Ya=function(a){var b=this;return this.h.then(function(){return Dn(b,a.ia(b.b))})}; k.Qc=function(a){df("firebase.auth.Auth.prototype.signInAndRetrieveDataWithCredential is deprecated. Please use firebase.auth.Auth.prototype.signInWithCredential instead.");return this.Ya(a)};k.vb=function(){var a=this;return this.h.then(function(){var b=U(a);if(b&&b.isAnonymous){var c=gf({providerId:null,isNewUser:!1});return gf({user:b,credential:null,additionalUserInfo:c,operationType:"signIn"})}return Dn(a,a.b.vb()).then(function(d){var e=d.user;Rm(e,"isAnonymous",!0);a.ca(e);return d})})}; function S(a){return a.app}function U(a){return a.currentUser}k.getUid=function(){return U(this)&&U(this).uid||null};function Jn(a){return U(a)&&U(a)._lat||null}function Fn(a){if(a.aa){for(var b=0;b<a.m.length;b++)if(a.m[b])a.m[b](Jn(a));if(a.W!==a.getUid()&&a.O.length)for(a.W=a.getUid(),b=0;b<a.O.length;b++)if(a.O[b])a.O[b](Jn(a))}}k.bc=function(a){this.addAuthTokenListener(a);this.s++;0<this.s&&U(this)&&Hm(U(this))}; k.Nc=function(a){var b=this;x(this.m,function(c){c==a&&b.s--});0>this.s&&(this.s=0);0==this.s&&U(this)&&Im(U(this));this.removeAuthTokenListener(a)};k.addAuthTokenListener=function(a){var b=this;this.m.push(a);T(this,this.h.then(function(){b.l||Sa(b.m,a)&&a(Jn(b))}))};k.removeAuthTokenListener=function(a){Ua(this.m,function(b){return b==a})};function In(a,b){a.O.push(b);T(a,a.h.then(function(){!a.l&&Sa(a.O,b)&&a.W!==a.getUid()&&(a.W=a.getUid(),b(Jn(a)))}))} k.delete=function(){this.l=!0;for(var a=0;a<this.P.length;a++)this.P[a].cancel("app-deleted");this.P=[];this.i&&(a=this.i,a.b.removeListener(mn("local"),a.a,this.oa));this.a&&(Il(this.a,this),Sl(this.a.b));return Promise.resolve()};function T(a,b){a.P.push(b);b.ma(function(){Ta(a.P,b)});return b}k.fc=function(a){return T(this,Vi(this.b,a))};k.zc=function(a){return!!bh(a)}; k.sb=function(a,b){var c=this;return T(this,E().then(function(){var d=new Pf(b);if(!d.c)throw new u("argument-error",Xf+" must be true when sending sign in link to email");return Zf(d)}).then(function(d){return c.b.sb(a,d)}).then(function(){}))};k.fd=function(a){return this.Pa(a).then(function(b){return b.data.email})};k.jb=function(a,b){return T(this,this.b.jb(a,b).then(function(){}))};k.Pa=function(a){return T(this,this.b.Pa(a).then(function(b){return new sf(b)}))}; k.fb=function(a){return T(this,this.b.fb(a).then(function(){}))};k.rb=function(a,b){var c=this;return T(this,E().then(function(){return"undefined"===typeof b||jb(b)?{}:Zf(new Pf(b))}).then(function(d){return c.b.rb(a,d)}).then(function(){}))};k.Uc=function(a,b){return T(this,Zl(this,a,b,r(this.Ya,this)))}; k.Tc=function(a,b){var c=this;return T(this,E().then(function(){var d=b||oe(),e=ah(a,d);d=bh(d);if(!d)throw new u("argument-error","Invalid email link!");if(d.tenantId!==c.S())throw new u("tenant-id-mismatch");return c.Ya(e)}))};function Kn(){}Kn.prototype.render=function(){};Kn.prototype.reset=function(){};Kn.prototype.getResponse=function(){};Kn.prototype.execute=function(){};function Ln(){this.a={};this.b=1E12}var Mn=null;Ln.prototype.render=function(a,b){this.a[this.b.toString()]=new Nn(a,b);return this.b++};Ln.prototype.reset=function(a){var b=On(this,a);a=Pn(a);b&&a&&(b.delete(),delete this.a[a])};Ln.prototype.getResponse=function(a){return(a=On(this,a))?a.getResponse():null};Ln.prototype.execute=function(a){(a=On(this,a))&&a.execute()};function On(a,b){return(b=Pn(b))?a.a[b]||null:null}function Pn(a){return(a="undefined"===typeof a?1E12:a)?a.toString():null} function Nn(a,b){this.g=!1;this.c=b;this.a=this.b=null;this.h="invisible"!==this.c.size;this.f=ec(a);var c=this;this.i=function(){c.execute()};this.h?this.execute():jd(this.f,"click",this.i)}Nn.prototype.getResponse=function(){Qn(this);return this.b}; Nn.prototype.execute=function(){Qn(this);var a=this;this.a||(this.a=setTimeout(function(){a.b=Je();var b=a.c.callback,c=a.c["expired-callback"];if(b)try{b(a.b)}catch(d){}a.a=setTimeout(function(){a.a=null;a.b=null;if(c)try{c()}catch(d){}a.h&&a.execute()},6E4)},500))};Nn.prototype.delete=function(){Qn(this);this.g=!0;clearTimeout(this.a);this.a=null;td(this.f,"click",this.i)};function Qn(a){if(a.g)throw Error("reCAPTCHA mock was already deleted!");};function Rn(){}K(Rn,"FACTOR_ID","phone");function Sn(){}Sn.prototype.g=function(){Mn||(Mn=new Ln);return E(Mn)};Sn.prototype.c=function(){};var Tn=null;function Un(){this.b=l.grecaptcha?Infinity:0;this.f=null;this.a="__rcb"+Math.floor(1E6*Math.random()).toString()}var Vn=new nb(ob,"https://www.google.com/recaptcha/api.js?onload=%{onload}&render=explicit&hl=%{hl}"),Wn=new We(3E4,6E4); Un.prototype.g=function(a){var b=this;return new D(function(c,d){var e=setTimeout(function(){d(new u("network-request-failed"))},Wn.get());if(!l.grecaptcha||a!==b.f&&!b.b){l[b.a]=function(){if(l.grecaptcha){b.f=a;var g=l.grecaptcha.render;l.grecaptcha.render=function(h,m){h=g(h,m);b.b++;return h};clearTimeout(e);c(l.grecaptcha)}else clearTimeout(e),d(new u("internal-error"));delete l[b.a]};var f=wb(Vn,{onload:b.a,hl:a||""});E(xi(f)).o(function(){clearTimeout(e);d(new u("internal-error","Unable to load external reCAPTCHA dependencies!"))})}else clearTimeout(e), c(l.grecaptcha)})};Un.prototype.c=function(){this.b--};var Xn=null;function Yn(a,b,c,d,e,f,g){K(this,"type","recaptcha");this.c=this.f=null;this.D=!1;this.u=b;this.g=null;g?(Tn||(Tn=new Sn),g=Tn):(Xn||(Xn=new Un),g=Xn);this.m=g;this.a=c||{theme:"light",type:"image"};this.h=[];if(this.a[Zn])throw new u("argument-error","sitekey should not be provided for reCAPTCHA as one is automatically provisioned for the current project.");this.i="invisible"===this.a[$n];if(!l.document)throw new u("operation-not-supported-in-this-environment","RecaptchaVerifier is only supported in a browser HTTP/HTTPS environment with DOM support."); if(!ec(b)||!this.i&&ec(b).hasChildNodes())throw new u("argument-error","reCAPTCHA container is either not found or already contains inner elements!");this.s=new Ei(a,f||null,e||null);this.w=d||function(){return null};var h=this;this.l=[];var m=this.a[ao];this.a[ao]=function(v){bo(h,v);if("function"===typeof m)m(v);else if("string"===typeof m){var C=J(m,l);"function"===typeof C&&C(v)}};var p=this.a[co];this.a[co]=function(){bo(h,null);if("function"===typeof p)p();else if("string"===typeof p){var v= J(p,l);"function"===typeof v&&v()}}}var ao="callback",co="expired-callback",Zn="sitekey",$n="size";function bo(a,b){for(var c=0;c<a.l.length;c++)try{a.l[c](b)}catch(d){}}function eo(a,b){Ua(a.l,function(c){return c==b})}function fo(a,b){a.h.push(b);b.ma(function(){Ta(a.h,b)});return b}k=Yn.prototype; k.Ga=function(){var a=this;return this.f?this.f:this.f=fo(this,E().then(function(){if(Pe()&&!Ge())return Be();throw new u("operation-not-supported-in-this-environment","RecaptchaVerifier is only supported in a browser HTTP/HTTPS environment.");}).then(function(){return a.m.g(a.w())}).then(function(b){a.g=b;return N(a.s,Dj,{})}).then(function(b){a.a[Zn]=b.recaptchaSiteKey}).o(function(b){a.f=null;throw b;}))}; k.render=function(){go(this);var a=this;return fo(this,this.Ga().then(function(){if(null===a.c){var b=a.u;if(!a.i){var c=ec(b);b=hc("DIV");c.appendChild(b)}a.c=a.g.render(b,a.a)}return a.c}))};k.verify=function(){go(this);var a=this;return fo(this,this.render().then(function(b){return new D(function(c){var d=a.g.getResponse(b);if(d)c(d);else{var e=function(f){f&&(eo(a,e),c(f))};a.l.push(e);a.i&&a.g.execute(a.c)}})}))};k.reset=function(){go(this);null!==this.c&&this.g.reset(this.c)}; function go(a){if(a.D)throw new u("internal-error","RecaptchaVerifier instance has been destroyed.");}k.clear=function(){go(this);this.D=!0;this.m.c();for(var a=0;a<this.h.length;a++)this.h[a].cancel("RecaptchaVerifier instance has been destroyed.");if(!this.i){a=ec(this.u);for(var b;b=a.firstChild;)a.removeChild(b)}}; function ho(a,b,c){var d=!1;try{this.b=c||firebase.app()}catch(g){throw new u("argument-error","No firebase.app.App instance is currently initialized.");}if(this.b.options&&this.b.options.apiKey)c=this.b.options.apiKey;else throw new u("invalid-api-key");var e=this,f=null;try{f=this.b.auth().Ea()}catch(g){}try{d=this.b.auth().settings.appVerificationDisabledForTesting}catch(g){}f=firebase.SDK_VERSION?Le(firebase.SDK_VERSION,f):null;Yn.call(this,c,a,b,function(){try{var g=e.b.auth().ja()}catch(h){g= null}return g},f,za(Aa),d)}t(ho,Yn);function io(a,b,c,d){a:{c=Array.prototype.slice.call(c);var e=0;for(var f=!1,g=0;g<b.length;g++)if(b[g].optional)f=!0;else{if(f)throw new u("internal-error","Argument validator encountered a required argument after an optional argument.");e++}f=b.length;if(c.length<e||f<c.length)d="Expected "+(e==f?1==e?"1 argument":e+" arguments":e+"-"+f+" arguments")+" but got "+c.length+".";else{for(e=0;e<c.length;e++)if(f=b[e].optional&&void 0===c[e],!b[e].K(c[e])&&!f){b=b[e];if(0>e||e>=jo.length)throw new u("internal-error", "Argument validator received an unsupported number of arguments.");c=jo[e];d=(d?"":c+" argument ")+(b.name?'"'+b.name+'" ':"")+"must be "+b.J+".";break a}d=null}}if(d)throw new u("argument-error",a+" failed: "+d);}var jo="First Second Third Fourth Fifth Sixth Seventh Eighth Ninth".split(" ");function V(a,b){return{name:a||"",J:"a valid string",optional:!!b,K:function(c){return"string"===typeof c}}} function ko(a,b){return{name:a||"",J:"a boolean",optional:!!b,K:function(c){return"boolean"===typeof c}}}function W(a,b){return{name:a||"",J:"a valid object",optional:!!b,K:q}}function lo(a,b){return{name:a||"",J:"a function",optional:!!b,K:n}}function mo(a,b){return{name:a||"",J:"null",optional:!!b,K:function(c){return null===c}}}function no(){return{name:"",J:"an HTML element",optional:!1,K:function(a){return!!(a&&a instanceof Element)}}} function oo(){return{name:"auth",J:"an instance of Firebase Auth",optional:!0,K:function(a){return!!(a&&a instanceof un)}}}function po(){return{name:"app",J:"an instance of Firebase App",optional:!0,K:function(a){return!!(a&&a instanceof firebase.app.App)}}}function qo(a){return{name:a?a+"Credential":"credential",J:a?"a valid "+a+" credential":"a valid credential",optional:!1,K:function(b){if(!b)return!1;var c=!a||b.providerId===a;return!(!b.ia||!c)}}} function ro(){return{name:"multiFactorAssertion",J:"a valid multiFactorAssertion",optional:!1,K:function(a){return a?!!a.ob:!1}}}function so(){return{name:"authProvider",J:"a valid Auth provider",optional:!1,K:function(a){return!!(a&&a.providerId&&a.hasOwnProperty&&a.hasOwnProperty("isOAuthProvider"))}}}function to(a,b){return q(a)&&"string"===typeof a.type&&a.type===b&&n(a.Fa)}function uo(a){return q(a)&&"string"===typeof a.uid} function vo(){return{name:"applicationVerifier",J:"an implementation of firebase.auth.ApplicationVerifier",optional:!1,K:function(a){return!(!a||"string"!==typeof a.type||!n(a.verify))}}}function X(a,b,c,d){return{name:c||"",J:a.J+" or "+b.J,optional:!!d,K:function(e){return a.K(e)||b.K(e)}}};function Y(a,b){for(var c in b){var d=b[c].name;a[d]=wo(d,a[c],b[c].j)}}function xo(a,b){for(var c in b){var d=b[c].name;d!==c&&Object.defineProperty(a,d,{get:sa(function(e){return this[e]},c),set:sa(function(e,f,g,h){io(e,[g],[h],!0);this[f]=h},d,c,b[c].gb),enumerable:!0})}}function Z(a,b,c,d){a[b]=wo(b,c,d)} function wo(a,b,c){function d(){var g=Array.prototype.slice.call(arguments);io(e,c,g);return b.apply(this,g)}if(!c)return b;var e=yo(a),f;for(f in b)d[f]=b[f];for(f in b.prototype)d.prototype[f]=b.prototype[f];return d}function yo(a){a=a.split(".");return a[a.length-1]};Y(un.prototype,{fb:{name:"applyActionCode",j:[V("code")]},Pa:{name:"checkActionCode",j:[V("code")]},jb:{name:"confirmPasswordReset",j:[V("code"),V("newPassword")]},cc:{name:"createUserWithEmailAndPassword",j:[V("email"),V("password")]},fc:{name:"fetchSignInMethodsForEmail",j:[V("email")]},pa:{name:"getRedirectResult",j:[]},zc:{name:"isSignInWithEmailLink",j:[V("emailLink")]},Fc:{name:"onAuthStateChanged",j:[X(W(),lo(),"nextOrObserver"),lo("opt_error",!0),lo("opt_completed",!0)]},Gc:{name:"onIdTokenChanged", j:[X(W(),lo(),"nextOrObserver"),lo("opt_error",!0),lo("opt_completed",!0)]},rb:{name:"sendPasswordResetEmail",j:[V("email"),X(W("opt_actionCodeSettings",!0),mo(null,!0),"opt_actionCodeSettings",!0)]},sb:{name:"sendSignInLinkToEmail",j:[V("email"),W("actionCodeSettings")]},tb:{name:"setPersistence",j:[V("persistence")]},Qc:{name:"signInAndRetrieveDataWithCredential",j:[qo()]},vb:{name:"signInAnonymously",j:[]},Ya:{name:"signInWithCredential",j:[qo()]},Rc:{name:"signInWithCustomToken",j:[V("token")]}, Sc:{name:"signInWithEmailAndPassword",j:[V("email"),V("password")]},Tc:{name:"signInWithEmailLink",j:[V("email"),V("emailLink",!0)]},Uc:{name:"signInWithPhoneNumber",j:[V("phoneNumber"),vo()]},Vc:{name:"signInWithPopup",j:[so()]},Wc:{name:"signInWithRedirect",j:[so()]},bd:{name:"updateCurrentUser",j:[X(function(a){return{name:"user",J:"an instance of Firebase User",optional:!!a,K:function(b){return!!(b&&b instanceof P)}}}(),mo(),"user")]},wb:{name:"signOut",j:[]},toJSON:{name:"toJSON",j:[V(null,!0)]}, dd:{name:"useDeviceLanguage",j:[]},fd:{name:"verifyPasswordResetCode",j:[V("code")]}});xo(un.prototype,{lc:{name:"languageCode",gb:X(V(),mo(),"languageCode")},ti:{name:"tenantId",gb:X(V(),mo(),"tenantId")}});un.Persistence=Kk;un.Persistence.LOCAL="local";un.Persistence.SESSION="session";un.Persistence.NONE="none"; Y(P.prototype,{"delete":{name:"delete",j:[]},mc:{name:"getIdTokenResult",j:[ko("opt_forceRefresh",!0)]},I:{name:"getIdToken",j:[ko("opt_forceRefresh",!0)]},Ac:{name:"linkAndRetrieveDataWithCredential",j:[qo()]},mb:{name:"linkWithCredential",j:[qo()]},Bc:{name:"linkWithPhoneNumber",j:[V("phoneNumber"),vo()]},Cc:{name:"linkWithPopup",j:[so()]},Dc:{name:"linkWithRedirect",j:[so()]},Jc:{name:"reauthenticateAndRetrieveDataWithCredential",j:[qo()]},pb:{name:"reauthenticateWithCredential",j:[qo()]},Kc:{name:"reauthenticateWithPhoneNumber", j:[V("phoneNumber"),vo()]},Lc:{name:"reauthenticateWithPopup",j:[so()]},Mc:{name:"reauthenticateWithRedirect",j:[so()]},reload:{name:"reload",j:[]},qb:{name:"sendEmailVerification",j:[X(W("opt_actionCodeSettings",!0),mo(null,!0),"opt_actionCodeSettings",!0)]},toJSON:{name:"toJSON",j:[V(null,!0)]},ad:{name:"unlink",j:[V("provider")]},xb:{name:"updateEmail",j:[V("email")]},yb:{name:"updatePassword",j:[V("password")]},cd:{name:"updatePhoneNumber",j:[qo("phone")]},zb:{name:"updateProfile",j:[W("profile")]}, Ab:{name:"verifyBeforeUpdateEmail",j:[V("email"),X(W("opt_actionCodeSettings",!0),mo(null,!0),"opt_actionCodeSettings",!0)]}});Y(Ln.prototype,{execute:{name:"execute"},render:{name:"render"},reset:{name:"reset"},getResponse:{name:"getResponse"}});Y(Kn.prototype,{execute:{name:"execute"},render:{name:"render"},reset:{name:"reset"},getResponse:{name:"getResponse"}});Y(D.prototype,{ma:{name:"finally"},o:{name:"catch"},then:{name:"then"}}); xo(Xl.prototype,{appVerificationDisabled:{name:"appVerificationDisabledForTesting",gb:ko("appVerificationDisabledForTesting")}});Y(Yl.prototype,{confirm:{name:"confirm",j:[V("verificationCode")]}});Z(yg,"fromJSON",function(a){a="string"===typeof a?JSON.parse(a):a;for(var b,c=[Jg,$g,gh,Gg],d=0;d<c.length;d++)if(b=c[d](a))return b;return null},[X(V(),W(),"json")]);Z(Vg,"credential",function(a,b){return new Ug(a,b)},[V("email"),V("password")]);Y(Ug.prototype,{v:{name:"toJSON",j:[V(null,!0)]}}); Y(Mg.prototype,{Aa:{name:"addScope",j:[V("scope")]},Ia:{name:"setCustomParameters",j:[W("customOAuthParameters")]}});Z(Mg,"credential",Ng,[X(V(),W(),"token")]);Z(Vg,"credentialWithLink",ah,[V("email"),V("emailLink")]);Y(Og.prototype,{Aa:{name:"addScope",j:[V("scope")]},Ia:{name:"setCustomParameters",j:[W("customOAuthParameters")]}});Z(Og,"credential",Pg,[X(V(),W(),"token")]);Y(Qg.prototype,{Aa:{name:"addScope",j:[V("scope")]},Ia:{name:"setCustomParameters",j:[W("customOAuthParameters")]}}); Z(Qg,"credential",Rg,[X(V(),X(W(),mo()),"idToken"),X(V(),mo(),"accessToken",!0)]);Y(Sg.prototype,{Ia:{name:"setCustomParameters",j:[W("customOAuthParameters")]}});Z(Sg,"credential",Tg,[X(V(),W(),"token"),V("secret",!0)]);Y(M.prototype,{Aa:{name:"addScope",j:[V("scope")]},credential:{name:"credential",j:[X(V(),X(W(),mo()),"optionsOrIdToken"),X(V(),mo(),"accessToken",!0)]},Ia:{name:"setCustomParameters",j:[W("customOAuthParameters")]}});Y(Hg.prototype,{v:{name:"toJSON",j:[V(null,!0)]}}); Y(Bg.prototype,{v:{name:"toJSON",j:[V(null,!0)]}});Z(hh,"credential",lh,[V("verificationId"),V("verificationCode")]); Y(hh.prototype,{cb:{name:"verifyPhoneNumber",j:[X(V(),function(a,b){return{name:a||"phoneInfoOptions",J:"valid phone info options",optional:!!b,K:function(c){return c?c.session&&c.phoneNumber?to(c.session,wg)&&"string"===typeof c.phoneNumber:c.session&&c.multiFactorHint?to(c.session,xg)&&uo(c.multiFactorHint):c.session&&c.multiFactorUid?to(c.session,xg)&&"string"===typeof c.multiFactorUid:c.phoneNumber?"string"===typeof c.phoneNumber:!1:!1}}}(),"phoneInfoOptions"),vo()]}}); Y(ch.prototype,{v:{name:"toJSON",j:[V(null,!0)]}});Y(u.prototype,{toJSON:{name:"toJSON",j:[V(null,!0)]}});Y(uh.prototype,{toJSON:{name:"toJSON",j:[V(null,!0)]}});Y(th.prototype,{toJSON:{name:"toJSON",j:[V(null,!0)]}});Y(dm.prototype,{toJSON:{name:"toJSON",j:[V(null,!0)]}});Y(am.prototype,{Pc:{name:"resolveSignIn",j:[ro()]}}); Y(lm.prototype,{Ob:{name:"getSession",j:[]},dc:{name:"enroll",j:[ro(),V("displayName",!0)]},$c:{name:"unenroll",j:[X({name:"multiFactorInfo",J:"a valid multiFactorInfo",optional:!1,K:uo},V(),"multiFactorInfoIdentifier")]}});Y(ho.prototype,{clear:{name:"clear",j:[]},render:{name:"render",j:[]},verify:{name:"verify",j:[]}});Z(Gf,"parseLink",Of,[V("link")]);Z(Rn,"assertion",function(a){return new jm(a)},[qo("phone")]); (function(){if("undefined"!==typeof firebase&&firebase.INTERNAL&&firebase.INTERNAL.registerComponent){var a={ActionCodeInfo:{Operation:{EMAIL_SIGNIN:xf,PASSWORD_RESET:"PASSWORD_RESET",RECOVER_EMAIL:"RECOVER_EMAIL",REVERT_SECOND_FACTOR_ADDITION:zf,VERIFY_AND_CHANGE_EMAIL:yf,VERIFY_EMAIL:"VERIFY_EMAIL"}},Auth:un,AuthCredential:yg,Error:u};Z(a,"EmailAuthProvider",Vg,[]);Z(a,"FacebookAuthProvider",Mg,[]);Z(a,"GithubAuthProvider",Og,[]);Z(a,"GoogleAuthProvider",Qg,[]);Z(a,"TwitterAuthProvider",Sg,[]); Z(a,"OAuthProvider",M,[V("providerId")]);Z(a,"SAMLAuthProvider",Lg,[V("providerId")]);Z(a,"PhoneAuthProvider",hh,[oo()]);Z(a,"RecaptchaVerifier",ho,[X(V(),no(),"recaptchaContainer"),W("recaptchaParameters",!0),po()]);Z(a,"ActionCodeURL",Gf,[]);Z(a,"PhoneMultiFactorGenerator",Rn,[]);firebase.INTERNAL.registerComponent({name:"auth",instanceFactory:function(b){b=b.getProvider("app").getImmediate();return new un(b)},multipleInstances:!1,serviceProps:a,instantiationMode:"LAZY",type:"PUBLIC"});firebase.INTERNAL.registerComponent({name:"auth-internal", instanceFactory:function(b){b=b.getProvider("auth").getImmediate();return{getUid:r(b.getUid,b),getToken:r(b.kc,b),addAuthTokenListener:r(b.bc,b),removeAuthTokenListener:r(b.Nc,b)}},multipleInstances:!1,instantiationMode:"LAZY",type:"PRIVATE"});firebase.registerVersion("@firebase/auth","0.14.1");firebase.INTERNAL.extendNamespace({User:P})}else throw Error("Cannot find the firebase namespace; be sure to include firebase-app.js before this library.");})();}).apply(typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : {}); //# sourceMappingURL=auth.esm.js.map
import * as firebase from 'firebase'; export default class Authentication { LogIn(email, password){ firebase.auth().signInWithEmailAndPassword(email, password).catch((error)=>{ return { errorCode: error.code, errorMessage: error.message }; }) ; } SignUp(email, password){ firebase.auth().createUserWithEmailAndPassword(email, password).catch((error)=>{ return { errorCode: error.code, errorMessage: error.message }; }) ; } LogOut(){ firebase.auth().signOut(); } }
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("omi")); else if(typeof define === 'function' && define.amd) define(["omi"], factory); else if(typeof exports === 'object') exports["add-box-rounded"] = factory(require("omi")); else root["add-box-rounded"] = factory(root["Omi"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_omi__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "./esm/add-box-rounded.js"); /******/ }) /************************************************************************/ /******/ ({ /***/ "./esm/add-box-rounded.js": /*!********************************!*\ !*** ./esm/add-box-rounded.js ***! \********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; eval("\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar omi_1 = __webpack_require__(/*! omi */ \"omi\");\nvar createSvgIcon_1 = __webpack_require__(/*! ./utils/createSvgIcon */ \"./esm/utils/createSvgIcon.js\");\nexports.default = createSvgIcon_1.default(omi_1.h(\"path\", {\n d: \"M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-3 10h-3v3c0 .55-.45 1-1 1s-1-.45-1-1v-3H8c-.55 0-1-.45-1-1s.45-1 1-1h3V8c0-.55.45-1 1-1s1 .45 1 1v3h3c.55 0 1 .45 1 1s-.45 1-1 1z\"\n}), 'AddBoxRounded');\n\n\n//# sourceURL=webpack://%5Bname%5D/./esm/add-box-rounded.js?"); /***/ }), /***/ "./esm/utils/createSvgIcon.js": /*!************************************!*\ !*** ./esm/utils/createSvgIcon.js ***! \************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; eval("\nvar __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar omi_1 = __webpack_require__(/*! omi */ \"omi\");\nvar hyphenateRE = /\\B([A-Z])/g;\nvar hyphenate = function (str) {\n return str.replace(hyphenateRE, '-$1').toLowerCase();\n};\nfunction createSvgIcon(path, displayName) {\n omi_1.define(hyphenate('OIcon' + displayName), function (_) {\n return omi_1.h('svg', __assign({ viewBox: \"0 0 24 24\", title: displayName }, _.props), path);\n }, {\n css: \":host {\\n fill: currentColor;\\n width: 1em;\\n height: 1em;\\n display: inline-block;\\n vertical-align: -0.125em;\\n transition: fill 200ms cubic-bezier(0.4, 0, 0.2, 1) 0ms;\\n flex-shrink: 0;\\n user-select: none;\\n}\"\n });\n}\nexports.default = createSvgIcon;\n\n\n//# sourceURL=webpack://%5Bname%5D/./esm/utils/createSvgIcon.js?"); /***/ }), /***/ "omi": /*!******************************************************************************!*\ !*** external {"commonjs":"omi","commonjs2":"omi","amd":"omi","root":"Omi"} ***! \******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { eval("module.exports = __WEBPACK_EXTERNAL_MODULE_omi__;\n\n//# sourceURL=webpack://%5Bname%5D/external_%7B%22commonjs%22:%22omi%22,%22commonjs2%22:%22omi%22,%22amd%22:%22omi%22,%22root%22:%22Omi%22%7D?"); /***/ }) /******/ })["default"]; });
initSidebarItems({"fn":[["main_code",""]],"type":[["ArcMutStateGlobal",""]]});
import { Mamifero } from './Mamifero.js' import { protectedPeso, protectedIdade, protectedMembros } from './symbolsAnimal.js' import { protectedCorPelo } from './symbolMamifero.js' let divApp = window.document.getElementById("App") export class Lobo extends Mamifero { emitirSom() { divApp.innerHTML += "<p>Auuuuuuuuu!</p>" } }
var d3 = require('d3/d3.js'); var width = '600'; var height = '400'; var data_1 = [432, 938, 373, 946, 123]; var data_2 = [432, 938, 373, 946, 123]; function run() { // linear var min = d3.min(data_1); var max = d3.max(data_1); var linear = d3.scale.linear() .domain([min, max]) .range([0, 300]); //ordinal var index = [0, 1, 2, 3, 4]; var color = ['red', 'orange', 'yellow', 'green', 'blue']; var ordinal = d3.scale.ordinal() .domain(index) .range(color); var svg = d3.select('body .main') .style('border', '1px solid #333') .append('svg') .attr('width', width) .attr('height', height) ; var rectHeight = 20; svg.selectAll('rect') .data(data_1) .enter() .append('rect') .attr('x', 20) .attr('y', function (d, i) { return i * (rectHeight + 5) + 100; }) .attr('width', function (d) { return linear(d); }) .attr('height', rectHeight) .attr('fill', 'steelblue'); }; module.exports.run = run;
from sys import maxsize class Group: def __init__(self, name=None, header=None, footer=None, id = None): self.name = name self.header = header self.footer = footer self.id = id def __repr__(self): return "%s:%s:%s:%s" % (self.id,self.name,self.header,self.footer) def __eq__(self, other): return (self.id is None or other.id is None or self.id == other.id), self.name == other.name, self.header == other.header def id_or_max(self): if self.id: return int(self.id) else: return maxsize
Blockly.Blocks['FilterComparableEqual'] = { init: function() { this.appendDummyInput() .appendField("FilterComparableEqual"); this.appendValueInput('valName') .setCheck('String') .appendField('Name:') .appendField(new Blockly.FieldTextInput('Equality'), 'fldName'); this.appendValueInput('valFieldName') .setCheck('String') .appendField('FieldName:') .appendField(new Blockly.FieldTextInput(''), 'fldFieldName'); this.appendValueInput('valComparableType') .setCheck('String') .appendField('ComparableType:') .appendField(new Blockly.FieldTextInput(''), 'fldComparableType'); this.appendValueInput('valValue') .setCheck('String') .appendField('Value:') .appendField(new Blockly.FieldTextInput(''), 'fldValue'); this.appendValueInput('valHowToCompareValues') //.setCheck('String') .appendField('HowToCompareValues:') .appendField(new Blockly.FieldTextInput(''), 'fldHowToCompareValues'); this.setTooltip("FilterComparableEqual"); this.setHelpUrl(""); this.setOutput(true, "Filters"); } };
import React, { PureComponent } from 'react'; import classNames from 'classnames'; import PropTypes from 'prop-types'; import Icon from '../Icon/Icon'; // styles import styles from './IconButton.css'; class IconButton extends PureComponent { getIconSize() { const { size } = this.props; switch (size) { case 'small': return 16; case 'large': return 30; default: return 22; } } renderIcon() { const { glyph } = this.props; const size = this.getIconSize(); return <Icon glyph={glyph} className={styles.icon} size={size} />; } render() { const { className, theme, size, disabled, id, flat, style, active, ...otherProps } = this.props; const buttonClassName = classNames( styles.container, styles[size], { [styles.disabled]: disabled, [styles.defaultStyle]: !flat, [styles.flat]: flat, [styles[theme]]: flat, [styles.active]: active, }, className, ); return ( <button className={buttonClassName} id={id} type="button" disabled={disabled} style={style} onClick={this.props.onClick} {...otherProps} > <span className={styles.fix}> {this.renderIcon()} </span> </button> ); } } IconButton.propTypes = { id: PropTypes.string, className: PropTypes.string, style: PropTypes.object, glyph: PropTypes.string, theme: PropTypes.oneOf( ['default', 'primary', 'success', 'danger', 'info', 'warning'], ), size: PropTypes.oneOf( ['small', 'normal', 'large'], ), flat: PropTypes.bool, disabled: PropTypes.bool, active: PropTypes.bool, onClick: PropTypes.func, }; IconButton.defaultProps = { active: true, size: 'normal', flat: false, theme: 'default', disabled: false, }; export default IconButton;
module.exports = { presets: [ '@vue/app', ['@babel/preset-env', //添加 babel-preset-env 配置 { 'modules': false } ] ], plugins: [ // element官方教程 [ 'component', { 'libraryName': 'element-ui', 'styleLibraryName': 'theme-chalk' } ] ] }
const equalSubstring = require('./01') test('1', () => { expect(equalSubstring('abcd', 'bcdf', 3)).toBe(3) }) test('2', () => { expect(equalSubstring('abcd', 'cdef', 3)).toBe(1) }) test('3', () => { expect(equalSubstring('abcd', 'acde', 0)).toBe(1) }) test('4', () => { expect(equalSubstring('krrgw', 'zjxss', 19)).toBe(2) })
/* A `gpii.express.router` component that uses the standard renderer to display the template found at `that.options.templateKey`. The handlebars context will be generated from the component itself and the rules found in `options.rules.contextToExpose`. These are used in the same way as in the `dispatcher`, i.e. the component's `model` and the incoming `request` object are the only things available as a starting point for your rules. By default, the request (path) and query parameters are exposed. This is particularly relevant when working with `initBlock` instances, where you might want to incorporate `req.params.code` or another variable into your model. Assuming you are using the defaults here, any components created using the `initBlock` helper will have `options.req` set. This component will only work if you have set up the `gpii.express.hb` middleware in your `gpii.express` instance. If you want to expose request or model variables to handlebars, you will also need to have rules like the following in your `gpii.express.hb` component's definition: handlebars: { type: "gpii.express.hb", options: { components: { initBlock: { options: { contextToOptionsRules: { req: "req" } } } } } }, */ "use strict"; var fluid = fluid || require("infusion"); var gpii = fluid.registerNamespace("gpii"); fluid.registerNamespace("gpii.express.user.api.singleTemplateRouter"); gpii.express.user.api.singleTemplateRouter.renderForm = function (that, request, response) { var generatedContext = fluid.model.transformWithRules({ model: that.model, req: request}, that.options.rules.contextToExpose); response.status(200).render(that.options.templateKey, generatedContext); }; fluid.defaults("gpii.express.user.api.singleTemplateRouter", { gradeNames: ["gpii.express.router"], path: "/", method: "get", rules: { contextToExpose: { "req": { "params": "req.params", "query": "req.query" } } }, invokers: { route: { funcName: "gpii.express.user.api.singleTemplateRouter.renderForm", args: ["{that}", "{arguments}.0", "{arguments}.1"] // request, response } } });
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Custom binding for the tts API. var binding = require('binding').Binding.create('tts'); var ttsNatives = requireNative('tts'); var GetNextTTSEventId = ttsNatives.GetNextTTSEventId; var chromeHidden = requireNative('chrome_hidden').GetChromeHidden(); var sendRequest = require('sendRequest').sendRequest; var lazyBG = requireNative('lazy_background_page'); binding.registerCustomHook(function(api) { var apiFunctions = api.apiFunctions; var tts = api.compiledApi; chromeHidden.tts = { handlers: {} }; function ttsEventListener(event) { var eventHandler = chromeHidden.tts.handlers[event.srcId]; if (eventHandler) { eventHandler({ type: event.type, charIndex: event.charIndex, errorMessage: event.errorMessage }); if (event.isFinalEvent) { delete chromeHidden.tts.handlers[event.srcId]; // Balanced in 'speak' handler. lazyBG.DecrementKeepaliveCount(); } } } // This file will get run if an extension needs the ttsEngine permission, but // it doesn't necessarily have the tts permission. If it doesn't, trying to // add a listener to chrome.tts.onEvent will fail. // See http://crbug.com/122474. try { tts.onEvent.addListener(ttsEventListener); } catch (e) {} apiFunctions.setHandleRequest('speak', function() { var args = arguments; if (args.length > 1 && args[1] && args[1].onEvent) { var id = GetNextTTSEventId(); args[1].srcId = id; chromeHidden.tts.handlers[id] = args[1].onEvent; // Keep the page alive until the event finishes. // Balanced in eventHandler. lazyBG.IncrementKeepaliveCount(); } sendRequest(this.name, args, this.definition.parameters); return id; }); }); exports.binding = binding.generate();
#!/usr/bin/env python3 # Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Run a voice recognizer that uses the Google Assistant Library and TTS, with customized commands for interacting with OpenHAB 2 via REST The Google Assistant Library has direct access to the audio API, so this Python code doesn't need to record audio. Hot word detection "OK, Google" and button push are supported. The Google Assistant Library can be installed with: env/bin/pip install google-assistant-library==0.0.2 It is available for Raspberry Pi 2/3 only; Pi Zero is not supported. Modified from Google AIY demo scripts by David Vargas (https://github.com/dvcarrillo) """ import logging import subprocess import threading import requests import sys import aiy.assistant.auth_helpers import aiy.assistant.device_helpers import aiy.audio import aiy.voicehat from google.assistant.library import Assistant from google.assistant.library.event import EventType # ---- CONFIGURATION ---- # openHAB server location openhab_ip = "localhost" openhab_port = "8080" # Set the group containing all the lights all_lights_group = 'Lights_ALL' # Set the Items on OpenHAB related to your light bulbs # The lights_ids array will be used for identifying each light in the spoken commands light_colors = ['hue_0210_00178828e0d0_1_color'] light_color_temps = ['hue_0210_00178828e0d0_1_color_temperature'] lights_ids = ['office'] # Example: "turn on the office light" # Hotwords that triggers the OpenHAB actions custom_hotword = 'home' # Show debug information (0 = false, 1 = true) debug = 1 # ----------------------- # The en-GB voice is clearer than the default en-US aiy.i18n.set_language_code('en-GB') logging.basicConfig( level=logging.INFO, format="[%(asctime)s] %(levelname)s:%(name)s:%(message)s" ) # -- OpenHAB 2 commands using OpenHAB REST API -- def openhab_send(item, state): url = 'http://' + openhab_ip + ':' + openhab_port + '/rest/items/' + item headers = { 'content-type': 'text/plain', 'accept': 'application/json' } r = requests.post(url, headers=headers, data=state) if (debug): print('REQUEST [POST]: ' + url + ' STATE: ' + state) if r.status_code == 200: aiy.audio.say('OK') elif r.status_code == 400: if (debug): print('ERROR [HTTP 400]: ' + r.text) aiy.audio.say('There has been an error: bad command') elif r.status_code == 404: if (debug): print('ERROR [HTTP 404]: ' + r.text) aiy.audio.say('There has been an error: unknown item') else: aiy.audio.say('Command failed') def openhab_get_state(item): url = 'http://' + openhab_ip + ':' + openhab_port + '/rest/items/' + item + '/state' r = requests.get(url) return r.text # -- Power management commands -- def power_off_pi(): aiy.audio.say('Powering off the system. Good bye!') subprocess.call('sudo shutdown now', shell=True) def reboot_pi(): aiy.audio.say('Rebooting the system. Hold on!') subprocess.call('sudo reboot', shell=True) def not_recognized(): aiy.audio.say('Sorry, I cannot do that yet') def device_not_found(): aiy.audio.say('Sorry, I don\'t know that device') def test_speech(): aiy.audio.say('Hello. This is a Text to Speech test.') # -- Helper functions -- def any_idx(iterable): idx = 0 for element in iterable: if element: return idx else: idx = idx + 1 # -- Class MyAssistant -- class MyAssistant(object): """ An assistant that runs in the background. The Google Assistant Library event loop blocks the running thread entirely. To support the button trigger, we need to run the event loop in a separate thread. Otherwise, the on_button_pressed() method will never get a chance to be invoked. """ def __init__(self): self._task = threading.Thread(target=self._run_task) self._can_start_conversation = False self._assistant = None def start(self): """ Starts the assistant. Starts the assistant event loop and begin processing events. """ self._task.start() def _run_task(self): credentials = aiy.assistant.auth_helpers.get_assistant_credentials() model_id, device_id = aiy.assistant.device_helpers.get_ids(credentials) with Assistant(credentials, model_id) as assistant: self._assistant = assistant for event in assistant.start(): self._process_event(event) # State management and event processing def _process_event(self, event): status_ui = aiy.voicehat.get_status_ui() if event.type == EventType.ON_START_FINISHED: status_ui.status('ready') self._can_start_conversation = True # Start the voicehat button trigger. aiy.voicehat.get_button().on_press(self._on_button_pressed) if sys.stdout.isatty(): print('\nSay "OK, Google" or press the button, then speak. ' '\nTrigger the openHAB actions by saying \"' + custom_hotword + '\" at the beginning of each command.' '\nPress Ctrl+C to quit.\n') elif event.type == EventType.ON_CONVERSATION_TURN_STARTED: self._can_start_conversation = False status_ui.status('listening') elif event.type == EventType.ON_END_OF_UTTERANCE: status_ui.status('thinking') elif event.type == EventType.ON_RECOGNIZING_SPEECH_FINISHED and event.args: print('You said:', event.args['text']) text = event.args['text'].lower() # CHECK HOTWORD if text.startswith(custom_hotword): self._assistant.stop_conversation() text = text + " " # CHECK ACTION # Power, turn, set, change if any(token in text for token in (' turn ', ' power ', ' set ', ' change ')): # CHECK DEVICE # For all the lights if ' all ' in text and ' lights ' in text: if ' on ' in text: openhab_send(all_lights_group, 'ON') elif ' off ' in text: openhab_send(all_lights_group, 'OFF') else: not_recognized() # For a specific light elif ' light ' in text: # Get the index of the mentioned item in the light arrays idx = any_idx(token in text for token in lights_ids) if (idx != None): direct_to_color = light_colors[idx] direct_to_color_temp = light_color_temps[idx] current_state = openhab_get_state(direct_to_color).split(',') if ' on ' in text: openhab_send(direct_to_color, 'ON') elif ' off ' in text: openhab_send(direct_to_color, 'OFF') elif ' red ' in text: new_state = "0,100," + current_state[2] openhab_send(direct_to_color, new_state) elif ' yellow ' in text: new_state = "100,100," + current_state[2] openhab_send(direct_to_color, new_state) elif ' blue ' in text: new_state = "260,100," + current_state[2] openhab_send(direct_to_color, new_state) elif ' pink ' in text: new_state = "340,100," + current_state[2] openhab_send(direct_to_color, new_state) elif ' green ' in text: new_state = "140,100," + current_state[2] openhab_send(direct_to_color, new_state) elif ' cool ' in text: openhab_send(direct_to_color_temp, "0") elif ' warm ' in text: openhab_send(direct_to_color_temp, "100") elif ' natural ' in text: openhab_send(direct_to_color_temp, "50") else: not_recognized() else: device_not_found() # For the system elif ' system ' in text: if ' off ' in text: power_off_pi() else: not_recognized() # Increase, raise elif any(token in text for token in (' increase ', ' raise ')): if ' brightness ' in text and 'light' in text: idx = any_idx(token in text for token in lights_ids) if (idx != None): direct_to_color = light_colors[idx] current_state = openhab_get_state(direct_to_color).split(',') new_brightness = int(current_state[2]) + 25 if (new_brightness > 100): new_brightness = 100 new_state = current_state[0] + ',' + current_state[1] + ',' + str(new_brightness) openhab_send(direct_to_color, new_state) else: device_not_found() else: not_recognized() # Decrease, reduce elif any(token in text for token in (' decrease ', ' reduce ')): if ' brightness ' in text and 'light' in text: idx = any_idx(token in text for token in lights_ids) if (idx != None): direct_to_color = light_colors[idx] current_state = openhab_get_state(direct_to_color).split(',') new_brightness = int(current_state[2]) - 25 if (new_brightness < 0): new_brightness = 0 new_state = current_state[0] + ',' + current_state[1] + ',' + str(new_brightness) openhab_send(direct_to_color, new_state) else: device_not_found() else: not_recognized() # Reboot, restart elif any(token in text for token in (' reboot ', ' restart ')): if ' system ' in text: reboot_pi() else: not_recognized() elif event.type == EventType.ON_CONVERSATION_TURN_FINISHED: status_ui.status('ready') self._can_start_conversation = True elif event.type == EventType.ON_ASSISTANT_ERROR and event.args and event.args['is_fatal']: sys.exit(1) def _on_button_pressed(self): # Check if we can start a conversation. 'self._can_start_conversation' # is False when either: # 1. The assistant library is not yet ready; OR # 2. The assistant library is already in a conversation. if self._can_start_conversation: self._assistant.start_conversation() def main(): MyAssistant().start() if __name__ == '__main__': main()
var searchData= [ ['is_5fusing_5f_228',['is_using_',['../classmercury_1_1_port_handler.html#acd0f51362140dd0773432d6cb48653ab',1,'mercury::PortHandler']]] ];
import response from "./response"; import moduleHelper from "./module-helper"; export default { WXShowToast(title, icon, duration, mask, s, f, c){ wx.showToast({ title, icon, duration, mask:Boolean(mask), ...response.handleText(s,f,c) }); }, WXHideToast(s, f, c){ wx.hideToast({ ...response.handleText(s,f,c) }); }, WXShowModal(conf,s, f, c){ wx.showModal({ ...JSON.parse(conf), ...response.handle(response.modalFormat,s,f,c) }); }, WXShowLoading(conf,s, f, c){ wx.showLoading({ ...JSON.parse(conf), ...response.handleText(s,f,c) }); }, WXHideLoading(s, f, c){ wx.hideLoading({ ...response.handleText(s,f,c) }); } }
import React, { Component } from 'react'; import { bool, string } from 'prop-types'; import { compose } from 'redux'; import { FormattedMessage, injectIntl, intlShape } from '../../util/reactIntl'; import { Field, Form as FinalForm } from 'react-final-form'; import isEqual from 'lodash/isEqual'; import classNames from 'classnames'; import { ensureCurrentUser } from '../../util/data'; import { propTypes } from '../../util/types'; import * as validators from '../../util/validators'; import { isUploadImageOverLimitError } from '../../util/errors'; import { Form, Avatar, Button, ImageFromFile, IconSpinner, FieldTextInput } from '../../components'; import css from './ProfileSettingsForm.css'; import SocialMediaField from '../../custom/organisms/SocialMediaField'; const ACCEPT_IMAGES = 'image/*'; const UPLOAD_CHANGE_DELAY = 2000; // Show spinner so that browser has time to load img srcset class ProfileSettingsFormComponent extends Component { constructor(props) { super(props); this.uploadDelayTimeoutId = null; this.state = { uploadDelay: false }; this.submittedValues = {}; } componentDidUpdate(prevProps) { // Upload delay is additional time window where Avatar is added to the DOM, // but not yet visible (time to load image URL from srcset) if (prevProps.uploadInProgress && !this.props.uploadInProgress) { this.setState({ uploadDelay: true }); this.uploadDelayTimeoutId = window.setTimeout(() => { this.setState({ uploadDelay: false }); }, UPLOAD_CHANGE_DELAY); } } componentWillUnmount() { window.clearTimeout(this.uploadDelayTimeoutId); } render() { return ( <FinalForm {...this.props} render={fieldRenderProps => { const { className, currentUser, handleSubmit, intl, invalid, onImageUpload, pristine, profileImage, rootClassName, updateInProgress, updateProfileError, uploadImageError, uploadInProgress, form, values, } = fieldRenderProps; const user = ensureCurrentUser(currentUser); // First name const firstNameLabel = intl.formatMessage({ id: 'ProfileSettingsForm.firstNameLabel', }); const firstNamePlaceholder = intl.formatMessage({ id: 'ProfileSettingsForm.firstNamePlaceholder', }); const firstNameRequiredMessage = intl.formatMessage({ id: 'ProfileSettingsForm.firstNameRequired', }); const firstNameRequired = validators.required(firstNameRequiredMessage); // Last name const lastNameLabel = intl.formatMessage({ id: 'ProfileSettingsForm.lastNameLabel', }); const lastNamePlaceholder = intl.formatMessage({ id: 'ProfileSettingsForm.lastNamePlaceholder', }); const lastNameRequiredMessage = intl.formatMessage({ id: 'ProfileSettingsForm.lastNameRequired', }); const lastNameRequired = validators.required(lastNameRequiredMessage); // Bio const bioLabel = intl.formatMessage({ id: 'ProfileSettingsForm.bioLabel', }); const bioPlaceholder = intl.formatMessage({ id: 'ProfileSettingsForm.bioPlaceholder', }); const uploadingOverlay = uploadInProgress || this.state.uploadDelay ? ( <div className={css.uploadingImageOverlay}> <IconSpinner /> </div> ) : null; const hasUploadError = !!uploadImageError && !uploadInProgress; const errorClasses = classNames({ [css.avatarUploadError]: hasUploadError }); const transientUserProfileImage = profileImage.uploadedImage || user.profileImage; const transientUser = { ...user, profileImage: transientUserProfileImage }; // Ensure that file exists if imageFromFile is used const fileExists = !!profileImage.file; const fileUploadInProgress = uploadInProgress && fileExists; const delayAfterUpload = profileImage.imageId && this.state.uploadDelay; const imageFromFile = fileExists && (fileUploadInProgress || delayAfterUpload) ? ( <ImageFromFile id={profileImage.id} className={errorClasses} rootClassName={css.uploadingImage} aspectRatioClassName={css.squareAspectRatio} file={profileImage.file} > {uploadingOverlay} </ImageFromFile> ) : null; // Avatar is rendered in hidden during the upload delay // Upload delay smoothes image change process: // responsive img has time to load srcset stuff before it is shown to user. const avatarClasses = classNames(errorClasses, css.avatar, { [css.avatarInvisible]: this.state.uploadDelay, }); const avatarComponent = !fileUploadInProgress && profileImage.imageId ? ( <Avatar className={avatarClasses} renderSizes="(max-width: 767px) 96px, 240px" user={transientUser} disableProfileLink /> ) : null; const chooseAvatarLabel = profileImage.imageId || fileUploadInProgress ? ( <div className={css.avatarContainer}> {imageFromFile} {avatarComponent} <div className={css.changeAvatar}> <FormattedMessage id="ProfileSettingsForm.changeAvatar" /> </div> </div> ) : ( <div className={css.avatarPlaceholder}> <div className={css.avatarPlaceholderText}> <FormattedMessage id="ProfileSettingsForm.addYourProfilePicture" /> </div> <div className={css.avatarPlaceholderTextMobile}> <FormattedMessage id="ProfileSettingsForm.addYourProfilePictureMobile" /> </div> </div> ); const submitError = updateProfileError ? ( <div className={css.error}> <FormattedMessage id="ProfileSettingsForm.updateProfileFailed" /> </div> ) : null; const classes = classNames(rootClassName || css.root, className); const submitInProgress = updateInProgress; const submittedOnce = Object.keys(this.submittedValues).length > 0; const pristineSinceLastSubmit = submittedOnce && isEqual(values, this.submittedValues); const submitDisabled = invalid || pristine || pristineSinceLastSubmit || uploadInProgress || submitInProgress; return ( <Form className={classes} onSubmit={e => { this.submittedValues = values; handleSubmit(e); }} > <div className={css.sectionContainer}> <h3 className={css.sectionTitle}> <FormattedMessage id="ProfileSettingsForm.yourProfilePicture" /> </h3> <Field accept={ACCEPT_IMAGES} id="profileImage" name="profileImage" label={chooseAvatarLabel} type="file" form={null} uploadImageError={uploadImageError} disabled={uploadInProgress} > {fieldProps => { const { accept, id, input, label, disabled, uploadImageError } = fieldProps; const { name, type } = input; const onChange = e => { const file = e.target.files[0]; form.change(`profileImage`, file); form.blur(`profileImage`); if (file != null) { const tempId = `${file.name}_${Date.now()}`; onImageUpload({ id: tempId, file }); } }; let error = null; if (isUploadImageOverLimitError(uploadImageError)) { error = ( <div className={css.error}> <FormattedMessage id="ProfileSettingsForm.imageUploadFailedFileTooLarge" /> </div> ); } else if (uploadImageError) { error = ( <div className={css.error}> <FormattedMessage id="ProfileSettingsForm.imageUploadFailed" /> </div> ); } return ( <div className={css.uploadAvatarWrapper}> <label className={css.label} htmlFor={id}> {label} </label> <input accept={accept} id={id} name={name} className={css.uploadAvatarInput} disabled={disabled} onChange={onChange} type={type} /> {error} </div> ); }} </Field> <div className={css.tip}> <FormattedMessage id="ProfileSettingsForm.tip" /> </div> <div className={css.fileInfo}> <FormattedMessage id="ProfileSettingsForm.fileInfo" /> </div> </div> <div className={css.sectionContainer}> <h3 className={css.sectionTitle}> <FormattedMessage id="ProfileSettingsForm.yourName" /> </h3> <div className={css.nameContainer}> <FieldTextInput className={css.firstName} type="text" id="firstName" name="firstName" label={firstNameLabel} placeholder={firstNamePlaceholder} validate={firstNameRequired} /> <FieldTextInput className={css.lastName} type="text" id="lastName" name="lastName" label={lastNameLabel} placeholder={lastNamePlaceholder} validate={lastNameRequired} /> </div> </div> {/* <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQIt14XdWoi9ztDZ3_KWgDFMToqGPtEpA7om9IQnL2VJ-kt4KH8Ig&s" /> */} <SocialMediaField handleSubmit={handleSubmit} {...this.props} /> <div className={classNames(css.sectionContainer, css.lastSection)}> <h3 className={css.sectionTitle}> <FormattedMessage id="ProfileSettingsForm.bioHeading" /> </h3> <FieldTextInput type="textarea" id="bio" name="bio" label={bioLabel} placeholder={bioPlaceholder} /> <p className={css.bioInfo}> <FormattedMessage id="ProfileSettingsForm.bioInfo" /> </p> </div> {submitError} <Button className={css.submitButton} type="submit" inProgress={submitInProgress} disabled={submitDisabled} ready={pristineSinceLastSubmit} > <FormattedMessage id="ProfileSettingsForm.saveChanges" /> </Button> </Form> ); }} /> ); } } ProfileSettingsFormComponent.defaultProps = { rootClassName: null, className: null, uploadImageError: null, updateProfileError: null, updateProfileReady: false, }; ProfileSettingsFormComponent.propTypes = { rootClassName: string, className: string, uploadImageError: propTypes.error, uploadInProgress: bool.isRequired, updateInProgress: bool.isRequired, updateProfileError: propTypes.error, updateProfileReady: bool, // from injectIntl intl: intlShape.isRequired, }; const ProfileSettingsForm = compose(injectIntl)(ProfileSettingsFormComponent); ProfileSettingsForm.displayName = 'ProfileSettingsForm'; export default ProfileSettingsForm;
import React, { Component } from 'react' import { connect } from 'react-redux' import PropTypes from 'prop-types' import { bindActionCreators } from 'redux' import cx from 'classnames' import { actions, selectors } from 'src/custom-lists' import extStyles from './Index.css' import CreateListForm from './CreateListForm' import ListItem from './list-item' import DeleteConfirmModal from 'src/overview/delete-confirm-modal/components/DeleteConfirmModal' import { actions as filterActs, selectors as filters } from 'src/search-filters' import { selectors as sidebar } from 'src/overview/sidebar-left' import { auth, contentSharing } from 'src/util/remote-functions-background' import { StaticListItem } from './static-list-item' import { show } from 'src/overview/modals/actions' import { SPECIAL_LIST_NAMES } from '@worldbrain/memex-storage/lib/lists/constants' const styles = require('./Index.css') class ListContainer extends Component { static propTypes = { getListFromDB: PropTypes.func.isRequired, inboxUnreadCount: PropTypes.number.isRequired, getInboxUnreadCount: PropTypes.func.isRequired, lists: PropTypes.array.isRequired, specialLists: PropTypes.array.isRequired, handleEditBtnClick: PropTypes.func.isRequired, handleAllSavedClick: PropTypes.func.isRequired, isListFilterActive: PropTypes.bool.isRequired, isDeleteConfShown: PropTypes.bool.isRequired, resetListDeleteModal: PropTypes.func.isRequired, handleCrossBtnClick: PropTypes.func.isRequired, handleListItemClick: PropTypes.func.isRequired, createPageList: PropTypes.func.isRequired, updateList: PropTypes.func.isRequired, handleAddPageList: PropTypes.func.isRequired, handleDeleteList: PropTypes.func.isRequired, toggleCreateListForm: PropTypes.func.isRequired, showCreateList: PropTypes.bool.isRequired, showListShareModal: PropTypes.func.isRequired, showCommonNameWarning: PropTypes.bool.isRequired, isSidebarOpen: PropTypes.bool.isRequired, isSidebarLocked: PropTypes.bool.isRequired, closeCreateListForm: PropTypes.func.isRequired, resetUrlDragged: PropTypes.func.isRequired, } constructor(props) { super(props) this.state = { listName: null, updatedListName: null, showWarning: false, isPioneer: false, displayName: null, shareAccess: false, } } async componentDidMount() { this.props.getInboxUnreadCount() // Gets all the list from the DB to populate the sidebar. this.props.getListFromDB() this.getUserInfo() } async getUserInfo() { // const isPioneer = await auth.isAuthorizedForFeature('beta') // const userProfile = await auth.getUserProfile() // const displayName = userProfile ? userProfile.displayName : undefined this.setState({ isPioneer: true, // TODO: use isPioneer declared above displayName: 'John Smith', // TODO: use displayName declared above }) } setInputRef = (el) => (this.inputEl = el) handleSearchChange = (field) => (event) => { const { value } = event.target this.setState((state) => ({ ...state, [field]: value, })) } getSearchVal = (value) => value.trim().replace(/\s\s+/g, ' ') handleCreateListSubmit = (event) => { event.preventDefault() const { value } = event.target.elements.listName // value = list name this.props.createPageList( this.getSearchVal(value), this.vacateInputField, ) } vacateInputField = () => { this.setState((state) => ({ ...state, listName: null, })) } handleUpdateList = ({ id, name: oldName }, index) => (event) => { event.preventDefault() const { value } = event.target.elements.listName const newName = this.getSearchVal(value) this.props.updateList([oldName, newName], id) this.setState((state) => ({ ...state, updatedListName: null, })) } handleShareButtonClick = (i) => () => { return this.props.showListShareModal({ list: this.props.lists[i] }) } renderAllLists = () => { return this.props.lists.map((list, i) => { if (list.isEditing) { return ( <CreateListForm key={i} onCheckboxClick={this.handleUpdateList(list, i)} handleNameChange={this.handleSearchChange( 'updatedListName', )} value={ typeof this.state.updatedListName === 'string' ? this.state.updatedListName : list.name } showWarning={this.state.showWarning} setInputRef={this.setInputRef} /> ) } return ( <ListItem key={i} listId={list.id} listName={list.name} isFiltered={list.isFilterIndex} onShareButtonClick={this.handleShareButtonClick(i)} onEditButtonClick={this.props.handleEditBtnClick(i)} onListItemClick={this.props.handleListItemClick(list)} onAddPageToList={this.props.handleAddPageList(list, i)} onCrossButtonClick={this.props.handleCrossBtnClick(list, i)} resetUrlDragged={this.props.resetUrlDragged} /> ) }) } renderSpecialLists = () => [ <StaticListItem key={0} listName="All Saved" isFiltered={!this.props.isListFilterActive} onListItemClick={this.props.handleAllSavedClick} />, ...this.props.specialLists.map((list, i) => ( <StaticListItem key={i + 1} listName={list.name} isFiltered={list.isFilterIndex} onListItemClick={this.props.handleListItemClick(list)} unreadCount={ list.name === SPECIAL_LIST_NAMES.INBOX ? this.props.inboxUnreadCount : undefined } /> )), ] renderCreateList = (shouldDisplayForm, value = null) => shouldDisplayForm && ( <CreateListForm onCheckboxClick={this.handleCreateListSubmit} handleNameChange={this.handleSearchChange('listName')} value={this.state.listName} showWarning={this.props.showCommonNameWarning} setInputRef={this.setInputRef} closeCreateListForm={this.props.closeCreateListForm} /> ) render() { return ( <React.Fragment> {this.renderSpecialLists()} <div className={styles.collection} onClick={this.props.toggleCreateListForm} > <div className={cx(styles.addNew, { [styles.addNewHover]: this.props.isSidebarLocked, })} > <span className={styles.myCollection}> My Collections{' '} </span> <span className={styles.plus} /> </div> </div> {this.renderCreateList(this.props.showCreateList)} <div className={cx({ [extStyles.allLists]: this.props.isSidebarOpen, [extStyles.allListsLocked]: this.props.isSidebarLocked, })} > <div className={cx({ [extStyles.wrapper]: this.props.isSidebarOpen, [extStyles.allListsInner]: this.props.isSidebarOpen, [extStyles.wrapperLocked]: this.props .isSidebarLocked, })} > {this.props.lists.length === 0 ? ( <div> {this.renderAllLists()} <div className={extStyles.noLists}> <strong> You don't have any collections{' '} </strong> <br /> Create one with the + icon and drag and drop items into it. </div> </div> ) : ( <div>{this.renderAllLists()}</div> )} </div> </div> <DeleteConfirmModal message="Delete collection? This does not delete the pages in it" isShown={this.props.isDeleteConfShown} onClose={this.props.resetListDeleteModal} deleteDocs={this.props.handleDeleteList} /> </React.Fragment> ) } } const mapStateToProps = (state) => ({ lists: selectors.createdDisplayLists(state), specialLists: selectors.specialDisplayLists(state), isDeleteConfShown: selectors.isDeleteConfShown(state), shareModalProps: selectors.shareModalProps(state), showCreateList: selectors.showCreateListForm(state), showCommonNameWarning: selectors.showCommonNameWarning(state), isSidebarOpen: sidebar.isSidebarOpen(state), isSidebarLocked: sidebar.sidebarLocked(state), isListFilterActive: filters.listFilterActive(state), lstFilter: filters.listIdFilter(state), inboxUnreadCount: selectors.inboxUnreadCount(state), }) const mapDispatchToProps = (dispatch, ownProps) => ({ ...bindActionCreators( { resetListDeleteModal: actions.resetListDeleteModal, getListFromDB: actions.getListFromDB, createPageList: actions.createPageList, updateList: actions.updateList, toggleCreateListForm: actions.toggleCreateListForm, closeCreateListForm: actions.closeCreateListForm, resetUrlDragged: actions.resetUrlDragged, }, dispatch, ), getInboxUnreadCount: () => dispatch(actions.getInboxUnreadCount()), handleEditBtnClick: (index) => (event) => { event.preventDefault() dispatch(actions.showEditBox(index)) }, handleCrossBtnClick: ({ id }, index) => (event) => { event.preventDefault() dispatch(actions.showListDeleteModal(id, index)) }, handleListItemClick: ({ id, name, isMobileList }) => () => { dispatch( filterActs.toggleListFilter({ id, name, isMobileListFiltered: isMobileList, }), ) }, handleAddPageList: ({ id, isMobileList }, index) => (url, isSocialPost) => { if (!isMobileList) { dispatch(actions.addUrltoList(url, isSocialPost, index, id)) } }, handleAllSavedClick: () => dispatch(filterActs.delListFilter()), handleDeleteList: (e) => { e.preventDefault() dispatch(actions.deletePageList()) dispatch(filterActs.delListFilter()) }, showListShareModal: ({ list }) => dispatch( show({ modalId: 'ShareListModal', options: { list, auth: auth, contentSharing: contentSharing, isPioneer: true, isShown: true, }, }), ), }) export default connect(mapStateToProps, mapDispatchToProps)(ListContainer)
import React from 'react'; import DestinyItem from './DestinyItem'; export default class FeaturedItems extends React.Component { render() { if (this.props.items) { let items = this.props.items.map((item, i) => <li key={i}> <DestinyItem item={item} /> </li>); return <ul className="rewardSet">{items}</ul>; } return null; }; };
#!/usr/bin/env python # coding=utf-8 # Copyright 2020 The HuggingFace Team 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. """ Fine-tuning the library models for token classification. """ # You can also adapt this script on your own token classification task and datasets. Pointers for this are left as # comments. import logging import sys from custom_callbacks import * import datasets import numpy as np from datasets import ClassLabel, load_dataset, load_metric import pickle import json import time import gc import transformers from transformers import ( AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, HfArgumentParser, AdamW, TrainingArguments, get_linear_schedule_with_warmup ) from torch.utils.data import DataLoader, RandomSampler, SequentialSampler from transformers import AutoModelForSequenceClassification, AdamW from transformers.utils.versions import require_version from sklearn.metrics import precision_recall_fscore_support from torch.utils.data import TensorDataset import ipdb import torch import random import wandb from glob import glob from eval_utils import * device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # Will error if the minimal version of Transformers is not installed. Remove at your own risks. # check_min_version("4.13.0.dev0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/token-classification/requirements.txt") def seed_torch(seed=12345): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if you are using multi-GPU. torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True pos_labels_by_dataset = {'DDI':['DDI-mechanism', 'DDI-advise', 'DDI-effect','DDI-int'], 'chemprot':['CPR:4', 'CPR:6', 'CPR:5', 'CPR:9', 'CPR:3'], 'gad':['1']} def train_epoch(model, train_dataloader, optimizer, scheduler): print("") print('Training...') model.train() total_train_loss = 0 # For each batch of training data... for step, batch in enumerate(train_dataloader): # Unpack this training batch from our dataloader. # # As we unpack the batch, we'll also copy each tensor to the GPU using the # `to` method. # # `batch` contains three pytorch tensors: # [0]: input ids # [1]: attention masks # [2]: labels b_input_ids = batch[0].to(device) b_input_mask = batch[1].to(device) b_labels = batch[2].to(device) # Always clear any previously calculated gradients before performing a # backward pass. PyTorch doesn't do this automatically because # accumulating the gradients is "convenient while training RNNs". # (source: https://stackoverflow.com/questions/48001598/why-do-we-need-to-call-zero-grad-in-pytorch) model.zero_grad() # Perform a forward pass (evaluate the model on this training batch). # The documentation for this `model` function is here: # https://huggingface.co/transformers/v2.2.0/model_doc/bert.html#transformers.BertForSequenceClassification # It returns different numbers of parameters depending on what arguments # arge given and what flags are set. For our useage here, it returns # the loss (because we provided labels) and the "logits"--the model # outputs prior to activation. outputs = model(b_input_ids, token_type_ids=None, attention_mask=b_input_mask, labels=b_labels) loss, logits = outputs['loss'], outputs['logits'] wandb.log({'train_batch_loss': loss.item()}) # Accumulate the training loss over all of the batches so that we can # calculate the average loss at the end. `loss` is a Tensor containing a # single value; the `.item()` function just returns the Python value # from the tensor. total_train_loss += loss.item() # Perform a backward pass to calculate the gradients. loss.backward() # Clip the norm of the gradients to 1.0. # This is to help prevent the "exploding gradients" problem. torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) # Update parameters and take a step using the computed gradient. # The optimizer dictates the "update rule"--how the parameters are # modified based on their gradients, the learning rate, etc. optimizer.step() # Update the learning rate. scheduler.step() # Calculate the average loss over all of the batches. avg_train_loss = total_train_loss / len(train_dataloader) wandb.log({'avg_train_loss': avg_train_loss}) print("") print(" Average training loss: {0:.2f}".format(avg_train_loss)) def evaluate(model, dev_dataloader, dev_df, labels_to_id, eval_name, args, epoch): if epoch % wandb.config.epoch_eval_period == 0: print("") print("Running Validation...") id_to_labels = {i:str(l) for l,i in labels_to_id.items()} t0 = time.time() # Put the model in evaluation mode--the dropout layers behave differently # during evaluation. model.eval() # Tracking variables total_eval_accuracy = 0 total_eval_loss = 0 predictions_list = [] labels_list = [] # Evaluate data for one epoch for batch in dev_dataloader: # Unpack this training batch from our dataloader. # # As we unpack the batch, we'll also copy each tensor to the GPU using # the `to` method. # # `batch` contains three pytorch tensors: # [0]: input ids # [1]: attention masks # [2]: labels b_input_ids = batch[0].to(device) b_input_mask = batch[1].to(device) b_labels = batch[2].to(device) # Tell pytorch not to bother with constructing the compute graph during # the forward pass, since this is only needed for backprop (training). with torch.no_grad(): # Forward pass, calculate logit predictions. # token_type_ids is the same as the "segment ids", which # differentiates sentence 1 and 2 in 2-sentence tasks. # The documentation for this `model` function is here: # https://huggingface.co/transformers/v2.2.0/model_doc/bert.html#transformers.BertForSequenceClassification # Get the "logits" output by the model. The "logits" are the output # values prior to applying an activation function like the softmax. outputs = model(b_input_ids, token_type_ids=None, attention_mask=b_input_mask, labels=b_labels) loss, logits = outputs['loss'], outputs['logits'] # Accumulate the validation loss. total_eval_loss += loss.item() # Move logits and labels to CPU logits = logits.detach().cpu().numpy() label_ids = b_labels.to('cpu').numpy() # Calculate the accuracy for this batch of test sentences, and # accumulate it over all batches. pred_flat = np.argmax(logits, axis=1).flatten() labels_flat = label_ids.flatten() # total_eval_accuracy = flatten(logits, label_ids) predictions_list.extend(pred_flat) labels_list.extend(labels_flat) dataset_file = os.path.join(args.output_dir, "{}.tokens.{}.txt".format(eval_name, int(epoch))) output_predictions_file = os.path.join(args.output_dir, "{}.predictions.{}.txt".format(eval_name, int(epoch))) output_labels_file = os.path.join(args.output_dir, "{}.labels.{}.txt".format(eval_name, int(epoch))) # Save predictions with open(dataset_file, "w") as writer: for sent in dev_df['masked_sents']: writer.write(sent + "\n") with open(output_predictions_file, "w") as writer: for prediction in predictions_list: writer.write(str(id_to_labels[prediction]) + "\n") with open(output_labels_file, "w") as writer: for label in labels_list: writer.write(str(id_to_labels[label]) + "\n") # Report the final accuracy for this validation run. avg_val_accuracy = total_eval_accuracy / len(dev_dataloader) # Calculate the average loss over all of the batches. avg_val_loss = total_eval_loss / len(dev_dataloader) wandb.log({'val_accuracy': avg_val_accuracy, 'avg_val_loss': avg_val_loss}) pos_labels = pos_labels_by_dataset[wandb.config.data_name] f1 = precision_recall_fscore_support(labels_list, predictions_list, average=None) p, r, f, s = precision_recall_fscore_support(y_pred=predictions_list, y_true=labels_list, labels=[labels_to_id[l] for l in pos_labels], average='micro') metrics = {'{}_f1'.format(eval_name):f, '{}_precision'.format(eval_name):p, '{}_recall'.format(eval_name):r, '{}_class_f1s'.format(eval_name): list(f1[2])} json.dump(metrics, open(args.output_dir + '/{}.metrics.{}_results.json'.format(eval_name,epoch),'w')) hyperparameter_defaults = dict( data_name='DDI', data_dir='../data/', output_dir='../outputs/', subset_num=1, experiment_num=1, run_type='grid',#cv, grid, best, worst kfolds=1, do_train=True, do_eval=True, do_predict=False, per_device_train_batch_size=16, learning_rate=2e-5, num_train_epochs=5, weight_decay=0.1, warmup_ratio=0.06, model_name='microsoft/BiomedNLP-PubMedBERT-base-uncased-abstract', per_device_eval_batch_size=16, seed=42, logging_strategy='no', evaluation_strategy='steps', save_strategy='no', eval_steps_epochs=None, save_total_limit=0, max_seq_length=128, max_eval_samples=None, max_predict_samples=None, overwrite_output_dir=True, gradient_checkpointing=True, disable_tqdm=True, epoch_eval_period=1 ) wandb.init(config=hyperparameter_defaults, project="bertNER") config = wandb.config def train(): dataset_dir = os.path.join(wandb.config.data_dir, wandb.config.data_name) wandb_dict = dict(wandb.config) #Follow directory structure for output directory under WandB Sweep and Run ids output_dir = '/'.join([wandb.config.output_dir, wandb.config.data_name, 'plms', str(wandb.config.experiment_num), wandb.config.run_type+'.'+str(wandb.run.sweep_id), wandb.run.id]) os.makedirs(output_dir) pickle.dump(dict(wandb.config), open(os.path.join(output_dir, '{}.params.p'.format(wandb.config.run_type)), 'wb')) wandb_dict['output_dir'] = output_dir #Using WandB arguments to feed into huggingface training arguments parser = HfArgumentParser((TrainingArguments)) training_args = parser.parse_dict(wandb_dict)[0] #Setup logging logger = logging.getLogger(__name__) log_level = logging.FATAL logger.setLevel(log_level) log_level = transformers.logging.FATAL datasets.utils.logging.set_verbosity(log_level) transformers.logging.set_verbosity(log_level) transformers.logging.disable_progress_bar() logger = logging.getLogger("wandb") logger.setLevel(logging.FATAL) wandb.util.logging.disable() # # logger.info(f"Training/evaluation parameters {training_args}") # Set seed before initializing model. seed_torch(training_args.seed) tokenizer = AutoTokenizer.from_pretrained(wandb.config.model_name, do_lower_cased=True) print(len(tokenizer)) special_tokens_dict = {'additional_special_tokens': ['ENT1', 'ENT2']} num_added_toks = tokenizer.add_special_tokens(special_tokens_dict) train_df, dev_df, test_df = load_re_dataset(dataset_dir, wandb.config.subset_num) unique_labels = np.sort(train_df['label'].unique(),kind='stable') labels_to_id = {str(l):i for l,i in zip(unique_labels, range(len(unique_labels)))} num_labels = len(unique_labels) #Loading Test Dataset before k-fold CV if training_args.do_predict: test_dataset = get_re_dataset(test_df, tokenizer, labels_to_id) test_dataloader = DataLoader( test_dataset, # The validation samples. sampler=SequentialSampler(test_dataset), # Pull out batches sequentially. batch_size=wandb.config.per_device_eval_batch_size # Evaluates with this batch size. ) else: test_dataloader = None original_train_dataset = train_df.sample(len(train_df), random_state=np.random.RandomState(wandb.config.seed)).reset_index() fold_size = int(len(original_train_dataset) / wandb.config.kfolds) for fold in range(wandb.config.kfolds): if wandb.config.kfolds > 1: training_args.output_dir = os.path.join(output_dir, str(fold)) os.makedirs(training_args.output_dir) train_df = original_train_dataset[(original_train_dataset.index < fold * fold_size) | (original_train_dataset.index >= (fold + 1) * fold_size)] dev_df = original_train_dataset[(original_train_dataset.index >= fold * fold_size) & (original_train_dataset.index < (fold + 1) * fold_size)] assert len(dev_df) == fold_size assert len(train_df) == len(original_train_dataset) - fold_size if wandb_dict['eval_steps_epochs'] is not None: training_args.eval_steps = wandb_dict['eval_steps_epochs'] * ( int(len(original_train_dataset) / training_args.per_device_train_batch_size) + 1) train_dataset = get_re_dataset(train_df, tokenizer, labels_to_id) dev_dataset = get_re_dataset(dev_df, tokenizer, labels_to_id) train_dataloader = DataLoader( train_dataset, # The training samples. sampler=RandomSampler(train_dataset), # Select batches randomly batch_size=wandb.config.per_device_train_batch_size # Trains with this batch size. ) dev_dataloader = DataLoader( dev_dataset, # The validation samples. sampler=SequentialSampler(dev_dataset), # Pull out batches sequentially. batch_size=wandb.config.per_device_eval_batch_size # Evaluates with this batch size. ) model = AutoModelForSequenceClassification.from_pretrained(wandb.config.model_name, num_labels=num_labels, output_attentions=False, # Whether the model returns attentions weights. output_hidden_states=False, # Whether the model returns all hidden-states. ) model.resize_token_embeddings(len(tokenizer)) model.gradient_checkpointing_enable() model.to(device) print('Learning_rate = ', wandb.config.learning_rate) optimizer = AdamW(model.parameters(), lr=wandb.config.learning_rate, weight_decay=wandb.config.weight_decay ) epochs = wandb.config.num_train_epochs warmup_ratio = wandb.config.warmup_ratio # ipdb.set_trace() print('epochs =>', epochs) # Total number of training steps is [number of batches] x [number of epochs]. # (Note that this is not the same as the number of training samples). total_steps = len(train_dataloader) * epochs num_warmup_steps = warmup_ratio * total_steps # Create the learning rate scheduler. scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=num_warmup_steps, # Default value in run_glue.py num_training_steps=total_steps) # Training if training_args.do_train: for epoch_i in range(1, epochs+1): print('======== Epoch {:} / {:} ========'.format(epoch_i, epochs)) train_epoch(model, train_dataloader, optimizer, scheduler) evaluate(model, dev_dataloader, dev_df, labels_to_id, 'dev', training_args, epoch_i) if training_args.do_predict: evaluate(model, test_dataloader, test_df, labels_to_id, 'test', training_args, epoch_i) # wandb.log({'training_data_size': len(train_dataset)}) # if training_args.save_strategy != 'no': model.save_pretrained(output_dir + '/trained_model_fold_{}'.format(fold)) del model time.sleep(2) gc.collect() time.sleep(2) torch.cuda.empty_cache() if wandb.config.run_type == 'cv': results_by_epoch = [] #Aggregate results and compute metric for epoch in range(wandb.config.num_train_epochs // wandb.config.epoch_eval_period): epoch += 1 # Starts at epoch *= wandb.config.epoch_eval_period tokens = [] labels = [] preds = [] for kfold in range(wandb.config.kfolds): tokens.extend(open(output_dir + '/{}/dev.tokens.{}.txt'.format(kfold, epoch), 'r').readlines()) labels.extend(open(output_dir + '/{}/dev.labels.{}.txt'.format(kfold, epoch), 'r').readlines()) preds.extend(open(output_dir + '/{}/dev.predictions.{}.txt'.format(kfold, epoch), 'r').readlines()) tok_file = open(output_dir + '/dev.tokens.{}.txt'.format(epoch), 'w') labels_file = open(output_dir + '/dev.labels.{}.txt'.format(epoch), 'w') preds_file = open(output_dir + '/dev.predictions.{}.txt'.format(epoch), 'w') tok_file.writelines(tokens) labels_file.writelines(labels) preds_file.writelines(preds) tok_file.close() labels_file.close() preds_file.close() preds = [labels_to_id[p.strip()] for p in preds] labels = [labels_to_id[l.strip()] for l in labels] pos_labels = pos_labels_by_dataset[wandb.config.data_name] p, r, f, s = precision_recall_fscore_support(y_pred=preds, y_true=labels, labels=[labels_to_id[l] for l in pos_labels], average='micro') results_by_epoch.append((f, p, r, wandb.run.id, epoch, training_args.per_device_train_batch_size, training_args.learning_rate, training_args.num_train_epochs, wandb.config.model_name, training_args.weight_decay, training_args.warmup_ratio )) results_by_epoch = pd.DataFrame(results_by_epoch, columns=['f1', 'precision', 'recall', 'run_id', 'epoch', 'batch_size', 'learning_rate', 'num_train_epochs', 'model_name', 'weight_decay', 'warmup_ratio' ] ) results_by_epoch.to_csv(output_dir+'/dev.metrics') elif wandb.config.run_type == 'grid': save_plm_metric_table(output_dir, training_args) save_plm_metric_table(output_dir, training_args, 'test') if __name__ == "__main__": train()
""" ASGI config for server project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ """ import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import apps.chat.routing os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings") application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( apps.chat.routing.websocket_urlpatterns ) ), })
// @flow import { connect } from 'react-redux'; import EditContract from './EditContract'; const mapStateToProps = (state, ownProps) => { const { objectId } = state.contract.contractList; return { objectId, contractLayer: ownProps.contractLayer, currentLayer: ownProps.currentLayer, fields: ownProps.fields, }; }; const EditContractContrainer = (connect(mapStateToProps)(EditContract): any); export default EditContractContrainer;
import ensureArray from 'ensure-array'; import * as parser from 'gcode-parser'; import _ from 'lodash'; import SerialConnection from '../../lib/SerialConnection'; import EventTrigger from '../../lib/EventTrigger'; import Feeder from '../../lib/Feeder'; import Sender, { SP_TYPE_CHAR_COUNTING } from '../../lib/Sender'; import Workflow, { WORKFLOW_STATE_IDLE, WORKFLOW_STATE_PAUSED, WORKFLOW_STATE_RUNNING } from '../../lib/Workflow'; import ensurePositiveNumber from '../../lib/ensure-positive-number'; import evaluateExpression from '../../lib/evaluate-expression'; import logger from '../../lib/logger'; import translateExpression from '../../lib/translate-expression'; import config from '../../services/configstore'; import monitor from '../../services/monitor'; import taskRunner from '../../services/taskrunner'; import store from '../../store'; import { WRITE_SOURCE_CLIENT, WRITE_SOURCE_FEEDER } from '../constants'; import GrblRunner from './GrblRunner'; import { GRBL, GRBL_ACTIVE_STATE_RUN, GRBL_ACTIVE_STATE_HOLD, GRBL_REALTIME_COMMANDS, GRBL_ALARMS, GRBL_ERRORS, GRBL_SETTINGS } from './constants'; // % commands const WAIT = '%wait'; const log = logger('controller:Grbl'); const noop = _.noop; class GrblController { type = GRBL; // CNCEngine engine = null; // Sockets sockets = {}; // Connection connection = null; connectionEventListener = { data: (data) => { log.silly(`< ${data}`); this.runner.parse('' + data); }, close: (err) => { this.ready = false; if (err) { log.warn(`Disconnected from serial port "${this.options.port}":`, err); } this.close(err => { // Remove controller from store const port = this.options.port; store.unset(`controllers[${JSON.stringify(port)}]`); // Destroy controller this.destroy(); }); }, error: (err) => { this.ready = false; if (err) { log.error(`Unexpected error while reading/writing serial port "${this.options.port}":`, err); } } }; // Grbl controller = null; ready = false; initialized = false; state = {}; settings = {}; queryTimer = null; actionMask = { queryParserState: { state: false, // wait for a message containing the current G-code parser modal state reply: false // wait for an `ok` or `error` response }, queryStatusReport: false, // Respond to user input replyParserState: false, // $G replyStatusReport: false // ? }; actionTime = { queryParserState: 0, queryStatusReport: 0, senderFinishTime: 0 }; // Event Trigger event = null; // Feeder feeder = null; // Sender sender = null; // Workflow workflow = null; constructor(engine, options) { if (!engine) { throw new Error('engine must be specified'); } this.engine = engine; const { port, baudrate, rtscts } = { ...options }; this.options = { ...this.options, port: port, baudrate: baudrate, rtscts: rtscts }; // Connection this.connection = new SerialConnection({ path: port, baudRate: baudrate, rtscts: rtscts, writeFilter: (data) => { const line = data.trim(); if (!line) { return data; } { // Grbl settings: $0-$255 const r = line.match(/^(\$\d{1,3})=([\d\.]+)$/); if (r) { const name = r[1]; const value = Number(r[2]); if ((name === '$13') && (value >= 0) && (value <= 65535)) { const nextSettings = { ...this.runner.settings, settings: { ...this.runner.settings.settings, [name]: value ? '1' : '0' } }; this.runner.settings = nextSettings; // enforce change } } } return data; } }); // Event Trigger this.event = new EventTrigger((event, trigger, commands) => { log.debug(`EventTrigger: event="${event}", trigger="${trigger}", commands="${commands}"`); if (trigger === 'system') { taskRunner.run(commands); } else { this.command('gcode', commands); } }); // Feeder this.feeder = new Feeder({ dataFilter: (line, context) => { // Remove comments that start with a semicolon `;` line = line.replace(/\s*;.*/g, '').trim(); context = this.populateContext(context); if (line[0] === '%') { // %wait if (line === WAIT) { log.debug('Wait for the planner to empty'); return 'G4 P0.5'; // dwell } // Expression // %_x=posx,_y=posy,_z=posz evaluateExpression(line.slice(1), context); return ''; } // line="G0 X[posx - 8] Y[ymax]" // > "G0 X2 Y50" line = translateExpression(line, context); const data = parser.parseLine(line, { flatten: true }); const words = ensureArray(data.words); { // Program Mode: M0, M1 const programMode = _.intersection(words, ['M0', 'M1'])[0]; if (programMode === 'M0') { log.debug('M0 Program Pause'); this.feeder.hold({ data: 'M0' }); // Hold reason } else if (programMode === 'M1') { log.debug('M1 Program Pause'); this.feeder.hold({ data: 'M1' }); // Hold reason } } // M6 Tool Change if (_.includes(words, 'M6')) { log.debug('M6 Tool Change'); this.feeder.hold({ data: 'M6' }); // Hold reason // Surround M6 with parentheses to ignore unsupported command error line = '(M6)'; } return line; } }); this.feeder.on('data', (line = '', context = {}) => { if (this.isClose()) { log.error(`Serial port "${this.options.port}" is not accessible`); return; } if (this.runner.isAlarm()) { this.feeder.reset(); log.warn('Stopped sending G-code commands in Alarm mode'); return; } line = String(line).trim(); if (line.length === 0) { return; } this.emit('serialport:write', line + '\n', { ...context, source: WRITE_SOURCE_FEEDER }); this.connection.write(line + '\n'); log.silly(`> ${line}`); // atmelino // this prints every line of gcode in terminal log.error('this.feeder.on' + line); }); this.feeder.on('hold', noop); this.feeder.on('unhold', noop); // Sender this.sender = new Sender(SP_TYPE_CHAR_COUNTING, { // Deduct the buffer size to prevent from buffer overrun bufferSize: (128 - 8), // The default buffer size is 128 bytes dataFilter: (line, context) => { // Remove comments that start with a semicolon `;` line = line.replace(/\s*;.*/g, '').trim(); context = this.populateContext(context); const { sent, received } = this.sender.state; if (line[0] === '%') { // %wait if (line === WAIT) { log.debug(`Wait for the planner to empty: line=${sent + 1}, sent=${sent}, received=${received}`); this.sender.hold({ data: WAIT }); // Hold reason return 'G4 P0.5'; // dwell } // Expression // %_x=posx,_y=posy,_z=posz evaluateExpression(line.slice(1), context); return ''; } // line="G0 X[posx - 8] Y[ymax]" // > "G0 X2 Y50" line = translateExpression(line, context); const data = parser.parseLine(line, { flatten: true }); const words = ensureArray(data.words); { // Program Mode: M0, M1 const programMode = _.intersection(words, ['M0', 'M1'])[0]; if (programMode === 'M0') { log.debug(`M0 Program Pause: line=${sent + 1}, sent=${sent}, received=${received}`); this.workflow.pause({ data: 'M0' }); } else if (programMode === 'M1') { log.debug(`M1 Program Pause: line=${sent + 1}, sent=${sent}, received=${received}`); this.workflow.pause({ data: 'M1' }); } } // M6 Tool Change if (_.includes(words, 'M6')) { log.debug(`M6 Tool Change: line=${sent + 1}, sent=${sent}, received=${received}`); this.workflow.pause({ data: 'M6' }); // Surround M6 with parentheses to ignore unsupported command error line = '(M6)'; } return line; } }); this.sender.on('data', (line = '', context = {}) => { if (this.isClose()) { log.error(`Serial port "${this.options.port}" is not accessible`); return; } if (this.workflow.state === WORKFLOW_STATE_IDLE) { log.error(`Unexpected workflow state: ${this.workflow.state}`); return; } line = String(line).trim(); if (line.length === 0) { log.warn(`Expected non-empty line: N=${this.sender.state.sent}`); return; } this.connection.write(line + '\n'); log.silly(`> ${line}`); }); this.sender.on('hold', noop); this.sender.on('unhold', noop); this.sender.on('start', (startTime) => { this.actionTime.senderFinishTime = 0; }); this.sender.on('end', (finishTime) => { this.actionTime.senderFinishTime = finishTime; }); // Workflow this.workflow = new Workflow(); this.workflow.on('start', (...args) => { this.emit('workflow:state', this.workflow.state); this.sender.rewind(); }); this.workflow.on('stop', (...args) => { this.emit('workflow:state', this.workflow.state); this.sender.rewind(); }); this.workflow.on('pause', (...args) => { this.emit('workflow:state', this.workflow.state); if (args.length > 0) { const reason = { ...args[0] }; this.sender.hold(reason); // Hold reason } else { this.sender.hold(); } }); this.workflow.on('resume', (...args) => { this.emit('workflow:state', this.workflow.state); // Reset feeder prior to resume program execution this.feeder.reset(); // Resume program execution this.sender.unhold(); this.sender.next(); }); // Grbl this.runner = new GrblRunner(); // atmelino log.error('new GrblRunner'); this.runner.on('raw', noop); this.runner.on('status', (res) => { this.actionMask.queryStatusReport = false; if (this.actionMask.replyStatusReport) { this.actionMask.replyStatusReport = false; this.emit('serialport:read', res.raw); } // Check if the receive buffer is available in the status report // @see https://github.com/cncjs/cncjs/issues/115 // @see https://github.com/cncjs/cncjs/issues/133 const rx = Number(_.get(res, 'buf.rx', 0)) || 0; if (rx > 0) { // Do not modify the buffer size when running a G-code program if (this.workflow.state !== WORKFLOW_STATE_IDLE) { return; } // Check if the streaming protocol is character-counting streaming protocol if (this.sender.sp.type !== SP_TYPE_CHAR_COUNTING) { return; } // Check if the queue is empty if (this.sender.sp.dataLength !== 0) { return; } // Deduct the receive buffer length to prevent from buffer overrun const bufferSize = (rx - 8); // TODO if (bufferSize > this.sender.sp.bufferSize) { this.sender.sp.bufferSize = bufferSize; } } }); this.runner.on('ok', (res) => { if (this.actionMask.queryParserState.reply) { if (this.actionMask.replyParserState) { this.actionMask.replyParserState = false; this.emit('serialport:read', res.raw); } this.actionMask.queryParserState.reply = false; return; } const { hold, sent, received } = this.sender.state; if (this.workflow.state === WORKFLOW_STATE_RUNNING) { if (hold && (received + 1 >= sent)) { log.debug(`Continue sending G-code: hold=${hold}, sent=${sent}, received=${received + 1}`); this.sender.unhold(); } this.sender.ack(); this.sender.next(); return; } if ((this.workflow.state === WORKFLOW_STATE_PAUSED) && (received < sent)) { if (!hold) { log.error('The sender does not hold off during the paused state'); } if (received + 1 >= sent) { log.debug(`Stop sending G-code: hold=${hold}, sent=${sent}, received=${received + 1}`); } this.sender.ack(); this.sender.next(); return; } this.emit('serialport:read', res.raw); // Feeder this.feeder.next(); }); this.runner.on('error', (res) => { const code = Number(res.message) || undefined; const error = _.find(GRBL_ERRORS, { code: code }); if (this.workflow.state === WORKFLOW_STATE_RUNNING) { const ignoreErrors = config.get('state.controller.exception.ignoreErrors'); const pauseError = !ignoreErrors; const { lines, received } = this.sender.state; const line = lines[received] || ''; this.emit('serialport:read', `> ${line.trim()} (line=${received + 1})`); if (error) { // Grbl v1.1 this.emit('serialport:read', `error:${code} (${error.message})`); if (pauseError) { this.workflow.pause({ err: `error:${code} (${error.message})` }); } } else { // Grbl v0.9 this.emit('serialport:read', res.raw); if (pauseError) { this.workflow.pause({ err: res.raw }); } } this.sender.ack(); this.sender.next(); return; } if (error) { // Grbl v1.1 this.emit('serialport:read', `error:${code} (${error.message})`); } else { // Grbl v0.9 this.emit('serialport:read', res.raw); } // Feeder this.feeder.next(); }); this.runner.on('alarm', (res) => { const code = Number(res.message) || undefined; const alarm = _.find(GRBL_ALARMS, { code: code }); if (alarm) { // Grbl v1.1 this.emit('serialport:read', `ALARM:${code} (${alarm.message})`); } else { // Grbl v0.9 this.emit('serialport:read', res.raw); } }); this.runner.on('parserstate', (res) => { this.actionMask.queryParserState.state = false; this.actionMask.queryParserState.reply = true; if (this.actionMask.replyParserState) { this.emit('serialport:read', res.raw); } }); this.runner.on('parameters', (res) => { // atmelino log.error('parameters: ' + JSON.stringify(res)); const probingData = { type: 'probing', printed: false, result: res.value }; //this.emit('serialport:read', 'parameters'); this.emit('serialport:read', probingData); this.emit('serialport:read', res.raw); }); this.runner.on('feedback', (res) => { this.emit('serialport:read', res.raw); }); this.runner.on('settings', (res) => { const setting = _.find(GRBL_SETTINGS, { setting: res.name }); if (!res.message && setting) { // Grbl v1.1 this.emit('serialport:read', `${res.name}=${res.value} (${setting.message}, ${setting.units})`); } else { // Grbl v0.9 this.emit('serialport:read', res.raw); } }); this.runner.on('startup', (res) => { this.emit('serialport:read', res.raw); // Check the initialized flag if (!this.initialized) { this.initialized = true; // https://github.com/cncjs/cncjs/issues/206 // $13=0 (report in mm) // $13=1 (report in inches) this.writeln('$$'); } // Set the ready flag to true when a startup message has arrived this.ready = true; // The startup message always prints upon startup, after a reset, or at program end. // Setting the initial state when Grbl has completed re-initializing all systems. this.clearActionValues(); }); this.runner.on('others', (res) => { this.emit('serialport:read', res.raw); }); const queryStatusReport = () => { // Check the ready flag if (!(this.ready)) { return; } const now = new Date().getTime(); // The status report query (?) is a realtime command, it does not consume the receive buffer. const lastQueryTime = this.actionTime.queryStatusReport; if (lastQueryTime > 0) { const timespan = Math.abs(now - lastQueryTime); const toleranceTime = 5000; // 5 seconds // Check if it has not been updated for a long time if (timespan >= toleranceTime) { log.debug(`Continue status report query: timespan=${timespan}ms`); this.actionMask.queryStatusReport = false; } } if (this.actionMask.queryStatusReport) { return; } if (this.isOpen()) { this.actionMask.queryStatusReport = true; this.actionTime.queryStatusReport = now; this.connection.write('?'); } }; const queryParserState = _.throttle(() => { // Check the ready flag if (!(this.ready)) { return; } const now = new Date().getTime(); // Do not force query parser state ($G) when running a G-code program, // it will consume 3 bytes from the receive buffer in each time period. // @see https://github.com/cncjs/cncjs/issues/176 // @see https://github.com/cncjs/cncjs/issues/186 if ((this.workflow.state === WORKFLOW_STATE_IDLE) && this.runner.isIdle()) { const lastQueryTime = this.actionTime.queryParserState; if (lastQueryTime > 0) { const timespan = Math.abs(now - lastQueryTime); const toleranceTime = 10000; // 10 seconds // Check if it has not been updated for a long time if (timespan >= toleranceTime) { log.debug(`Continue parser state query: timespan=${timespan}ms`); this.actionMask.queryParserState.state = false; this.actionMask.queryParserState.reply = false; } } } if (this.actionMask.queryParserState.state || this.actionMask.queryParserState.reply) { return; } if (this.isOpen()) { this.actionMask.queryParserState.state = true; this.actionMask.queryParserState.reply = false; this.actionTime.queryParserState = now; this.connection.write('$G\n'); } }, 500); this.queryTimer = setInterval(() => { if (this.isClose()) { // Serial port is closed return; } // Feeder if (this.feeder.peek()) { this.emit('feeder:status', this.feeder.toJSON()); } // Sender if (this.sender.peek()) { this.emit('sender:status', this.sender.toJSON()); } const zeroOffset = _.isEqual( this.runner.getWorkPosition(this.state), this.runner.getWorkPosition(this.runner.state) ); // Grbl settings if (this.settings !== this.runner.settings) { this.settings = this.runner.settings; this.emit('controller:settings', GRBL, this.settings); this.emit('Grbl:settings', this.settings); // Backward compatibility } // Grbl state if (this.state !== this.runner.state) { this.state = this.runner.state; this.emit('controller:state', GRBL, this.state); this.emit('Grbl:state', this.state); // Backward compatibility } // Check the ready flag if (!(this.ready)) { // Wait for the bootloader to complete before sending commands return; } // ? - Status Report queryStatusReport(); // $G - Parser State queryParserState(); // Check if the machine has stopped movement after completion if (this.actionTime.senderFinishTime > 0) { const machineIdle = zeroOffset && this.runner.isIdle(); const now = new Date().getTime(); const timespan = Math.abs(now - this.actionTime.senderFinishTime); const toleranceTime = 500; // in milliseconds if (!machineIdle) { // Extend the sender finish time this.actionTime.senderFinishTime = now; } else if (timespan > toleranceTime) { log.silly(`Finished sending G-code: timespan=${timespan}`); this.actionTime.senderFinishTime = 0; // Stop workflow this.command('gcode:stop'); } } }, 250); } populateContext(context) { // Machine position const { x: mposx, y: mposy, z: mposz, a: mposa, b: mposb, c: mposc } = this.runner.getMachinePosition(); // Work position const { x: posx, y: posy, z: posz, a: posa, b: posb, c: posc } = this.runner.getWorkPosition(); // Modal group const modal = this.runner.getModalGroup(); return Object.assign(context || {}, { // Bounding box xmin: Number(context.xmin) || 0, xmax: Number(context.xmax) || 0, ymin: Number(context.ymin) || 0, ymax: Number(context.ymax) || 0, zmin: Number(context.zmin) || 0, zmax: Number(context.zmax) || 0, // Machine position mposx: Number(mposx) || 0, mposy: Number(mposy) || 0, mposz: Number(mposz) || 0, mposa: Number(mposa) || 0, mposb: Number(mposb) || 0, mposc: Number(mposc) || 0, // Work position posx: Number(posx) || 0, posy: Number(posy) || 0, posz: Number(posz) || 0, posa: Number(posa) || 0, posb: Number(posb) || 0, posc: Number(posc) || 0, // Modal group modal: { motion: modal.motion, wcs: modal.wcs, plane: modal.plane, units: modal.units, distance: modal.distance, feedrate: modal.feedrate, program: modal.program, spindle: modal.spindle, // M7 and M8 may be active at the same time, but a modal group violation might occur when issuing M7 and M8 together on the same line. Using the new line character (\n) to separate lines can avoid this issue. coolant: ensureArray(modal.coolant).join('\n') } }); } clearActionValues() { this.actionMask.queryParserState.state = false; this.actionMask.queryParserState.reply = false; this.actionMask.queryStatusReport = false; this.actionMask.replyParserState = false; this.actionMask.replyStatusReport = false; this.actionTime.queryParserState = 0; this.actionTime.queryStatusReport = 0; this.actionTime.senderFinishTime = 0; } destroy() { if (this.queryTimer) { clearInterval(this.queryTimer); this.queryTimer = null; } if (this.runner) { this.runner.removeAllListeners(); this.runner = null; } this.sockets = {}; if (this.connection) { this.connection = null; } if (this.event) { this.event = null; } if (this.feeder) { this.feeder = null; } if (this.sender) { this.sender = null; } if (this.workflow) { this.workflow = null; } } get status() { return { port: this.options.port, baudrate: this.options.baudrate, rtscts: this.options.rtscts, sockets: Object.keys(this.sockets), ready: this.ready, controller: { type: this.type, settings: this.settings, state: this.state }, feeder: this.feeder.toJSON(), sender: this.sender.toJSON(), workflow: { state: this.workflow.state } }; } open(callback = noop) { const { port, baudrate } = this.options; // Assertion check if (this.isOpen()) { log.error(`Cannot open serial port "${port}"`); return; } this.connection.on('data', this.connectionEventListener.data); this.connection.on('close', this.connectionEventListener.close); this.connection.on('error', this.connectionEventListener.error); this.connection.open((err) => { if (err) { log.error(`Error opening serial port "${port}":`, err); this.emit('serialport:error', { err: err, port: port }); callback(err); // notify error return; } this.emit('serialport:open', { port: port, baudrate: baudrate, controllerType: this.type, inuse: true }); // Emit a change event to all connected sockets if (this.engine.io) { this.engine.io.emit('serialport:change', { port: port, inuse: true }); } callback(); // register controller log.debug(`Connected to serial port "${port}"`); this.workflow.stop(); // Clear action values this.clearActionValues(); if (this.sender.state.gcode) { // Unload G-code this.command('unload'); } }); } close(callback) { const { port } = this.options; // Assertion check if (!this.connection) { const err = `Serial port "${port}" is not available`; callback(new Error(err)); return; } // Stop status query this.ready = false; // Clear initialized flag this.initialized = false; this.emit('serialport:close', { port: port, inuse: false }); // Emit a change event to all connected sockets if (this.engine.io) { this.engine.io.emit('serialport:change', { port: port, inuse: false }); } if (this.isClose()) { callback(null); return; } this.connection.removeAllListeners(); this.connection.close(callback); } isOpen() { return this.connection && this.connection.isOpen; } isClose() { return !(this.isOpen()); } addConnection(socket) { if (!socket) { log.error('The socket parameter is not specified'); return; } log.debug(`Add socket connection: id=${socket.id}`); this.sockets[socket.id] = socket; // // Send data to newly connected client // if (this.isOpen()) { socket.emit('serialport:open', { port: this.options.port, baudrate: this.options.baudrate, controllerType: this.type, inuse: true }); } if (!_.isEmpty(this.settings)) { // controller settings socket.emit('controller:settings', GRBL, this.settings); socket.emit('Grbl:settings', this.settings); // Backward compatibility } if (!_.isEmpty(this.state)) { // controller state socket.emit('controller:state', GRBL, this.state); socket.emit('Grbl:state', this.state); // Backward compatibility } if (this.feeder) { // feeder status socket.emit('feeder:status', this.feeder.toJSON()); } if (this.sender) { // sender status socket.emit('sender:status', this.sender.toJSON()); const { name, gcode, context } = this.sender.state; if (gcode) { socket.emit('gcode:load', name, gcode, context); } } if (this.workflow) { // workflow state socket.emit('workflow:state', this.workflow.state); } } removeConnection(socket) { if (!socket) { log.error('The socket parameter is not specified'); return; } log.debug(`Remove socket connection: id=${socket.id}`); this.sockets[socket.id] = undefined; delete this.sockets[socket.id]; } emit(eventName, ...args) { Object.keys(this.sockets).forEach(id => { const socket = this.sockets[id]; socket.emit(eventName, ...args); }); } command(cmd, ...args) { const handler = { 'gcode:load': () => { let [name, gcode, context = {}, callback = noop] = args; if (typeof context === 'function') { callback = context; context = {}; } // G4 P0 or P with a very small value will empty the planner queue and then // respond with an ok when the dwell is complete. At that instant, there will // be no queued motions, as long as no more commands were sent after the G4. // This is the fastest way to do it without having to check the status reports. const dwell = '%wait ; Wait for the planner to empty'; const ok = this.sender.load(name, gcode + '\n' + dwell, context); if (!ok) { callback(new Error(`Invalid G-code: name=${name}`)); return; } this.emit('gcode:load', name, gcode, context); this.event.trigger('gcode:load'); log.debug(`Load G-code: name="${this.sender.state.name}", size=${this.sender.state.gcode.length}, total=${this.sender.state.total}`); this.workflow.stop(); callback(null, this.sender.toJSON()); }, 'gcode:unload': () => { this.workflow.stop(); // Sender this.sender.unload(); this.emit('gcode:unload'); this.event.trigger('gcode:unload'); }, 'start': () => { log.warn(`Warning: The "${cmd}" command is deprecated and will be removed in a future release.`); this.command('gcode:start'); }, 'gcode:start': () => { this.event.trigger('gcode:start'); this.workflow.start(); // Feeder this.feeder.reset(); // Sender this.sender.next(); }, 'stop': () => { log.warn(`Warning: The "${cmd}" command is deprecated and will be removed in a future release.`); this.command('gcode:stop'); }, // @param {object} options The options object. // @param {boolean} [options.force] Whether to force stop a G-code program. Defaults to false. 'gcode:stop': () => { const { force = false } = { ...args[0] }; this.event.trigger('gcode:stop'); this.workflow.stop(); if (force) { const activeState = _.get(this.state, 'status.activeState', ''); if (activeState === GRBL_ACTIVE_STATE_RUN) { this.write('!'); // hold } setTimeout(() => { const activeState = _.get(this.state, 'status.activeState', ''); if (activeState === GRBL_ACTIVE_STATE_HOLD) { this.write('\x18'); // ctrl-x } }, 500); // delay 500ms } }, 'pause': () => { log.warn(`Warning: The "${cmd}" command is deprecated and will be removed in a future release.`); this.command('gcode:pause'); }, 'gcode:pause': () => { this.event.trigger('gcode:pause'); this.workflow.pause(); this.write('!'); }, 'resume': () => { log.warn(`Warning: The "${cmd}" command is deprecated and will be removed in a future release.`); this.command('gcode:resume'); }, 'gcode:resume': () => { this.event.trigger('gcode:resume'); this.write('~'); this.workflow.resume(); }, 'feeder:feed': () => { const [commands, context = {}] = args; this.command('gcode', commands, context); }, 'feeder:start': () => { if (this.workflow.state === WORKFLOW_STATE_RUNNING) { return; } this.write('~'); this.feeder.unhold(); this.feeder.next(); }, 'feeder:stop': () => { this.feeder.reset(); }, 'feedhold': () => { this.event.trigger('feedhold'); this.write('!'); }, 'cyclestart': () => { this.event.trigger('cyclestart'); this.write('~'); }, 'statusreport': () => { this.write('?'); }, 'homing': () => { this.event.trigger('homing'); this.writeln('$H'); }, 'sleep': () => { this.event.trigger('sleep'); this.writeln('$SLP'); }, 'unlock': () => { this.writeln('$X'); }, 'reset': () => { this.workflow.stop(); this.feeder.reset(); this.write('\x18'); // ^x }, // Feed Overrides // @param {number} value The amount of percentage increase or decrease. // 0: Set 100% of programmed rate. // 10: Increase 10% // -10: Decrease 10% // 1: Increase 1% // -1: Decrease 1% 'feedOverride': () => { const [value] = args; if (value === 0) { this.write('\x90'); } else if (value === 10) { this.write('\x91'); } else if (value === -10) { this.write('\x92'); } else if (value === 1) { this.write('\x93'); } else if (value === -1) { this.write('\x94'); } }, // Spindle Speed Overrides // @param {number} value The amount of percentage increase or decrease. // 0: Set 100% of programmed spindle speed // 10: Increase 10% // -10: Decrease 10% // 1: Increase 1% // -1: Decrease 1% 'spindleOverride': () => { const [value] = args; if (value === 0) { this.write('\x99'); } else if (value === 10) { this.write('\x9a'); } else if (value === -10) { this.write('\x9b'); } else if (value === 1) { this.write('\x9c'); } else if (value === -1) { this.write('\x9d'); } }, // Rapid Overrides // @param {number} value A percentage value of 25, 50, or 100. A value of zero will reset to 100%. // 100: Set to 100% full rapid rate. // 50: Set to 50% of rapid rate. // 25: Set to 25% of rapid rate. 'rapidOverride': () => { const [value] = args; if (value === 0 || value === 100) { this.write('\x95'); } else if (value === 50) { this.write('\x96'); } else if (value === 25) { this.write('\x97'); } }, 'lasertest:on': () => { const [power = 0, duration = 0, maxS = 1000] = args; const commands = [ // https://github.com/gnea/grbl/wiki/Grbl-v1.1-Laser-Mode // The laser will only turn on when Grbl is in a G1, G2, or G3 motion mode. 'G1F1', 'M3S' + ensurePositiveNumber(maxS * (power / 100)) ]; if (duration > 0) { commands.push('G4P' + ensurePositiveNumber(duration / 1000)); commands.push('M5S0'); } this.command('gcode', commands); }, 'lasertest:off': () => { const commands = [ 'M5S0' ]; this.command('gcode', commands); }, 'gcode': () => { const [commands, context] = args; const data = ensureArray(commands) .join('\n') .split(/\r?\n/) .filter(line => { if (typeof line !== 'string') { return false; } return line.trim().length > 0; }); this.feeder.feed(data, context); if (!this.feeder.isPending()) { this.feeder.next(); } }, 'macro:run': () => { let [id, context = {}, callback = noop] = args; if (typeof context === 'function') { callback = context; context = {}; } const macros = config.get('macros'); const macro = _.find(macros, { id: id }); if (!macro) { log.error(`Cannot find the macro: id=${id}`); return; } this.event.trigger('macro:run'); this.command('gcode', macro.content, context); callback(null); }, 'macro:load': () => { let [id, context = {}, callback = noop] = args; if (typeof context === 'function') { callback = context; context = {}; } const macros = config.get('macros'); const macro = _.find(macros, { id: id }); if (!macro) { log.error(`Cannot find the macro: id=${id}`); return; } this.event.trigger('macro:load'); this.command('gcode:load', macro.name, macro.content, context, callback); }, 'watchdir:load': () => { const [file, callback = noop] = args; const context = {}; // empty context monitor.readFile(file, (err, data) => { if (err) { callback(err); return; } this.command('gcode:load', file, data, context, callback); }); } }[cmd]; if (!handler) { log.error(`Unknown command: ${cmd}`); return; } handler(); } write(data, context) { // Assertion check if (this.isClose()) { log.error(`Serial port "${this.options.port}" is not accessible`); return; } const cmd = data.trim(); this.actionMask.replyStatusReport = (cmd === '?') || this.actionMask.replyStatusReport; this.actionMask.replyParserState = (cmd === '$G') || this.actionMask.replyParserState; this.emit('serialport:write', data, { ...context, source: WRITE_SOURCE_CLIENT }); this.connection.write(data); log.silly(`> ${data}`); } writeln(data, context) { if (_.includes(GRBL_REALTIME_COMMANDS, data)) { this.write(data, context); } else { this.write(data + '\n', context); } } } export default GrblController;
/* eslint-disable import/no-extraneous-dependencies */ require('dotenv').config({ path: `.env.${process.env.NODE_ENV}`, }) module.exports = { siteMetadata: { title: 'Gatsby Contentstack starter', }, plugins: [ 'gatsby-plugin-react-helmet', { resolve: 'gatsby-plugin-manifest', options: { name: 'gatsby-starter-contentstack', short_name: 'starter', start_url: '/', background_color: '#663399', theme_color: '#663399', display: 'minimal-ui', icon: 'src/images/contentstack-logo.png', // This path is relative to the root of the site. }, }, // { // resolve: 'gatsby-source-filesystem', // options: { // path: `${__dirname}/src/`, // }, // }, // `gatsby-plugin-sharp`, `gatsby-transformer-sharp`, { resolve: 'gatsby-source-contentstack', options: { api_key: process.env.CONTENTSTACK_API_KEY, delivery_token: process.env.CONTENTSTACK_DELIVERY_TOKEN, environment: process.env.CONTENTSTACK_ENVIRONMENT, cdn: process.env.CONTENTSTACK_CDN ? process.env.CONTENTSTACK_CDN : '', // Optional: expediteBuild set this to either true or false expediteBuild: true, // Optional: Specify true if you want to generate custom schema enableSchemaGeneration: true, // Optional: Specify a different prefix for types. // This is useful in cases where you have multiple instances // of the plugin to be connected to different stacks. type_prefix: 'Contentstack', // (default) }, }, ], }
import random from word import words import string def get_valid_word(words): word = random.choice(words) # randomly ghooses something from the list while '-' in word or ' ' in word: word = random.choice(words) return word.upper() def hangman(): word = get_valid_word(words) word_letters = set(word) # letters in the world alphabet = set(string.ascii_uppercase) used_letters = set() # what the user has guessed # getting user input while len(word_letters) > 0: print('You have used these letters: ', ' '.join(used_letters)) word_list = [letter if letter in used_letters else '_' for letter in word] print('Current word: ', ' '.join(word_list)) user_letter = input('Guess a letter: ').upper() if user_letter in alphabet - used_letters: used_letters.add(user_letter) if user_letter in word_letters: word_letters.remove(user_letter) elif user_letter in used_letters: print('You have already used that letter. Try again') else: print('Invalid character. Try again') print(hangman())
#! /usr/bin/env python """ Author: LiangLiang ZHENG Date: File Description """ import numpy as np import matplotlib.pyplot as plt import copy from scipy.io import wavfile from scipy.signal import butter, lfilter import scipy.ndimage # Most of the Spectrograms and Inversion are taken from: https://gist.github.com/kastnerkyle/179d6e9a88202ab0a2fe def butter_bandpass(lowcut, highcut, fs, order=5): nyq = 0.5 * fs low = lowcut / nyq high = highcut / nyq b, a = butter(order, [low, high], btype='band') return b, a def butter_bandpass_filter(data, lowcut, highcut, fs, order=5): b, a = butter_bandpass(lowcut, highcut, fs, order=order) y = lfilter(b, a, data) return y def overlap(X, window_size, window_step): """ Create an overlapped version of X Parameters ---------- X : ndarray, shape=(n_samples,) Input signal to window and overlap window_size : int Size of windows to take window_step : int Step size between windows Returns ------- X_strided : shape=(n_windows, window_size) 2D array of overlapped X """ window_size, window_step = map(int, (window_size, window_step)) if window_size % 2 != 0: raise ValueError("Window size must be even!") # Make sure there are an even number of windows before stridetricks append = np.zeros((window_size - len(X) % window_size)) X = np.hstack((X, append)) ws = window_size ss = window_step a = X valid = len(a) - ws nw = (valid) // ss out = np.ndarray((nw,ws),dtype = a.dtype) for i in range(nw): # "slide" the window along the samples start = i * ss stop = start + ws out[i] = a[start : stop] return out def stft(X, fftsize=128, step=65, mean_normalize=True, real=False, compute_onesided=True): """ Compute STFT for 1D real valued input X """ if real: local_fft = np.fft.rfft cut = -1 else: local_fft = np.fft.fft cut = None if compute_onesided: cut = fftsize // 2 if mean_normalize: X -= X.mean() X = overlap(X, fftsize, step) size = fftsize win = 0.54 - .46 * np.cos(2 * np.pi * np.arange(size) / (size - 1)) X = X * win[None] X = local_fft(X)[:, :cut] return X def pretty_spectrogram(d,log = True, thresh= 5, fft_size = 512, step_size = 64): """ creates a spectrogram log: take the log of the spectrgram thresh: threshold minimum power for log spectrogram """ specgram = np.abs(stft(d, fftsize=fft_size, step=step_size, real=False, compute_onesided=True)) if log == True: specgram /= specgram.max() # volume normalize to max 1 specgram = np.log10(specgram) # take log specgram[specgram < -thresh] = -thresh # set anything less than the threshold as the threshold else: specgram[specgram < thresh] = thresh # set anything less than the threshold as the threshold return specgram # Also mostly modified or taken from https://gist.github.com/kastnerkyle/179d6e9a88202ab0a2fe def invert_pretty_spectrogram(X_s, log = True, fft_size = 512, step_size = 512/4, n_iter = 10): if log == True: X_s = np.power(10, X_s) X_s = np.concatenate([X_s, X_s[:, ::-1]], axis=1) X_t = iterate_invert_spectrogram(X_s, fft_size, step_size, n_iter=n_iter) return X_t def iterate_invert_spectrogram(X_s, fftsize, step, n_iter=10, verbose=False): """ Under MSR-LA License Based on MATLAB implementation from Spectrogram Inversion Toolbox References ---------- D. Griffin and J. Lim. Signal estimation from modified short-time Fourier transform. IEEE Trans. Acoust. Speech Signal Process., 32(2):236-243, 1984. Malcolm Slaney, Daniel Naar and Richard F. Lyon. Auditory Model Inversion for Sound Separation. Proc. IEEE-ICASSP, Adelaide, 1994, II.77-80. Xinglei Zhu, G. Beauregard, L. Wyse. Real-Time Signal Estimation from Modified Short-Time Fourier Transform Magnitude Spectra. IEEE Transactions on Audio Speech and Language Processing, 08/2007. """ reg = np.max(X_s) / 1E8 X_best = copy.deepcopy(X_s) for i in range(n_iter): if verbose: print("Runnning iter %i" % i) if i == 0: X_t = invert_spectrogram(X_best, step, calculate_offset=True, set_zero_phase=True) else: # Calculate offset was False in the MATLAB version # but in mine it massively improves the result # Possible bug in my impl? X_t = invert_spectrogram(X_best, step, calculate_offset=True, set_zero_phase=False) est = stft(X_t, fftsize=fftsize, step=step, compute_onesided=False) phase = est / np.maximum(reg, np.abs(est)) X_best = X_s * phase[:len(X_s)] X_t = invert_spectrogram(X_best, step, calculate_offset=True, set_zero_phase=False) return np.real(X_t) def invert_spectrogram(X_s, step, calculate_offset=True, set_zero_phase=True): """ Under MSR-LA License Based on MATLAB implementation from Spectrogram Inversion Toolbox References ---------- D. Griffin and J. Lim. Signal estimation from modified short-time Fourier transform. IEEE Trans. Acoust. Speech Signal Process., 32(2):236-243, 1984. Malcolm Slaney, Daniel Naar and Richard F. Lyon. Auditory Model Inversion for Sound Separation. Proc. IEEE-ICASSP, Adelaide, 1994, II.77-80. Xinglei Zhu, G. Beauregard, L. Wyse. Real-Time Signal Estimation from Modified Short-Time Fourier Transform Magnitude Spectra. IEEE Transactions on Audio Speech and Language Processing, 08/2007. """ step = int(step) size = int(X_s.shape[1] // 2) wave = np.zeros((X_s.shape[0] * step + size)) # Getting overflow warnings with 32 bit... wave = wave.astype('float64') total_windowing_sum = np.zeros((X_s.shape[0] * step + size)) win = 0.54 - .46 * np.cos(2 * np.pi * np.arange(size) / (size - 1)) est_start = int(size // 2) - 1 est_end = est_start + size for i in range(X_s.shape[0]): wave_start = int(step * i) wave_end = wave_start + size if set_zero_phase: spectral_slice = X_s[i].real + 0j else: # already complex spectral_slice = X_s[i] # Don't need fftshift due to different impl. wave_est = np.real(np.fft.ifft(spectral_slice))[::-1] if calculate_offset and i > 0: offset_size = size - step if offset_size <= 0: print("WARNING: Large step size >50\% detected! " "This code works best with high overlap - try " "with 75% or greater") offset_size = step offset = xcorr_offset(wave[wave_start:wave_start + offset_size], wave_est[est_start:est_start + offset_size]) else: offset = 0 wave[wave_start:wave_end] += win * wave_est[ est_start - offset:est_end - offset] total_windowing_sum[wave_start:wave_end] += win wave = np.real(wave) / (total_windowing_sum + 1E-6) return wave def xcorr_offset(x1, x2): """ Under MSR-LA License Based on MATLAB implementation from Spectrogram Inversion Toolbox References ---------- D. Griffin and J. Lim. Signal estimation from modified short-time Fourier transform. IEEE Trans. Acoust. Speech Signal Process., 32(2):236-243, 1984. Malcolm Slaney, Daniel Naar and Richard F. Lyon. Auditory Model Inversion for Sound Separation. Proc. IEEE-ICASSP, Adelaide, 1994, II.77-80. Xinglei Zhu, G. Beauregard, L. Wyse. Real-Time Signal Estimation from Modified Short-Time Fourier Transform Magnitude Spectra. IEEE Transactions on Audio Speech and Language Processing, 08/2007. """ x1 = x1 - x1.mean() x2 = x2 - x2.mean() frame_size = len(x2) half = frame_size // 2 corrs = np.convolve(x1.astype('float32'), x2[::-1].astype('float32')) corrs[:half] = -1E30 corrs[-half:] = -1E30 offset = corrs.argmax() - len(x1) return offset def make_mel(spectrogram, mel_filter, shorten_factor = 1): mel_spec =np.transpose(mel_filter).dot(np.transpose(spectrogram)) mel_spec = scipy.ndimage.zoom(mel_spec.astype('float32'), [1, 1./shorten_factor]).astype('float16') mel_spec = mel_spec[:,1:-1] # a little hacky but seemingly needed for clipping return mel_spec def mel_to_spectrogram(mel_spec, mel_inversion_filter, spec_thresh, shorten_factor): """ takes in an mel spectrogram and returns a normal spectrogram for inversion """ mel_spec = (mel_spec+spec_thresh) uncompressed_spec = np.transpose(np.transpose(mel_spec).dot(mel_inversion_filter)) uncompressed_spec = scipy.ndimage.zoom(uncompressed_spec.astype('float32'), [1,shorten_factor]).astype('float16') uncompressed_spec = uncompressed_spec -4 return uncompressed_spec # From https://github.com/jameslyons/python_speech_features def hz2mel(hz): """Convert a value in Hertz to Mels :param hz: a value in Hz. This can also be a numpy array, conversion proceeds element-wise. :returns: a value in Mels. If an array was passed in, an identical sized array is returned. """ return 2595 * np.log10(1+hz/700.) def mel2hz(mel): """Convert a value in Mels to Hertz :param mel: a value in Mels. This can also be a numpy array, conversion proceeds element-wise. :returns: a value in Hertz. If an array was passed in, an identical sized array is returned. """ return 700*(10**(mel/2595.0)-1) def get_filterbanks(nfilt=20,nfft=512,samplerate=16000,lowfreq=0,highfreq=None): """Compute a Mel-filterbank. The filters are stored in the rows, the columns correspond to fft bins. The filters are returned as an array of size nfilt * (nfft/2 + 1) :param nfilt: the number of filters in the filterbank, default 20. :param nfft: the FFT size. Default is 512. :param samplerate: the samplerate of the signal we are working with. Affects mel spacing. :param lowfreq: lowest band edge of mel filters, default 0 Hz :param highfreq: highest band edge of mel filters, default samplerate/2 :returns: A numpy array of size nfilt * (nfft/2 + 1) containing filterbank. Each row holds 1 filter. """ highfreq= highfreq or samplerate/2 assert highfreq <= samplerate/2, "highfreq is greater than samplerate/2" # compute points evenly spaced in mels lowmel = hz2mel(lowfreq) highmel = hz2mel(highfreq) melpoints = np.linspace(lowmel,highmel,nfilt+2) # our points are in Hz, but we use fft bins, so we have to convert # from Hz to fft bin number bin = np.floor((nfft+1)*mel2hz(melpoints)/samplerate) fbank = np.zeros([nfilt,nfft//2]) for j in range(0,nfilt): for i in range(int(bin[j]), int(bin[j+1])): fbank[j,i] = (i - bin[j]) / (bin[j+1]-bin[j]) for i in range(int(bin[j+1]), int(bin[j+2])): fbank[j,i] = (bin[j+2]-i) / (bin[j+2]-bin[j+1]) return fbank def create_mel_filter(fft_size, n_freq_components = 64, start_freq = 300, end_freq = 8000, samplerate=44100): """ Creates a filter to convolve with the spectrogram to get out mels """ mel_inversion_filter = get_filterbanks(nfilt=n_freq_components, nfft=fft_size, samplerate=samplerate, lowfreq=start_freq, highfreq=end_freq) # Normalize filter mel_filter = mel_inversion_filter.T / mel_inversion_filter.sum(axis=1) return mel_filter, mel_inversion_filter ### Parameters ### fft_size = 2048 # window size for the FFT step_size = fft_size/16 # distance to slide along the window (in time) spec_thresh = 4 # threshold for spectrograms (lower filters out more noise) lowcut = 500 # Hz # Low cut for our butter bandpass filter highcut = 15000 # Hz # High cut for our butter bandpass filter # For mels n_mel_freq_components = 64 # number of mel frequency channels shorten_factor = 10 # how much should we compress the x-axis (time) start_freq = 300 # Hz # What frequency to start sampling our melS from end_freq = 8000 # Hz # What frequency to stop sampling our melS from # Grab your wav and filter it mywav = 'babibu_1.wav' rate, data = wavfile.read(mywav) data = butter_bandpass_filter(data, lowcut, highcut, rate, order=1) # Only use a short clip for our demo if np.shape(data)[0]/float(rate) > 10: data = data[0:rate*10] print ('Length in time (s): ', np.shape(data)[0]/float(rate)) wav_spectrogram = pretty_spectrogram(data.astype('float64'), fft_size = fft_size, step_size = step_size, log = True, thresh = spec_thresh) fig, ax = plt.subplots() cax = ax.matshow(np.transpose(wav_spectrogram), interpolation='nearest', aspect='auto', origin='lower') fig.colorbar(cax) plt.title('Babibu Original Spectrogram') plt.xlabel('Time/s', fontsize=12) plt.ylabel('Frequency/hz', fontsize=12) plt.show() # Generate the mel filters mel_filter, mel_inversion_filter = create_mel_filter(fft_size = fft_size, n_freq_components = n_mel_freq_components, start_freq = start_freq, end_freq = end_freq) # take a look at both of the filters fig, ax = plt.subplots(nrows=2,ncols=1, figsize=(20,5)) ax[0].matshow(np.transpose(mel_filter),cmap=plt.cm.afmhot, interpolation='nearest', aspect='auto') ax[0].set_title('mel Filter') ax[1].matshow(mel_inversion_filter,cmap=plt.cm.afmhot, interpolation='nearest', aspect='auto') ax[1].set_title('mel Inversion Filter') mel_spec = make_mel(wav_spectrogram, mel_filter, shorten_factor = shorten_factor) # plot the compressed spec fig, ax = plt.subplots(nrows=1,ncols=1, figsize=(20,5)) cax = ax.matshow(np.float32(mel_spec), interpolation='nearest', aspect='auto', cmap=plt.cm.afmhot, origin='lower') fig.colorbar(cax) plt.title('mel Spectrogram') plt.show() # Output some stats of our file print(''.join(['mel Spectrogram Size: ',str(np.shape(mel_spec))])) print(''.join(['Original Spectrogram Size: ',str(np.shape(np.transpose(wav_spectrogram)))])) print(''.join(['Original Waveform Size: ',str(np.shape(data))])) print(''.join(['Length (s): ', str(len(data)/float(rate))])) print(''.join(['Original Sampling Rate (ms) : ', str(1./float(rate))])) print(''.join(['New Sampling Rate (ms): ', str(float(np.shape(mel_spec)[1]) / (len(data)/float(rate)))])) mel_inverted_spectrogram = mel_to_spectrogram(mel_spec, mel_inversion_filter, spec_thresh=spec_thresh, shorten_factor=shorten_factor) fig, ax = plt.subplots(nrows=1,ncols=1, figsize=(20,4)) cax = ax.matshow(np.float32(mel_inverted_spectrogram), cmap=plt.cm.afmhot, origin='lower', aspect='auto',interpolation='nearest') fig.colorbar(cax) plt.title('Inverted mel Spectrogram') plt.show() inverted_mel_audio = invert_pretty_spectrogram(np.transpose(mel_inverted_spectrogram), fft_size = fft_size, step_size = step_size, log = True, n_iter = 10)
import React from 'react'; import ReactDOM from 'react-dom'; import App from '../App'; import { shallow } from 'enzyme'; import PageContainer from '../containers/PageContainer'; describe('App', () => { let wrapper; it('renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render(<App />, div); ReactDOM.unmountComponentAtNode(div); }); beforeEach(() => { wrapper = shallow(<App/>); }) it('render a <PageContainer>', () => { expect(wrapper.childAt(0).type()).toBe(PageContainer) }) });
"""Tests for input validation functions""" from tempfile import NamedTemporaryFile import numpy as np from numpy.testing import assert_array_equal import scipy.sparse as sp from nose.tools import assert_raises, assert_true, assert_false, assert_equal from sklearn.utils import (array2d, as_float_array, atleast2d_or_csr, atleast2d_or_csc, check_arrays, safe_asarray) from sklearn.random_projection import sparse_random_matrix def test_as_float_array(): """Test function for as_float_array""" X = np.ones((3, 10), dtype=np.int32) X = X + np.arange(10, dtype=np.int32) # Checks that the return type is ok X2 = as_float_array(X, copy=False) np.testing.assert_equal(X2.dtype, np.float32) # Another test X = X.astype(np.int64) X2 = as_float_array(X, copy=True) # Checking that the array wasn't overwritten assert_true(as_float_array(X, False) is not X) # Checking that the new type is ok np.testing.assert_equal(X2.dtype, np.float64) # Here, X is of the right type, it shouldn't be modified X = np.ones((3, 2), dtype=np.float32) assert_true(as_float_array(X, copy=False) is X) # Test that if X is fortran ordered it stays X = np.asfortranarray(X) assert_true(np.isfortran(as_float_array(X, copy=True))) # Test the copy parameter with some matrices matrices = [ np.matrix(np.arange(5)), sp.csc_matrix(np.arange(5)).todense(), sparse_random_matrix(10, 10, density=0.10).todense() ] for M in matrices: N = as_float_array(M, copy=True) N[0, 0] = np.nan assert_false(np.isnan(M).any()) def test_check_arrays_exceptions(): """Check that invalid arguments raise appropriate exceptions""" assert_raises(ValueError, check_arrays, [0], [0, 1]) assert_raises(TypeError, check_arrays, 0, [0, 1]) assert_raises(TypeError, check_arrays, [0], 0) assert_raises(TypeError, check_arrays, [0, 1], [0, 1], meaning_of_life=42) assert_raises(ValueError, check_arrays, [0], [0], sparse_format='fake') def test_np_matrix(): """Confirm that input validation code does not return np.matrix""" X = np.arange(12).reshape(3, 4) assert_false(isinstance(as_float_array(X), np.matrix)) assert_false(isinstance(as_float_array(np.matrix(X)), np.matrix)) assert_false(isinstance(as_float_array(sp.csc_matrix(X)), np.matrix)) assert_false(isinstance(atleast2d_or_csr(X), np.matrix)) assert_false(isinstance(atleast2d_or_csr(np.matrix(X)), np.matrix)) assert_false(isinstance(atleast2d_or_csr(sp.csc_matrix(X)), np.matrix)) assert_false(isinstance(atleast2d_or_csc(X), np.matrix)) assert_false(isinstance(atleast2d_or_csc(np.matrix(X)), np.matrix)) assert_false(isinstance(atleast2d_or_csc(sp.csr_matrix(X)), np.matrix)) assert_false(isinstance(safe_asarray(X), np.matrix)) assert_false(isinstance(safe_asarray(np.matrix(X)), np.matrix)) assert_false(isinstance(safe_asarray(sp.lil_matrix(X)), np.matrix)) assert_true(atleast2d_or_csr(X, copy=False) is X) assert_false(atleast2d_or_csr(X, copy=True) is X) assert_true(atleast2d_or_csc(X, copy=False) is X) assert_false(atleast2d_or_csc(X, copy=True) is X) def test_memmap(): """Confirm that input validation code doesn't copy memory mapped arrays""" asflt = lambda x: as_float_array(x, copy=False) with NamedTemporaryFile(prefix='sklearn-test') as tmp: M = np.memmap(tmp, shape=100, dtype=np.float32) M[:] = 0 for f in (array2d, np.asarray, asflt, safe_asarray): X = f(M) X[:] = 1 assert_array_equal(X.ravel(), M) X[:] = 0 def test_ordering(): """Check that ordering is enforced correctly by validation utilities. We need to check each validation utility, because a 'copy' without 'order=K' will kill the ordering. """ X = np.ones((10, 5)) for A in X, X.T: for validator in (array2d, atleast2d_or_csr, atleast2d_or_csc): for copy in (True, False): B = validator(A, order='C', copy=copy) assert_true(B.flags['C_CONTIGUOUS']) B = validator(A, order='F', copy=copy) assert_true(B.flags['F_CONTIGUOUS']) if copy: assert_false(A is B) X = sp.csr_matrix(X) X.data = X.data[::-1] assert_false(X.data.flags['C_CONTIGUOUS']) for validator in (atleast2d_or_csc, atleast2d_or_csr): for copy in (True, False): Y = validator(X, copy=copy, order='C') assert_true(Y.data.flags['C_CONTIGUOUS']) def test_check_arrays(): # check that error is raised on different length inputs X = [0, 1] Y = np.arange(3) assert_raises(ValueError, check_arrays, X, Y) # check error for sparse matrix and array X = sp.csc_matrix(np.arange(4)) assert_raises(ValueError, check_arrays, X, Y) # check they y=None pattern X = [0, 1, 2] X_, Y_, Z_ = check_arrays(X, Y, None) assert_true(Z_ is None) # check that lists are converted X_, Y_ = check_arrays(X, Y) assert_true(isinstance(X_, np.ndarray)) assert_true(isinstance(Y_, np.ndarray)) # check that Y was not copied: assert_true(Y_ is Y) # check copying X_, Y_ = check_arrays(X, Y, copy=True) assert_false(Y_ is Y) # check forcing dtype X_, Y_ = check_arrays(X, Y, dtype=np.int) assert_equal(X_.dtype, np.int) assert_equal(Y_.dtype, np.int) X_, Y_ = check_arrays(X, Y, dtype=np.float) assert_equal(X_.dtype, np.float) assert_equal(Y_.dtype, np.float) # test check_ccontiguous Y = np.arange(6).reshape(3, 2).copy('F') # if we don't specify it, it is not changed X_, Y_ = check_arrays(X, Y) assert_true(Y_.flags['F_CONTIGUOUS']) assert_false(Y_.flags['C_CONTIGUOUS']) X_, Y_ = check_arrays(X, Y, check_ccontiguous=True) assert_true(Y_.flags['C_CONTIGUOUS']) assert_false(Y_.flags['F_CONTIGUOUS']) # check that lists are passed through if allow_lists is true X_, Y_ = check_arrays(X, Y, allow_lists=True) assert_true(isinstance(X_, list))
import collections from types import MethodType from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.db.models.fields.files import FieldFile from django.utils.encoding import force_text from django.utils.functional import Promise from elasticsearch_dsl.field import ( Boolean, Byte, Completion, Date, Double, Field, Float, GeoPoint, GeoShape, Integer, Ip, Long, Nested, Object, ScaledFloat, Short, Keyword, Text, SearchAsYouType, ) from .exceptions import VariableLookupError class DEDField(Field): def __init__(self, attr=None, **kwargs): super(DEDField, self).__init__(**kwargs) self._path = attr.split('.') if attr else [] def __setattr__(self, key, value): if key == 'get_value_from_instance': self.__dict__[key] = value else: super(DEDField, self).__setattr__(key, value) def get_value_from_instance(self, instance, field_value_to_ignore=None): """ Given an model instance to index with ES, return the value that should be put into ES for this field. """ if not instance: return None for attr in self._path: try: instance = instance[attr] except ( TypeError, AttributeError, KeyError, ValueError, IndexError ): try: instance = getattr(instance, attr) except ObjectDoesNotExist: return None except (TypeError, AttributeError): try: instance = instance[int(attr)] except ( IndexError, ValueError, KeyError, TypeError ): if self._required: raise VariableLookupError( "Failed lookup for key [{}] in " "{!r}".format(attr, instance) ) return None if isinstance(instance, models.manager.Manager): instance = instance.all() elif callable(instance): instance = instance() elif instance is None: return None if instance == field_value_to_ignore: return None # convert lazy object like lazy translations to string if isinstance(instance, Promise): return force_text(instance) return instance class ObjectField(DEDField, Object): def _get_inner_field_data(self, obj, field_value_to_ignore=None): data = {} if hasattr(self, 'properties'): for name, field in self.properties.to_dict().items(): if not isinstance(field, DEDField): continue if field._path == []: field._path = [name] data[name] = field.get_value_from_instance( obj, field_value_to_ignore ) else: for name, field in self._doc_class._doc_type.mapping.properties._params.get('properties', {}).items(): # noqa if not isinstance(field, DEDField): continue if field._path == []: field._path = [name] data[name] = field.get_value_from_instance( obj, field_value_to_ignore ) # This allows for ObjectFields to be indexed from dicts with # dynamic keys (i.e. keys/fields not defined in 'properties') if not data and obj and isinstance(obj, dict): data = obj return data def get_value_from_instance(self, instance, field_value_to_ignore=None): objs = super(ObjectField, self).get_value_from_instance( instance, field_value_to_ignore ) if objs is None: return {} try: is_iterable = bool(iter(objs)) except TypeError: is_iterable = False # While dicts are iterable, they need to be excluded here so # their full data is indexed if is_iterable and not isinstance(objs, dict): return [ self._get_inner_field_data(obj, field_value_to_ignore) for obj in objs if obj != field_value_to_ignore ] return self._get_inner_field_data(objs, field_value_to_ignore) def ListField(field): """ This wraps a field so that when get_value_from_instance is called, the field's values are iterated over """ original_get_value_from_instance = field.get_value_from_instance def get_value_from_instance(self, instance, field_value_to_ignore=None): if not original_get_value_from_instance(instance): return [] return [value for value in original_get_value_from_instance(instance)] field.get_value_from_instance = MethodType(get_value_from_instance, field) return field class BooleanField(DEDField, Boolean): pass class ByteField(DEDField, Byte): pass class CompletionField(DEDField, Completion): pass class DateField(DEDField, Date): pass class DoubleField(DEDField, Double): pass class FloatField(DEDField, Float): pass class ScaledFloatField(DEDField, ScaledFloat): pass class GeoPointField(DEDField, GeoPoint): pass class GeoShapeField(DEDField, GeoShape): pass class IntegerField(DEDField, Integer): pass class IpField(DEDField, Ip): pass class LongField(DEDField, Long): pass class NestedField(Nested, ObjectField): pass class ShortField(DEDField, Short): pass class KeywordField(DEDField, Keyword): pass class TextField(DEDField, Text): pass class SearchAsYouTypeField(DEDField, SearchAsYouType): pass class FileFieldMixin(object): def get_value_from_instance(self, instance, field_value_to_ignore=None): _file = super(FileFieldMixin, self).get_value_from_instance( instance, field_value_to_ignore) if isinstance(_file, FieldFile): return _file.url if _file else '' return _file if _file else '' class FileField(FileFieldMixin, DEDField, Text): pass
from progressivis.table.module import TableModule from progressivis.table.table import Table from progressivis.core.slot import SlotDescriptor try: from .cxx_max import Max as CxxMax except: CxxMax = None import numpy as np import logging logger = logging.getLogger(__name__) class Max(TableModule): parameters = [('history', np.dtype(int), 3)] inputs = [SlotDescriptor('table', type=Table, required=True)] def __init__(self, columns=None, **kwds): super(Max, self).__init__(**kwds) self._columns = columns self.default_step_size = 10000 self.cxx_module = CxxMax(self) def is_ready(self): if self.get_input_slot('table').created.any(): return True return super().is_ready() def run_step(self, run_number, step_size, howlong): return self.cxx_module.run(run_number, step_size, howlong)
"""learning_log URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin # from django.urls import path urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('learning_logs.urls', namespace='learning_logs')), ]
import asyncio from time import sleep from telethon.tl import functions from telethon.tl.types import ( ChannelParticipantsKicked, ChatBannedRights, UserStatusEmpty, UserStatusLastMonth, UserStatusLastWeek, UserStatusOffline, UserStatusOnline, UserStatusRecently, ) from . import * @beast.on(beastx_cmd(pattern="unbanall ?(.*)")) async def _(event): if event.fwd_from: return input_str = event.pattern_match.group(1) if input_str: logger.info("TODO: Not yet Implemented") else: if event.is_private: return False await event.edit("Searching Participant Lists.") p = 0 async for i in borg.iter_participants( event.chat_id, filter=ChannelParticipantsKicked, aggressive=True ): rights = ChatBannedRights(until_date=0, view_messages=False) try: await borg( functions.channels.EditBannedRequest(event.chat_id, i, rights) ) except FloodWaitError as ex: logger.warn("sleeping for {} seconds".format(ex.seconds)) sleep(ex.seconds) except Exception as ex: await event.edit(str(ex)) else: p += 1 await event.edit("{}: {} unbanned".format(event.chat_id, p)) @beast.on(beastx_cmd(pattern="igstat ?(.*)")) async def _(event): if event.fwd_from: return if event.is_private: return False input_str = event.pattern_match.group(1) if input_str: chat = await event.get_chat() if not (chat.admin_rights or chat.creator): await event.edit("`You aren't an admin here!`") return False p = 0 b = 0 c = 0 d = 0 e = [] m = 0 n = 0 y = 0 w = 0 o = 0 q = 0 r = 0 await event.edit("Searching Participant Lists.") async for i in borg.iter_participants(event.chat_id): p = p + 1 # # Note that it's "reversed". You must set to ``True`` the permissions # you want to REMOVE, and leave as ``None`` those you want to KEEP. rights = ChatBannedRights(until_date=None, view_messages=True) if isinstance(i.status, UserStatusEmpty): y = y + 1 if "y" in input_str: status, e = await ban_user(event.chat_id, i, rights) if not status: await event.edit("I need admin priveleges to perform this action!") e.append(str(e)) break else: c = c + 1 if isinstance(i.status, UserStatusLastMonth): m = m + 1 if "m" in input_str: status, e = await ban_user(event.chat_id, i, rights) if not status: await event.edit("I need admin priveleges to perform this action!") e.append(str(e)) break else: c = c + 1 if isinstance(i.status, UserStatusLastWeek): w = w + 1 if "w" in input_str: status, e = await ban_user(event.chat_id, i, rights) if not status: await event.edit("I need admin priveleges to perform this action!") e.append(str(e)) break else: c = c + 1 if isinstance(i.status, UserStatusOffline): o = o + 1 if "o" in input_str: status, e = await ban_user(event.chat_id, i, rights) if not status: await event.edit("I need admin priveleges to perform this action!") e.append(str(e)) break else: c = c + 1 if isinstance(i.status, UserStatusOnline): q = q + 1 if "q" in input_str: status, e = await ban_user(event.chat_id, i, rights) if not status: await event.edit("I need admin priveleges to perform this action!") e.append(str(e)) break else: c = c + 1 if isinstance(i.status, UserStatusRecently): r = r + 1 if "r" in input_str: status, e = await ban_user(event.chat_id, i, rights) if not status: await event.edit("I need admin priveleges to perform this action!") e.append(str(e)) break else: c = c + 1 if i.bot: b = b + 1 if "b" in input_str: status, e = await ban_user(event.chat_id, i, rights) if not status: await event.edit("I need admin priveleges to perform this action!") e.append(str(e)) break else: c = c + 1 elif i.deleted: d = d + 1 if "d" in input_str: status, e = await ban_user(event.chat_id, i, rights) if not status: await event.edit("I need admin priveleges to perform this action!") e.append(str(e)) else: c = c + 1 elif i.status is None: n = n + 1 if input_str: required_string = """Kicked {} / {} users Deleted Accounts: {} UserStatusEmpty: {} UserStatusLastMonth: {} UserStatusLastWeek: {} UserStatusOffline: {} UserStatusOnline: {} UserStatusRecently: {} Bots: {} None: {}""" await event.edit(required_string.format(c, p, d, y, m, w, o, q, r, b, n)) await asyncio.sleep(5) await event.edit( """Total: {} users Deleted Accounts: {} UserStatusEmpty: {} UserStatusLastMonth: {} UserStatusLastWeek: {} UserStatusOffline: {} UserStatusOnline: {} UserStatusRecently: {} Bots: {} None: {}""".format( p, d, y, m, w, o, q, r, b, n ) ) async def ban_user(chat_id, i, rights): try: await borg(functions.channels.EditBannedRequest(chat_id, i, rights)) return True, None except Exception as exc: return False, str(exc) CMD_HELP.update( { "Unbanall": "**Unbanall**\ \n\n**Syntax : **`.unbanall`\ \n**Usage :** Unbans everyone in your group.\ \n\n**Syntax : **`.igstat`\ \n**Usage :** Shows stats of Group." } )
'use strict' /* * Create a `add` function that takes 2 number arguments and add them * * @notions Primitive and Operators, Functions */ // Your code : function add (number1, number2){ return number1 + number2; } //* Begin of tests const assert = require('assert') const rand = Math.random() assert.strictEqual(typeof add, 'function') assert.strictEqual(add.length, 2) assert.strictEqual(add(2, 2), 4) assert.strictEqual(add(rand, rand), rand + rand) // End of tests */
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/8/2 21:33 # @Author : Raymound luo # @Mail : luolinhao1998@gmail.com # @File : CGNN.py # @Software: PyCharm # @Describe: import torch import torch.nn as nn import dgl.function as fn import json import torch.nn.functional as F class ContextGNN(nn.Module): def __init__(self, g, model_config): super(ContextGNN, self).__init__() self.g = g self.primary_type = model_config['primary_type'] self.auxiliary_embedding = model_config['auxiliary_embedding'] self.K_length = model_config['K_length'] self.primary_emb = nn.Embedding(g.number_of_nodes( self.primary_type), model_config['embedding_dim']) self.enable_gru = model_config['gru'] self.enable_add_init = model_config['add_init'] self.ntypes = g.ntypes self.etypes = g.etypes if self.auxiliary_embedding == "emb": self.auxiliary_emb = nn.ModuleDict( {ntype: nn.Embedding(g.number_of_nodes(ntype), model_config['embedding_dim']) for ntype in g.ntypes if ntype != self.primary_type}) else: self.auxiliary_tans_fuc = nn.ModuleDict({ etype: EmbTransformer(model_config['in_dim'], model_config['out_dim'], self.auxiliary_embedding) for etype in g.etypes }) self.multihead_cgnn = nn.ModuleList( [MultiHeadCGNN(model_config['in_dim'], model_config['out_dim'], model_config['num_heads'], merge=model_config['merge'], g_agg_type=model_config['g_agg_type'], drop_out=model_config['drop_out'], cgnn_non_linear=model_config['cgnn_non_linear'], multi_attn_linear=model_config['multi_attn_linear'], ntypes=g.ntypes, etypes=g.etypes, graph_attention=model_config['graph_attention'], kq_linear_out_dim=model_config['kq_linear_out_dim'], path_attention=model_config['path_attention'], c_linear_out_dim=model_config['c_linear_out_dim'], enable_bilinear=model_config['enable_bilinear']) for hop in range(self.K_length + 1) # self.K_length + 1 (self.K_length + 1) // 2 + 1 ]) self.loss_weight = nn.Parameter(torch.zeros(self.K_length + 1)) if self.enable_gru: self.gru_gate = nn.GRUCell( model_config['out_dim'], model_config['out_dim']) self.reset_parameter() def reset_parameter(self): if self.auxiliary_embedding == "emb": [nn.init.normal_(emb.weight) for emb in self.auxiliary_emb.values()] else: [nn.init.normal_(func.linear.weight) for func in self.auxiliary_tans_fuc.values()] def embedding_transformer(self, primary_feature): ''' Get HIN feature dict for each node type :param primary_feature: Primary Graph feature :return: h_dict, {ntype, feature} ''' if self.auxiliary_embedding == "emb": h_dict = {ntype: emb.weight for ntype, emb in self.auxiliary_emb.items()} h_dict[self.primary_type] = primary_feature else: h_dict = {} non_init_graph = self.g.ntypes[:] # Copy list h_dict[self.primary_type] = primary_feature non_init_graph.remove(self.primary_type) while non_init_graph: for srctype, etype, dsttype in self.g.canonical_etypes: if srctype not in non_init_graph and dsttype in non_init_graph: h_dict[dsttype] = self.auxiliary_tans_fuc[etype](self.g, h_dict[srctype], srctype, etype, dsttype) non_init_graph.remove(dsttype) return h_dict def dump_cgnn_attention_matrix(self, path): ''' Dump multi head attention matrix to json :param path: path to json file :return: ''' with open(path, 'w') as f: multi_head_attention_matrix = {} for k, layer in enumerate(self.multihead_cgnn): hop_multi_head_matrix = layer.dump_multi_head_attention_matrix() multi_head_attention_matrix["length_{}".format( k)] = hop_multi_head_matrix json.dump(multi_head_attention_matrix, f) def forward(self, k): ''' :param k: k-hop :return: K_length feature emb h_feature of primary type ''' h_dict = self.embedding_transformer( self.primary_emb.weight) # Generate emb for auxiliary graph # KCI # k = k // 2 + 1 for hop in range(k): new_h_dict = self.multihead_cgnn[hop]( self.g, h_dict) # multi head CGNN if self.enable_gru: # Enable Gru new_primary_feature = self.gru_gate(new_h_dict[self.primary_type], h_dict[self.primary_type]) # GRU gate for primary graph new_h_dict[self.primary_type] = new_primary_feature if self.enable_add_init: new_h_dict[self.primary_type] += self.primary_emb.weight h_dict = new_h_dict return h_dict[self.primary_type] def _context_score(self, src, dst, p_emb, context_emb): logits = torch.sum((p_emb[src] * context_emb[src]) * (p_emb[dst] * context_emb[dst]), dim=1) return logits def get_loss(self, k_hop, pos_src, pos_dst, neg_src, neg_dst, p_emb, p_context_emb): # k_length = k_hop // 2 k_length = k_hop - 1 pos_score = self._context_score(pos_src, pos_dst, p_emb, p_context_emb) neg_score = self._context_score(neg_src, neg_dst, p_emb, p_context_emb) # pos_score = torch.clamp(pos_score, max=10, min=-10) pos_loss = -F.logsigmoid(pos_score).view(-1).mean() # neg_score = torch.clamp(neg_score, max=10, min=-10) neg_loss = -F.logsigmoid(-neg_score).view(-1).mean() # Multi loss weight = torch.exp(-self.loss_weight[k_length]) return (pos_loss + neg_loss) * weight + self.loss_weight[ k_length] # torch.mean(torch.cat((pos_score, neg_score))) class EmbTransformer(nn.Module): def __init__(self, in_feat, out_feat, apply_linear='linear'): super(EmbTransformer, self).__init__() self.linear = nn.Linear(in_feat, out_feat) self.apply_linear = apply_linear def forward(self, g, src_h, srctype, etype, dsttype): g.nodes[srctype].data['h'] = src_h g[etype].update_all(fn.copy_src('h', 'm'), fn.sum(msg='m', out='h')) if self.apply_linear == 'non_linear': return torch.relu(self.linear(g.nodes[dsttype].data['h'])) else: return self.linear(g.nodes[dsttype].data['h']) class MultiHeadCGNN(nn.Module): def __init__(self, in_dim, out_dim, num_heads, merge='linear', g_agg_type="mean", drop_out=0., cgnn_non_linear=False, multi_attn_linear=False, ntypes=None, etypes=None, graph_attention=True, kq_linear_out_dim=None, path_attention=True, c_linear_out_dim=None, enable_bilinear=False): super(MultiHeadCGNN, self).__init__() self.heads = nn.ModuleList() cgnn_out_dim = out_dim // num_heads if merge == 'stack' or merge == 'linear' else out_dim for i in range(num_heads): self.heads.append( CGNNLayer(in_dim, cgnn_out_dim, g_agg_type, drop_out, cgnn_non_linear, multi_attn_linear, ntypes, etypes, graph_attention, kq_linear_out_dim, path_attention, c_linear_out_dim, enable_bilinear)) self.merge = merge # W_2 self.cgnn_non_linear = cgnn_non_linear if merge == 'linear': self.fc = nn.Linear(out_dim, out_dim) self.reset_parameters() def reset_parameters(self): nn.init.xavier_normal_(self.fc.weight) def dump_multi_head_attention_matrix(self): ''' Reutrn attention matrix of each head :return: multi_head_matrix_dict {h_head, attention matrix of head h} ''' multi_head_matrix_dict = {} for h, head in enumerate(self.heads): head_matrix = head.dump_attention_matrix() multi_head_matrix_dict['head_{}'.format(h)] = head_matrix return multi_head_matrix_dict def forward(self, g, h): head_outs = [attn_head(g, h) for attn_head in self.heads] h_dict = {} if self.merge == 'linear': # concat on the output feature dimension (dim=1) for ntype in g.ntypes: n_feature = torch.cat([feature[ntype] for feature in head_outs], dim=1) h_dict[ntype] = self.fc(n_feature) elif self.merge == 'mean': # merge using average for ntype in g.ntypes: n_feature = torch.stack([feature[ntype] for feature in head_outs], dim=1) h_dict[ntype] = torch.mean(n_feature, dim=1) elif self.merge == 'stack': for ntype in g.ntypes: n_feature = torch.cat([feature[ntype] for feature in head_outs], dim=1) h_dict[ntype] = n_feature return h_dict class CGNNLayer(nn.Module): def __init__(self, in_dim, out_dim, g_agg_type="mean", drop_out=0., cgnn_non_linear=False, multi_attn_linear=False, ntypes=None, etypes=None, graph_attention=True, kq_linear_out_dim=None, path_attention=True, c_linear_out_dim=None, enable_bilinear=False): super(CGNNLayer, self).__init__() self.graph_attention_matrix = {} self.g_agg_type = g_agg_type # Graph aggregation type self.multi_attn_linear = multi_attn_linear self.cgnn_non_linear = cgnn_non_linear self.graph_attention = graph_attention self.path_attention = path_attention self.enable_bilinear = enable_bilinear if self.multi_attn_linear: self.k_linear = nn.ModuleDict() self.q_linear = nn.ModuleDict() self.c_linear = nn.ModuleDict() for ntype in ntypes: self.k_linear[ntype] = nn.Linear( in_dim, kq_linear_out_dim, bias=False) self.q_linear[ntype] = nn.Linear( in_dim, kq_linear_out_dim, bias=False) self.c_linear[ntype] = nn.Linear( in_dim, c_linear_out_dim, bias=False) else: # K-linear self.k_linear = nn.Linear(in_dim, kq_linear_out_dim, bias=False) # Q-linear self.q_linear = nn.Linear(in_dim, kq_linear_out_dim, bias=False) self.c_linear = nn.Linear(in_dim, c_linear_out_dim, bias=False) # W_1 if self.cgnn_non_linear: self.fc = nn.Sequential( nn.Linear(in_dim, out_dim), nn.ReLU() ) else: self.fc = nn.Linear(in_dim, out_dim) self.node_dropout = nn.Dropout2d(drop_out) self.attn_fc = nn.Linear(2 * c_linear_out_dim, 1, bias=False) if enable_bilinear: self.bilinear = nn.ModuleDict() for etype in etypes: self.bilinear[etype] = nn.Bilinear(kq_linear_out_dim, kq_linear_out_dim, 1) self.reset_parameters() def reset_parameters(self): """Reinitialize learnable parameters.""" if self.multi_attn_linear: for linear in self.k_linear.values(): nn.init.xavier_normal_(linear.weight) for linear in self.q_linear.values(): nn.init.xavier_normal_(linear.weight) else: nn.init.xavier_normal_(self.k_linear.weight) nn.init.xavier_normal_(self.q_linear.weight) if self.cgnn_non_linear: nn.init.xavier_normal_(self.fc[0].weight) else: nn.init.xavier_normal_(self.fc.weight) def graph_aggregation(self, h): ''' How to aggregate graph information :param h: Node embedding (N, D) :return: Graph representation (D) ''' if self.g_agg_type == "mean": return torch.mean(h, dim=0) elif self.g_agg_type == "sum": return torch.sum(h, dim=0) return def dump_attention_matrix(self): ''' Return the attention matrix of each hop :return: graph_attention_matrix attention_matrix {etype, attention score} ''' return self.graph_attention_matrix def context_edge_attention(self, edges): # s_ij = W(h_i||h_j) z = torch.cat((edges.src['C_h'], edges.dst['C_h']), dim=1) c_A = self.attn_fc(z) # c_A = torch.sum(edges.src['Q_h'] * edges.dst['K_h'], dim=1) / (edges.dst['K_h'].shape[-1] ** (1 / 2)) return {'c_A': c_A.squeeze(-1)} def context_attention(self, g): ''' Context edges attention score :param g: :return: g with k,q feature for each node ''' for ntype in g.ntypes: if self.multi_attn_linear: g.nodes[ntype].data['C_h'] = self.c_linear[ntype]( g.nodes[ntype].data['h']) else: g.nodes[ntype].data['C_h'] = self.c_linear( g.nodes[ntype].data['h']) for etype in g.etypes: g.apply_edges(self.context_edge_attention, etype=etype) return g def msg_func(self, edges): return {'h': edges.src['h'], 'C_h': edges.src['C_h'], 'g_A': edges.data['g_A'], 'c_A': edges.data['c_A']} def reduce_func(self, nodes): # S_j # sim_matrix = torch.tanh(torch.bmm(nodes.mailbox['C_h'], nodes.mailbox['C_h'].transpose(1, 2)) / ( # nodes.mailbox['C_h'].shape[-1] ** (1 / 2))) # sim_J = torch.mean(sim_matrix, dim=2) # \sigma(s_ij-S_j) e = F.leaky_relu(nodes.mailbox['c_A']) # nodes.mailbox['c_A'] - sim_J alpha = F.softmax(e, dim=1).unsqueeze(-1) h = nodes.mailbox['g_A'][:, 0].unsqueeze(-1) * torch.sum(alpha * nodes.mailbox['h'], dim=1) return {'h': h} def forward(self, g, h): ''' CGNN :param g: graph :param h: feature dict {ntype, feature} :return: h: feature dict {ntype, feature} ''' # The input is a dictionary of node features for each type funcs = {} graph_feature = {} for ntype in g.ntypes: h_feat = h[ntype].unsqueeze(0) # (1, N , D) feat = self.node_dropout(h_feat) feat = feat.squeeze(0) # (N, D) graph_feature[ntype] = self.graph_aggregation( feat) # Graph Aggregation g.nodes[ntype].data['h'] = feat # Context Edges attention: if self.path_attention: g = self.context_attention(g) # Graph Attention if self.graph_attention: l_hop_graph_attention = {} for q_dsttype in g.ntypes: context_feature = [] if self.multi_attn_linear: q_h = self.q_linear[q_dsttype](graph_feature[q_dsttype]) else: q_h = self.q_linear(graph_feature[q_dsttype]) # k linear # Compute attention score for each other graph for k_srctype, k_etype, k_dsttype in g.canonical_etypes: # Score only exists when two graphs are connected if q_dsttype != k_dsttype: continue if self.multi_attn_linear: k_h = self.k_linear[k_srctype]( graph_feature[k_srctype]) else: k_h = self.k_linear( graph_feature[k_srctype]) # q linear # A = g.number_of_edges(q_etype) # V if self.enable_bilinear: z = self.bilinear[k_etype](k_h, q_h) else: z = torch.sum(k_h * q_h) / \ (k_h.shape[-1] ** (1 / 2)) # ATThead context_feature.append((k_etype, z)) c_feature = torch.stack( [score for _, score in context_feature]) c_attention_matrix = torch.softmax(c_feature, dim=0) for i, (etype, score) in enumerate(context_feature): att_score = c_attention_matrix[i] g.edges[etype].data['g_A'] = att_score.expand( g.number_of_edges(etype)) # Bind attention score to edge feature l_hop_graph_attention[etype] = float( c_attention_matrix[i].detach().cpu().numpy()) self.graph_attention_matrix = l_hop_graph_attention # h: source node feature, g_A: Graph attention score between two graphs, c_A: Attentnion score between two nodes, m: result for etype in g.etypes: if self.path_attention: funcs[etype] = (self.msg_func, self.reduce_func) elif self.graph_attention: funcs[etype] = (fn.u_mul_e('h', 'g_A', 'm'), fn.sum('m', 'h')) else: funcs[etype] = (fn.copy_src('h', 'm'), fn.sum('m', 'h')) g.multi_update_all(funcs, 'sum') return {ntype: self.fc(g.nodes[ntype].data['h']) for ntype in g.ntypes}
import torch, argparse, sys def save_likelihoods(model_path, data_dir_prefix='./data/snli_1.0/cl_snli', output_file=None): pass def parse_cli(): p = argparse.ArgumentParser(description='Save likelihoods for a given model and dataset') p.set_defaults(subcmd_fn=save_likelihoods) p.add_argument('--model-path', help='Path to your model', required=True) p.add_argument('--data-dir-prefix', help='Path to the dataset', default='./data/snli_1.0/cl_snli') p.add_argument('--output-file', '-o', help='Where would you like to save the results', default=None) # sp = p.add_subparsers(help='Sub-commands') # # Experiment config # sp_exp = sp.add_parser('train', help='Train a model') # sp_exp.set_defaults(subcmd_fn=save_likelihoods) # sp_exp.add_argument('--run-name', '-n', type=str, # help='Name of run and output file', required=True) parsed = p.parse_args() if 'subcmd_fn' not in parsed: p.print_help() sys.exit() return parsed if __name__ == '__main__': torch.cuda.empty_cache() parsed_args = parse_cli() subcmd_fn = parsed_args.subcmd_fn del parsed_args.subcmd_fn if torch.cuda.device_count() > 1: from multiprocessing import set_start_method try: set_start_method('spawn') except RuntimeError: pass print(f'*** Starting {subcmd_fn.__name__} with config:\n{parsed_args}') subcmd_fn(**vars(parsed_args))
/** * Actions bundle. * * @type {Object} */ const Action = { clear: require('./clear'), show: require('./show'), hide: require('./hide'), upgrade: require('./upgrade'), downgrade: require('./downgrade'), activate: require('./activate') }; module.exports = Action;
module.exports = { verbose: true, testEnvironment: 'jsdom', moduleFileExtensions: ['js', 'vue'], transform: { '^.+\\.vue$': 'vue-jest', '^.+\\.js$': '<rootDir>/node_modules/babel-jest', }, snapshotSerializers: ['<rootDir>/node_modules/jest-serializer-vue'], };
// Copyright 2021, University of Colorado Boulder // Auto-generated by modulifyFontAwesomeIcons.js, please do not modify directly. import Shape from '../../../../kite/js/Shape.js'; import jogetString from './jogetString.js'; export default new Shape( jogetString );
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Written by Kyle Carhart. <<<<<<< HEAD Email: kcarhart@email.sc.edu ======= >>>>>>> 13fbc54d639a4a028fed58f3e5d1adff32f3b3ee Description: Takes cases that have been resolved in The Hive within a specified interval and imports them to LimeSurvey as new responses. Users then go to the survey, input the case number and complete the survey. """ from ConfigParser import SafeConfigParser from datetime import datetime import logging import time import os import urllib3 from hive2lime.hive import Hive from hive2lime.lime import Lime from hive2lime.mailclient import MailClient def main(): PARSER.read('./config/misc.ini') interval = PARSER.getint("script", "interval") current_milli_time = int(round(time.time() * 1000)) interval_time_ago = current_milli_time - interval # time ago from the interval hive = Hive(debug=DEBUG) query = { "_and":[ { "_string": "(status:\"Resolved\") AND endDate:[ {} TO * ]".format(interval_time_ago) } ] } # grab all the cases from hive that have been completed interval_time_ago cases = hive.search(query, "all", ["+caseId"]) if cases: case_numbers = [] for case in cases: case_numbers.append(str(case["caseId"])) if DEBUG: logging.debug("%s cases resolved: %s", len(cases), ", ".join(case_numbers)) else: if DEBUG: logging.debug("No cases resolved today.") logging.info("Exiting successfully.") exit() PARSER.read('./config/lime.ini') tokens = {} for name, value in PARSER.items("tokens"): tokens[name] = value lime = Lime(debug=DEBUG) for case in cases: response = lime.create_json(case, tokens.get(case["updatedBy"], "")) srid = lime.add_response(response) lime.save_response(case["caseId"], srid) incomplete_cases = lime.export_responses() mailclient = MailClient(debug=DEBUG) mailclient.multisend(incomplete_cases, tokens) lime.release_session() if __name__ == "__main__": # change working environment so relative paths work. "./XXX/X.ini" abspath = os.path.abspath(__file__) dname = os.path.dirname(abspath) os.chdir(dname) # get rid of annoying insecure warnings urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) # Check if debugging is on. PARSER = SafeConfigParser() PARSER.read('./config/misc.ini') DEBUG = PARSER.getboolean("script", "debug") # configure the debugger to write logs. if DEBUG: logging.getLogger("urllib3").setLevel(logging.WARNING) DEBUG_STATE = str(datetime.fromtimestamp(int(round(time.time()))).strftime('%Y-%m-%d')) + '.txt' logging.basicConfig( filename="./log/{}".format(DEBUG_STATE), format='%(levelname)s:%(message)s', level=logging.DEBUG, filemode='w') logging.info("Starting.") try: main() if DEBUG: logging.info("Exiting successfully.") except (ValueError, TypeError, Exception) as e: if DEBUG: logging.error(e.message) logging.info("Exiting with error.")
import json from django.urls import reverse from common.code import * from .models import ExtendedUser as User from rest_framework.test import APITestCase class AccountCreateTests(APITestCase): def setUp(self): self.url = reverse('account-register') def tearDown(self): response = self.client.post(self.url, self.data, format='json') content = json.loads(response.content) self.assertEqual(content['code'], self.code) def test_correct_1(self): # correct password # correct email # correct name self.data = { 'username': 'daddy', 'password': '123ASDab123A', 'email': 'abc@qq11.com', 'first_name': 'test', 'last_name': 'gg' } self.code = ACCOUNT_REGISTER_SUCCESS class AccountLoginTests(APITestCase): def setUp(self): self.url = reverse('account-login') self.user = User.objects.create_user(username='daddy', password='passwordASD123', email='email@email.com', first_name='first', last_name='last') def tearDown(self): response = self.client.post(self.url, self.data, format='json') content = json.loads(response.content) self.assertEqual(content['code'], self.code) def test_correct_1(self): # correct credentials self.data = { 'username': 'daddy', 'password': 'passwordASD123' } self.code = ACCOUNT_LOGIN_SUCCESS class AccountLogoutTests(APITestCase): def setUp(self): self.url = reverse('account-logout') self.user = User.objects.create_user(username='daddy', password='passwordASD123', email='email@email.com', first_name='first', last_name='last') data = { 'username': 'daddy', 'password': 'passwordASD123' } response = self.client.post(reverse('account-login'), data, format='json') content = json.loads(response.content) self.token = content['token'] def tearDown(self): response = self.client.post(self.url, self.data, format='json') content = json.loads(response.content) self.assertEqual(content['code'], self.code) def test_correct_1(self): # correct token self.data = { 'token': self.token } self.code = ACCOUNT_LOGOUT_SUCCESS class AccountGetTests(APITestCase): def setUp(self): self.url = reverse('account-get') self.user = User.objects.create_user(username='daddy', password='passwordASD123', email='email@email.com', first_name='first', last_name='last') data = { 'username': 'daddy', 'password': 'passwordASD123' } response = self.client.post(reverse('account-login'), data, format='json') content = json.loads(response.content) self.token = content['token'] def tearDown(self): response = self.client.post(self.url, self.data, format='json') content = json.loads(response.content) self.assertEqual(content['code'], self.code) if self.code == ACCOUNT_GET_SUCCESS: self.assertEqual(content['details']['first_name'], self.user.first_name) self.assertEqual(content['details']['last_name'], self.user.last_name) self.assertEqual(content['details']['email'], self.user.email) def test_correct_1(self): # correct token self.data = { 'token': self.token } self.code = ACCOUNT_GET_SUCCESS def test_wrong_1(self): # wrong token self.data = { 'token': 'abc' } self.code = ACCOUNT_TOKEN_ERROR
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[83],{ /***/ "./node_modules/@babel/runtime/helpers/classCallCheck.js": /*!***************************************************************!*\ !*** ./node_modules/@babel/runtime/helpers/classCallCheck.js ***! \***************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { eval("function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\n\nmodule.exports = _classCallCheck;//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9ub2RlX21vZHVsZXMvQGJhYmVsL3J1bnRpbWUvaGVscGVycy9jbGFzc0NhbGxDaGVjay5qcy5qcyIsInNvdXJjZXMiOlsid2VicGFjazovLy8uL25vZGVfbW9kdWxlcy9AYmFiZWwvcnVudGltZS9oZWxwZXJzL2NsYXNzQ2FsbENoZWNrLmpzPzk3MGIiXSwic291cmNlc0NvbnRlbnQiOlsiZnVuY3Rpb24gX2NsYXNzQ2FsbENoZWNrKGluc3RhbmNlLCBDb25zdHJ1Y3Rvcikge1xuICBpZiAoIShpbnN0YW5jZSBpbnN0YW5jZW9mIENvbnN0cnVjdG9yKSkge1xuICAgIHRocm93IG5ldyBUeXBlRXJyb3IoXCJDYW5ub3QgY2FsbCBhIGNsYXNzIGFzIGEgZnVuY3Rpb25cIik7XG4gIH1cbn1cblxubW9kdWxlLmV4cG9ydHMgPSBfY2xhc3NDYWxsQ2hlY2s7Il0sIm1hcHBpbmdzIjoiQUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSIsInNvdXJjZVJvb3QiOiIifQ==\n//# sourceURL=webpack-internal:///./node_modules/@babel/runtime/helpers/classCallCheck.js\n"); /***/ }), /***/ "./node_modules/@babel/runtime/helpers/createClass.js": /*!************************************************************!*\ !*** ./node_modules/@babel/runtime/helpers/createClass.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { eval("function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n}\n\nmodule.exports = _createClass;//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9ub2RlX21vZHVsZXMvQGJhYmVsL3J1bnRpbWUvaGVscGVycy9jcmVhdGVDbGFzcy5qcy5qcyIsInNvdXJjZXMiOlsid2VicGFjazovLy8uL25vZGVfbW9kdWxlcy9AYmFiZWwvcnVudGltZS9oZWxwZXJzL2NyZWF0ZUNsYXNzLmpzPzViYzMiXSwic291cmNlc0NvbnRlbnQiOlsiZnVuY3Rpb24gX2RlZmluZVByb3BlcnRpZXModGFyZ2V0LCBwcm9wcykge1xuICBmb3IgKHZhciBpID0gMDsgaSA8IHByb3BzLmxlbmd0aDsgaSsrKSB7XG4gICAgdmFyIGRlc2NyaXB0b3IgPSBwcm9wc1tpXTtcbiAgICBkZXNjcmlwdG9yLmVudW1lcmFibGUgPSBkZXNjcmlwdG9yLmVudW1lcmFibGUgfHwgZmFsc2U7XG4gICAgZGVzY3JpcHRvci5jb25maWd1cmFibGUgPSB0cnVlO1xuICAgIGlmIChcInZhbHVlXCIgaW4gZGVzY3JpcHRvcikgZGVzY3JpcHRvci53cml0YWJsZSA9IHRydWU7XG4gICAgT2JqZWN0LmRlZmluZVByb3BlcnR5KHRhcmdldCwgZGVzY3JpcHRvci5rZXksIGRlc2NyaXB0b3IpO1xuICB9XG59XG5cbmZ1bmN0aW9uIF9jcmVhdGVDbGFzcyhDb25zdHJ1Y3RvciwgcHJvdG9Qcm9wcywgc3RhdGljUHJvcHMpIHtcbiAgaWYgKHByb3RvUHJvcHMpIF9kZWZpbmVQcm9wZXJ0aWVzKENvbnN0cnVjdG9yLnByb3RvdHlwZSwgcHJvdG9Qcm9wcyk7XG4gIGlmIChzdGF0aWNQcm9wcykgX2RlZmluZVByb3BlcnRpZXMoQ29uc3RydWN0b3IsIHN0YXRpY1Byb3BzKTtcbiAgcmV0dXJuIENvbnN0cnVjdG9yO1xufVxuXG5tb2R1bGUuZXhwb3J0cyA9IF9jcmVhdGVDbGFzczsiXSwibWFwcGluZ3MiOiJBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EiLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///./node_modules/@babel/runtime/helpers/createClass.js\n"); /***/ }), /***/ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=script&lang=js&": /*!*****************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=script&lang=js& ***! \*****************************************************************************************************************************************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ \"./node_modules/@babel/runtime/regenerator/index.js\");\n/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ \"./node_modules/@babel/runtime/helpers/asyncToGenerator.js\");\n/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);\n/* harmony import */ var _api_resource__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @/api/resource */ \"./resources/js/api/resource.js\");\n\n\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n\nvar perfilEmpresaResource = new _api_resource__WEBPACK_IMPORTED_MODULE_2__[\"default\"]('perfilEmpresa');\nvar embarqueResource = new _api_resource__WEBPACK_IMPORTED_MODULE_2__[\"default\"]('embarques');\n\nvar logoEmpresa = __webpack_require__(/*! @/assets/empresa/logo-dsi.jpeg */ \"./resources/js/assets/empresa/logo-dsi.jpeg\").default;\n\n/* harmony default export */ __webpack_exports__[\"default\"] = ({\n data: function data() {\n return {\n logoEmpresa: logoEmpresa,\n article: '',\n fullscreenLoading: true,\n id: 0,\n perfil_empresa_id: 0,\n query: {\n page: 1,\n limit: 15,\n keyword: '',\n role: '',\n id: ''\n },\n embarques: [],\n embarque: {\n cliente: {\n nombre_cliente: ''\n }\n },\n perfil_empresa: []\n };\n },\n created: function created() {\n this.id = this.$route.params.id;\n },\n mounted: function mounted() {\n this.fetchData();\n },\n methods: {\n fetchData: function fetchData() {// this.getPerfilEmpresa();\n // this.query.id = this.id;\n // await embarqueResource.list(this.query).then(data => {\n // this.embarques = data.data;\n // this.embarque = data.data[0];\n // setTimeout(() => {\n // this.fullscreenLoading = false;\n // this.$nextTick(() => {\n // window.print();\n // });\n // }, 3000);\n // });\n\n return _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {\n return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n case \"end\":\n return _context.stop();\n }\n }\n }, _callee);\n }))();\n }\n }\n});//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9ub2RlX21vZHVsZXMvYmFiZWwtbG9hZGVyL2xpYi9pbmRleC5qcz8hLi9ub2RlX21vZHVsZXMvdnVlLWxvYWRlci9saWIvaW5kZXguanM/IS4vcmVzb3VyY2VzL2pzL3ZpZXdzL2VtcGxlYWRvcy9jb21wb25lbnRzL2NvbnRyYXRvX2VtcGxlYWRvX2Rvd25sb2FkLnZ1ZT92dWUmdHlwZT1zY3JpcHQmbGFuZz1qcyYuanMiLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvanMvdmlld3MvZW1wbGVhZG9zL2NvbXBvbmVudHMvY29udHJhdG9fZW1wbGVhZG9fZG93bmxvYWQudnVlPzNjZWYiXSwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IF9yZWdlbmVyYXRvclJ1bnRpbWUgZnJvbSBcIkBiYWJlbC9ydW50aW1lL3JlZ2VuZXJhdG9yXCI7XG5pbXBvcnQgX2FzeW5jVG9HZW5lcmF0b3IgZnJvbSBcIkBiYWJlbC9ydW50aW1lL2hlbHBlcnMvYXN5bmNUb0dlbmVyYXRvclwiO1xuLy9cbi8vXG4vL1xuLy9cbi8vXG4vL1xuLy9cbi8vXG4vL1xuLy9cbi8vXG4vL1xuLy9cbi8vXG4vL1xuLy9cbi8vXG4vL1xuLy9cbi8vXG4vL1xuLy9cbi8vXG4vL1xuLy9cbi8vXG4vL1xuLy9cbi8vXG4vL1xuLy9cbi8vXG4vL1xuLy9cbi8vXG4vL1xuLy9cbi8vXG4vL1xuLy9cbi8vXG4vL1xuLy9cbmltcG9ydCBSZXNvdXJjZSBmcm9tICdAL2FwaS9yZXNvdXJjZSc7XG52YXIgcGVyZmlsRW1wcmVzYVJlc291cmNlID0gbmV3IFJlc291cmNlKCdwZXJmaWxFbXByZXNhJyk7XG52YXIgZW1iYXJxdWVSZXNvdXJjZSA9IG5ldyBSZXNvdXJjZSgnZW1iYXJxdWVzJyk7XG5cbnZhciBsb2dvRW1wcmVzYSA9IHJlcXVpcmUoJ0AvYXNzZXRzL2VtcHJlc2EvbG9nby1kc2kuanBlZycpLmRlZmF1bHQ7XG5cbmV4cG9ydCBkZWZhdWx0IHtcbiAgZGF0YTogZnVuY3Rpb24gZGF0YSgpIHtcbiAgICByZXR1cm4ge1xuICAgICAgbG9nb0VtcHJlc2E6IGxvZ29FbXByZXNhLFxuICAgICAgYXJ0aWNsZTogJycsXG4gICAgICBmdWxsc2NyZWVuTG9hZGluZzogdHJ1ZSxcbiAgICAgIGlkOiAwLFxuICAgICAgcGVyZmlsX2VtcHJlc2FfaWQ6IDAsXG4gICAgICBxdWVyeToge1xuICAgICAgICBwYWdlOiAxLFxuICAgICAgICBsaW1pdDogMTUsXG4gICAgICAgIGtleXdvcmQ6ICcnLFxuICAgICAgICByb2xlOiAnJyxcbiAgICAgICAgaWQ6ICcnXG4gICAgICB9LFxuICAgICAgZW1iYXJxdWVzOiBbXSxcbiAgICAgIGVtYmFycXVlOiB7XG4gICAgICAgIGNsaWVudGU6IHtcbiAgICAgICAgICBub21icmVfY2xpZW50ZTogJydcbiAgICAgICAgfVxuICAgICAgfSxcbiAgICAgIHBlcmZpbF9lbXByZXNhOiBbXVxuICAgIH07XG4gIH0sXG4gIGNyZWF0ZWQ6IGZ1bmN0aW9uIGNyZWF0ZWQoKSB7XG4gICAgdGhpcy5pZCA9IHRoaXMuJHJvdXRlLnBhcmFtcy5pZDtcbiAgfSxcbiAgbW91bnRlZDogZnVuY3Rpb24gbW91bnRlZCgpIHtcbiAgICB0aGlzLmZldGNoRGF0YSgpO1xuICB9LFxuICBtZXRob2RzOiB7XG4gICAgZmV0Y2hEYXRhOiBmdW5jdGlvbiBmZXRjaERhdGEoKSB7Ly8gdGhpcy5nZXRQZXJmaWxFbXByZXNhKCk7XG4gICAgICAvLyB0aGlzLnF1ZXJ5LmlkID0gdGhpcy5pZDtcbiAgICAgIC8vIGF3YWl0IGVtYmFycXVlUmVzb3VyY2UubGlzdCh0aGlzLnF1ZXJ5KS50aGVuKGRhdGEgPT4ge1xuICAgICAgLy8gICB0aGlzLmVtYmFycXVlcyA9IGRhdGEuZGF0YTtcbiAgICAgIC8vICAgdGhpcy5lbWJhcnF1ZSA9IGRhdGEuZGF0YVswXTtcbiAgICAgIC8vICAgc2V0VGltZW91dCgoKSA9PiB7XG4gICAgICAvLyAgICAgdGhpcy5mdWxsc2NyZWVuTG9hZGluZyA9IGZhbHNlO1xuICAgICAgLy8gICAgIHRoaXMuJG5leHRUaWNrKCgpID0+IHtcbiAgICAgIC8vICAgICAgIHdpbmRvdy5wcmludCgpO1xuICAgICAgLy8gICAgIH0pO1xuICAgICAgLy8gICB9LCAzMDAwKTtcbiAgICAgIC8vIH0pO1xuXG4gICAgICByZXR1cm4gX2FzeW5jVG9HZW5lcmF0b3IoIC8qI19fUFVSRV9fKi9fcmVnZW5lcmF0b3JSdW50aW1lLm1hcmsoZnVuY3Rpb24gX2NhbGxlZSgpIHtcbiAgICAgICAgcmV0dXJuIF9yZWdlbmVyYXRvclJ1bnRpbWUud3JhcChmdW5jdGlvbiBfY2FsbGVlJChfY29udGV4dCkge1xuICAgICAgICAgIHdoaWxlICgxKSB7XG4gICAgICAgICAgICBzd2l0Y2ggKF9jb250ZXh0LnByZXYgPSBfY29udGV4dC5uZXh0KSB7XG4gICAgICAgICAgICAgIGNhc2UgMDpcbiAgICAgICAgICAgICAgY2FzZSBcImVuZFwiOlxuICAgICAgICAgICAgICAgIHJldHVybiBfY29udGV4dC5zdG9wKCk7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgfVxuICAgICAgICB9LCBfY2FsbGVlKTtcbiAgICAgIH0pKSgpO1xuICAgIH1cbiAgfVxufTsiXSwibWFwcGluZ3MiOiJBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwic291cmNlUm9vdCI6IiJ9\n//# sourceURL=webpack-internal:///./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=script&lang=js&\n"); /***/ }), /***/ "./node_modules/css-loader/dist/cjs.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=style&index=0&rel=stylesheet%2Fscss&lang=scss&": /*!**************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/css-loader/dist/cjs.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--6-2!./node_modules/sass-loader/dist/cjs.js??ref--6-3!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=style&index=0&rel=stylesheet%2Fscss&lang=scss& ***! \**************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { eval("// Imports\nvar ___CSS_LOADER_API_IMPORT___ = __webpack_require__(/*! ../../../../../node_modules/css-loader/dist/runtime/api.js */ \"./node_modules/css-loader/dist/runtime/api.js\");\nexports = ___CSS_LOADER_API_IMPORT___(false);\n// Module\nexports.push([module.i, \"#elTable {\\n display: inline-block;\\n -webkit-box-sizing: border-box;\\n box-sizing: border-box;\\n position: relative;\\n vertical-align: middle;\\n padding-left: 10px;\\n padding-right: 10px;\\n width: 100%;\\n}\\n.el-table .cell {\\n word-break: break-word;\\n}\\n.el-table thead {\\n color: #000;\\n}\\n#customer .el-table {\\n font-size: 10px;\\n}\\n#customer .el-table .cell {\\n padding: 0px;\\n line-height: 12px;\\n}\\n.el-table--border {\\n border: 1px solid #dfe6ec;\\n}\\n.main-article {\\n margin: 0 auto;\\n display: block;\\n width: 740px;\\n background: #fff;\\n}\\n.article__heading {\\n position: relative;\\n padding: 0 0 20px;\\n overflow: hidden;\\n}\\n.article__heading__title {\\n display: block;\\n display: -webkit-box;\\n -webkit-box-orient: vertical;\\n -webkit-line-clamp: 2;\\n line-clamp: 2;\\n word-wrap: break-word;\\n overflow-wrap: break-word;\\n font-size: 32px;\\n line-height: 48px;\\n font-weight: 600;\\n color: #333;\\n overflow: hidden;\\n}\\n.node-article-content {\\n margin: 0 0 0;\\n font-size: 12px;\\n color: #333;\\n letter-spacing: 0.5px;\\n line-height: 28px;\\n margin-bottom: 30px;\\n font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif;\\n /*\\r\\n\\t CSS-Tricks Example\\r\\n\\t by Chris Coyier\\r\\n\\t http://css-tricks.com\\r\\n*/\\n}\\n.node-article-content:before {\\n display: table;\\n content: '';\\n clear: both;\\n}\\n.node-article-content:after {\\n display: table;\\n content: '';\\n clear: both;\\n}\\n.node-article-content > :last-child {\\n margin-bottom: 0;\\n}\\n.node-article-content * {\\n margin: 0;\\n padding: 0;\\n}\\n.node-article-content body {\\n font: 14px/1.4;\\n}\\n.node-article-content #page-wrap {\\n width: 100%;\\n margin: 0 auto;\\n}\\n.node-article-content textarea {\\n border: 0;\\n overflow: hidden;\\n resize: none;\\n}\\n.node-article-content textarea:hover, .node-article-content textarea:focus, .node-article-content #items td.total-value textarea:hover, .node-article-content #items td.total-value textarea:focus, .node-article-content .delete:hover {\\n background-color: #EEFF88;\\n}\\n.node-article-content #ordenes textarea {\\n text-align: center;\\n vertical-align: middle;\\n}\\n.node-article-content table td, .node-article-content table th {\\n padding: 5px;\\n}\\n.node-article-content #header {\\n height: 30px;\\n width: 100%;\\n margin: 0 0;\\n background: #fff;\\n text-align: center;\\n color: black;\\n font: bold 15px Helvetica, Sans-Serif;\\n -webkit-text-decoration: uppercase;\\n text-decoration: uppercase;\\n letter-spacing: 20px;\\n padding: 8px 0px;\\n}\\n.node-article-content #address {\\n width: 400px;\\n height: 150px;\\n float: right;\\n line-height: 12px;\\n text-align: right;\\n font-size: 8px;\\n}\\n.node-article-content #address textarea {\\n width: 50%;\\n text-align: right;\\n}\\n.node-article-content #customer {\\n margin: 0 0 20px 0;\\n overflow: hidden;\\n}\\n.node-article-content #meta {\\n margin-top: 1px;\\n width: 100%;\\n}\\n.node-article-content #image {\\n height: 150px;\\n}\\n.node-article-content #terms {\\n text-align: center;\\n margin-top: 20px;\\n width: 276px;\\n padding-top: 100px;\\n}\\n.node-article-content #terms h5 {\\n text-transform: uppercase;\\n font: 13px;\\n letter-spacing: 10px;\\n border-bottom: 1px solid black;\\n padding: 0 0 8px 0;\\n margin: 0 0 8px 0;\\n}\\n.node-article-content #terms textarea {\\n width: 100%;\\n text-align: center;\\n}\\n\", \"\"]);\n// Exports\nmodule.exports = exports;\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9ub2RlX21vZHVsZXMvY3NzLWxvYWRlci9kaXN0L2Nqcy5qcyEuL25vZGVfbW9kdWxlcy92dWUtbG9hZGVyL2xpYi9sb2FkZXJzL3N0eWxlUG9zdExvYWRlci5qcyEuL25vZGVfbW9kdWxlcy9wb3N0Y3NzLWxvYWRlci9zcmMvaW5kZXguanM/IS4vbm9kZV9tb2R1bGVzL3Nhc3MtbG9hZGVyL2Rpc3QvY2pzLmpzPyEuL25vZGVfbW9kdWxlcy92dWUtbG9hZGVyL2xpYi9pbmRleC5qcz8hLi9yZXNvdXJjZXMvanMvdmlld3MvZW1wbGVhZG9zL2NvbXBvbmVudHMvY29udHJhdG9fZW1wbGVhZG9fZG93bmxvYWQudnVlP3Z1ZSZ0eXBlPXN0eWxlJmluZGV4PTAmcmVsPXN0eWxlc2hlZXQlMkZzY3NzJmxhbmc9c2NzcyYuanMiLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvanMvdmlld3MvZW1wbGVhZG9zL2NvbXBvbmVudHMvY29udHJhdG9fZW1wbGVhZG9fZG93bmxvYWQudnVlP2JhOTIiXSwic291cmNlc0NvbnRlbnQiOlsiLy8gSW1wb3J0c1xudmFyIF9fX0NTU19MT0FERVJfQVBJX0lNUE9SVF9fXyA9IHJlcXVpcmUoXCIuLi8uLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvY3NzLWxvYWRlci9kaXN0L3J1bnRpbWUvYXBpLmpzXCIpO1xuZXhwb3J0cyA9IF9fX0NTU19MT0FERVJfQVBJX0lNUE9SVF9fXyhmYWxzZSk7XG4vLyBNb2R1bGVcbmV4cG9ydHMucHVzaChbbW9kdWxlLmlkLCBcIiNlbFRhYmxlIHtcXG4gIGRpc3BsYXk6IGlubGluZS1ibG9jaztcXG4gIC13ZWJraXQtYm94LXNpemluZzogYm9yZGVyLWJveDtcXG4gIGJveC1zaXppbmc6IGJvcmRlci1ib3g7XFxuICBwb3NpdGlvbjogcmVsYXRpdmU7XFxuICB2ZXJ0aWNhbC1hbGlnbjogbWlkZGxlO1xcbiAgcGFkZGluZy1sZWZ0OiAxMHB4O1xcbiAgcGFkZGluZy1yaWdodDogMTBweDtcXG4gIHdpZHRoOiAxMDAlO1xcbn1cXG4uZWwtdGFibGUgLmNlbGwge1xcbiAgd29yZC1icmVhazogYnJlYWstd29yZDtcXG59XFxuLmVsLXRhYmxlIHRoZWFkIHtcXG4gIGNvbG9yOiAjMDAwO1xcbn1cXG4jY3VzdG9tZXIgLmVsLXRhYmxlIHtcXG4gIGZvbnQtc2l6ZTogMTBweDtcXG59XFxuI2N1c3RvbWVyIC5lbC10YWJsZSAuY2VsbCB7XFxuICBwYWRkaW5nOiAwcHg7XFxuICBsaW5lLWhlaWdodDogMTJweDtcXG59XFxuLmVsLXRhYmxlLS1ib3JkZXIge1xcbiAgYm9yZGVyOiAxcHggc29saWQgI2RmZTZlYztcXG59XFxuLm1haW4tYXJ0aWNsZSB7XFxuICBtYXJnaW46IDAgYXV0bztcXG4gIGRpc3BsYXk6IGJsb2NrO1xcbiAgd2lkdGg6IDc0MHB4O1xcbiAgYmFja2dyb3VuZDogI2ZmZjtcXG59XFxuLmFydGljbGVfX2hlYWRpbmcge1xcbiAgcG9zaXRpb246IHJlbGF0aXZlO1xcbiAgcGFkZGluZzogMCAwIDIwcHg7XFxuICBvdmVyZmxvdzogaGlkZGVuO1xcbn1cXG4uYXJ0aWNsZV9faGVhZGluZ19fdGl0bGUge1xcbiAgZGlzcGxheTogYmxvY2s7XFxuICBkaXNwbGF5OiAtd2Via2l0LWJveDtcXG4gIC13ZWJraXQtYm94LW9yaWVudDogdmVydGljYWw7XFxuICAtd2Via2l0LWxpbmUtY2xhbXA6IDI7XFxuICBsaW5lLWNsYW1wOiAyO1xcbiAgd29yZC13cmFwOiBicmVhay13b3JkO1xcbiAgb3ZlcmZsb3ctd3JhcDogYnJlYWstd29yZDtcXG4gIGZvbnQtc2l6ZTogMzJweDtcXG4gIGxpbmUtaGVpZ2h0OiA0OHB4O1xcbiAgZm9udC13ZWlnaHQ6IDYwMDtcXG4gIGNvbG9yOiAjMzMzO1xcbiAgb3ZlcmZsb3c6IGhpZGRlbjtcXG59XFxuLm5vZGUtYXJ0aWNsZS1jb250ZW50IHtcXG4gIG1hcmdpbjogMCAwIDA7XFxuICBmb250LXNpemU6IDEycHg7XFxuICBjb2xvcjogIzMzMztcXG4gIGxldHRlci1zcGFjaW5nOiAwLjVweDtcXG4gIGxpbmUtaGVpZ2h0OiAyOHB4O1xcbiAgbWFyZ2luLWJvdHRvbTogMzBweDtcXG4gIGZvbnQtZmFtaWx5OiAnSGVsdmV0aWNhIE5ldWUnLCAnSGVsdmV0aWNhJywgSGVsdmV0aWNhLCBBcmlhbCwgc2Fucy1zZXJpZjtcXG4gIC8qXFxyXFxuXFx0IENTUy1Ucmlja3MgRXhhbXBsZVxcclxcblxcdCBieSBDaHJpcyBDb3lpZXJcXHJcXG5cXHQgaHR0cDovL2Nzcy10cmlja3MuY29tXFxyXFxuKi9cXG59XFxuLm5vZGUtYXJ0aWNsZS1jb250ZW50OmJlZm9yZSB7XFxuICBkaXNwbGF5OiB0YWJsZTtcXG4gIGNvbnRlbnQ6ICcnO1xcbiAgY2xlYXI6IGJvdGg7XFxufVxcbi5ub2RlLWFydGljbGUtY29udGVudDphZnRlciB7XFxuICBkaXNwbGF5OiB0YWJsZTtcXG4gIGNvbnRlbnQ6ICcnO1xcbiAgY2xlYXI6IGJvdGg7XFxufVxcbi5ub2RlLWFydGljbGUtY29udGVudCA+IDpsYXN0LWNoaWxkIHtcXG4gIG1hcmdpbi1ib3R0b206IDA7XFxufVxcbi5ub2RlLWFydGljbGUtY29udGVudCAqIHtcXG4gIG1hcmdpbjogMDtcXG4gIHBhZGRpbmc6IDA7XFxufVxcbi5ub2RlLWFydGljbGUtY29udGVudCBib2R5IHtcXG4gIGZvbnQ6IDE0cHgvMS40O1xcbn1cXG4ubm9kZS1hcnRpY2xlLWNvbnRlbnQgI3BhZ2Utd3JhcCB7XFxuICB3aWR0aDogMTAwJTtcXG4gIG1hcmdpbjogMCBhdXRvO1xcbn1cXG4ubm9kZS1hcnRpY2xlLWNvbnRlbnQgdGV4dGFyZWEge1xcbiAgYm9yZGVyOiAwO1xcbiAgb3ZlcmZsb3c6IGhpZGRlbjtcXG4gIHJlc2l6ZTogbm9uZTtcXG59XFxuLm5vZGUtYXJ0aWNsZS1jb250ZW50IHRleHRhcmVhOmhvdmVyLCAubm9kZS1hcnRpY2xlLWNvbnRlbnQgdGV4dGFyZWE6Zm9jdXMsIC5ub2RlLWFydGljbGUtY29udGVudCAjaXRlbXMgdGQudG90YWwtdmFsdWUgdGV4dGFyZWE6aG92ZXIsIC5ub2RlLWFydGljbGUtY29udGVudCAjaXRlbXMgdGQudG90YWwtdmFsdWUgdGV4dGFyZWE6Zm9jdXMsIC5ub2RlLWFydGljbGUtY29udGVudCAuZGVsZXRlOmhvdmVyIHtcXG4gIGJhY2tncm91bmQtY29sb3I6ICNFRUZGODg7XFxufVxcbi5ub2RlLWFydGljbGUtY29udGVudCAjb3JkZW5lcyB0ZXh0YXJlYSB7XFxuICB0ZXh0LWFsaWduOiBjZW50ZXI7XFxuICB2ZXJ0aWNhbC1hbGlnbjogbWlkZGxlO1xcbn1cXG4ubm9kZS1hcnRpY2xlLWNvbnRlbnQgdGFibGUgdGQsIC5ub2RlLWFydGljbGUtY29udGVudCB0YWJsZSB0aCB7XFxuICBwYWRkaW5nOiA1cHg7XFxufVxcbi5ub2RlLWFydGljbGUtY29udGVudCAjaGVhZGVyIHtcXG4gIGhlaWdodDogMzBweDtcXG4gIHdpZHRoOiAxMDAlO1xcbiAgbWFyZ2luOiAwIDA7XFxuICBiYWNrZ3JvdW5kOiAjZmZmO1xcbiAgdGV4dC1hbGlnbjogY2VudGVyO1xcbiAgY29sb3I6IGJsYWNrO1xcbiAgZm9udDogYm9sZCAxNXB4IEhlbHZldGljYSwgU2Fucy1TZXJpZjtcXG4gIC13ZWJraXQtdGV4dC1kZWNvcmF0aW9uOiB1cHBlcmNhc2U7XFxuICAgICAgICAgIHRleHQtZGVjb3JhdGlvbjogdXBwZXJjYXNlO1xcbiAgbGV0dGVyLXNwYWNpbmc6IDIwcHg7XFxuICBwYWRkaW5nOiA4cHggMHB4O1xcbn1cXG4ubm9kZS1hcnRpY2xlLWNvbnRlbnQgI2FkZHJlc3Mge1xcbiAgd2lkdGg6IDQwMHB4O1xcbiAgaGVpZ2h0OiAxNTBweDtcXG4gIGZsb2F0OiByaWdodDtcXG4gIGxpbmUtaGVpZ2h0OiAxMnB4O1xcbiAgdGV4dC1hbGlnbjogcmlnaHQ7XFxuICBmb250LXNpemU6IDhweDtcXG59XFxuLm5vZGUtYXJ0aWNsZS1jb250ZW50ICNhZGRyZXNzIHRleHRhcmVhIHtcXG4gIHdpZHRoOiA1MCU7XFxuICB0ZXh0LWFsaWduOiByaWdodDtcXG59XFxuLm5vZGUtYXJ0aWNsZS1jb250ZW50ICNjdXN0b21lciB7XFxuICBtYXJnaW46IDAgMCAyMHB4IDA7XFxuICBvdmVyZmxvdzogaGlkZGVuO1xcbn1cXG4ubm9kZS1hcnRpY2xlLWNvbnRlbnQgI21ldGEge1xcbiAgbWFyZ2luLXRvcDogMXB4O1xcbiAgd2lkdGg6IDEwMCU7XFxufVxcbi5ub2RlLWFydGljbGUtY29udGVudCAjaW1hZ2Uge1xcbiAgaGVpZ2h0OiAxNTBweDtcXG59XFxuLm5vZGUtYXJ0aWNsZS1jb250ZW50ICN0ZXJtcyB7XFxuICB0ZXh0LWFsaWduOiBjZW50ZXI7XFxuICBtYXJnaW4tdG9wOiAyMHB4O1xcbiAgd2lkdGg6IDI3NnB4O1xcbiAgcGFkZGluZy10b3A6IDEwMHB4O1xcbn1cXG4ubm9kZS1hcnRpY2xlLWNvbnRlbnQgI3Rlcm1zIGg1IHtcXG4gIHRleHQtdHJhbnNmb3JtOiB1cHBlcmNhc2U7XFxuICBmb250OiAxM3B4O1xcbiAgbGV0dGVyLXNwYWNpbmc6IDEwcHg7XFxuICBib3JkZXItYm90dG9tOiAxcHggc29saWQgYmxhY2s7XFxuICBwYWRkaW5nOiAwIDAgOHB4IDA7XFxuICBtYXJnaW46IDAgMCA4cHggMDtcXG59XFxuLm5vZGUtYXJ0aWNsZS1jb250ZW50ICN0ZXJtcyB0ZXh0YXJlYSB7XFxuICB3aWR0aDogMTAwJTtcXG4gIHRleHQtYWxpZ246IGNlbnRlcjtcXG59XFxuXCIsIFwiXCJdKTtcbi8vIEV4cG9ydHNcbm1vZHVsZS5leHBvcnRzID0gZXhwb3J0cztcbiJdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Iiwic291cmNlUm9vdCI6IiJ9\n//# sourceURL=webpack-internal:///./node_modules/css-loader/dist/cjs.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=style&index=0&rel=stylesheet%2Fscss&lang=scss&\n"); /***/ }), /***/ "./node_modules/style-loader/index.js!./node_modules/css-loader/dist/cjs.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=style&index=0&rel=stylesheet%2Fscss&lang=scss&": /*!******************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/style-loader!./node_modules/css-loader/dist/cjs.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--6-2!./node_modules/sass-loader/dist/cjs.js??ref--6-3!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=style&index=0&rel=stylesheet%2Fscss&lang=scss& ***! \******************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { eval("\nvar content = __webpack_require__(/*! !../../../../../node_modules/css-loader/dist/cjs.js!../../../../../node_modules/vue-loader/lib/loaders/stylePostLoader.js!../../../../../node_modules/postcss-loader/src??ref--6-2!../../../../../node_modules/sass-loader/dist/cjs.js??ref--6-3!../../../../../node_modules/vue-loader/lib??vue-loader-options!./contrato_empleado_download.vue?vue&type=style&index=0&rel=stylesheet%2Fscss&lang=scss& */ \"./node_modules/css-loader/dist/cjs.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=style&index=0&rel=stylesheet%2Fscss&lang=scss&\");\n\nif(typeof content === 'string') content = [[module.i, content, '']];\n\nvar transform;\nvar insertInto;\n\n\n\nvar options = {\"hmr\":true}\n\noptions.transform = transform\noptions.insertInto = undefined;\n\nvar update = __webpack_require__(/*! ../../../../../node_modules/style-loader/lib/addStyles.js */ \"./node_modules/style-loader/lib/addStyles.js\")(content, options);\n\nif(content.locals) module.exports = content.locals;\n\nif(false) {}//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9ub2RlX21vZHVsZXMvc3R5bGUtbG9hZGVyL2luZGV4LmpzIS4vbm9kZV9tb2R1bGVzL2Nzcy1sb2FkZXIvZGlzdC9janMuanMhLi9ub2RlX21vZHVsZXMvdnVlLWxvYWRlci9saWIvbG9hZGVycy9zdHlsZVBvc3RMb2FkZXIuanMhLi9ub2RlX21vZHVsZXMvcG9zdGNzcy1sb2FkZXIvc3JjL2luZGV4LmpzPyEuL25vZGVfbW9kdWxlcy9zYXNzLWxvYWRlci9kaXN0L2Nqcy5qcz8hLi9ub2RlX21vZHVsZXMvdnVlLWxvYWRlci9saWIvaW5kZXguanM/IS4vcmVzb3VyY2VzL2pzL3ZpZXdzL2VtcGxlYWRvcy9jb21wb25lbnRzL2NvbnRyYXRvX2VtcGxlYWRvX2Rvd25sb2FkLnZ1ZT92dWUmdHlwZT1zdHlsZSZpbmRleD0wJnJlbD1zdHlsZXNoZWV0JTJGc2NzcyZsYW5nPXNjc3MmLmpzIiwic291cmNlcyI6WyJ3ZWJwYWNrOi8vLy4vcmVzb3VyY2VzL2pzL3ZpZXdzL2VtcGxlYWRvcy9jb21wb25lbnRzL2NvbnRyYXRvX2VtcGxlYWRvX2Rvd25sb2FkLnZ1ZT9jNWZkIl0sInNvdXJjZXNDb250ZW50IjpbIlxudmFyIGNvbnRlbnQgPSByZXF1aXJlKFwiISEuLi8uLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvY3NzLWxvYWRlci9kaXN0L2Nqcy5qcyEuLi8uLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvdnVlLWxvYWRlci9saWIvbG9hZGVycy9zdHlsZVBvc3RMb2FkZXIuanMhLi4vLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL3Bvc3Rjc3MtbG9hZGVyL3NyYy9pbmRleC5qcz8/cmVmLS02LTIhLi4vLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL3Nhc3MtbG9hZGVyL2Rpc3QvY2pzLmpzPz9yZWYtLTYtMyEuLi8uLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvdnVlLWxvYWRlci9saWIvaW5kZXguanM/P3Z1ZS1sb2FkZXItb3B0aW9ucyEuL2NvbnRyYXRvX2VtcGxlYWRvX2Rvd25sb2FkLnZ1ZT92dWUmdHlwZT1zdHlsZSZpbmRleD0wJnJlbD1zdHlsZXNoZWV0JTJGc2NzcyZsYW5nPXNjc3MmXCIpO1xuXG5pZih0eXBlb2YgY29udGVudCA9PT0gJ3N0cmluZycpIGNvbnRlbnQgPSBbW21vZHVsZS5pZCwgY29udGVudCwgJyddXTtcblxudmFyIHRyYW5zZm9ybTtcbnZhciBpbnNlcnRJbnRvO1xuXG5cblxudmFyIG9wdGlvbnMgPSB7XCJobXJcIjp0cnVlfVxuXG5vcHRpb25zLnRyYW5zZm9ybSA9IHRyYW5zZm9ybVxub3B0aW9ucy5pbnNlcnRJbnRvID0gdW5kZWZpbmVkO1xuXG52YXIgdXBkYXRlID0gcmVxdWlyZShcIiEuLi8uLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvc3R5bGUtbG9hZGVyL2xpYi9hZGRTdHlsZXMuanNcIikoY29udGVudCwgb3B0aW9ucyk7XG5cbmlmKGNvbnRlbnQubG9jYWxzKSBtb2R1bGUuZXhwb3J0cyA9IGNvbnRlbnQubG9jYWxzO1xuXG5pZihtb2R1bGUuaG90KSB7XG5cdG1vZHVsZS5ob3QuYWNjZXB0KFwiISEuLi8uLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvY3NzLWxvYWRlci9kaXN0L2Nqcy5qcyEuLi8uLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvdnVlLWxvYWRlci9saWIvbG9hZGVycy9zdHlsZVBvc3RMb2FkZXIuanMhLi4vLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL3Bvc3Rjc3MtbG9hZGVyL3NyYy9pbmRleC5qcz8/cmVmLS02LTIhLi4vLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL3Nhc3MtbG9hZGVyL2Rpc3QvY2pzLmpzPz9yZWYtLTYtMyEuLi8uLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvdnVlLWxvYWRlci9saWIvaW5kZXguanM/P3Z1ZS1sb2FkZXItb3B0aW9ucyEuL2NvbnRyYXRvX2VtcGxlYWRvX2Rvd25sb2FkLnZ1ZT92dWUmdHlwZT1zdHlsZSZpbmRleD0wJnJlbD1zdHlsZXNoZWV0JTJGc2NzcyZsYW5nPXNjc3MmXCIsIGZ1bmN0aW9uKCkge1xuXHRcdHZhciBuZXdDb250ZW50ID0gcmVxdWlyZShcIiEhLi4vLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL2Nzcy1sb2FkZXIvZGlzdC9janMuanMhLi4vLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL3Z1ZS1sb2FkZXIvbGliL2xvYWRlcnMvc3R5bGVQb3N0TG9hZGVyLmpzIS4uLy4uLy4uLy4uLy4uL25vZGVfbW9kdWxlcy9wb3N0Y3NzLWxvYWRlci9zcmMvaW5kZXguanM/P3JlZi0tNi0yIS4uLy4uLy4uLy4uLy4uL25vZGVfbW9kdWxlcy9zYXNzLWxvYWRlci9kaXN0L2Nqcy5qcz8/cmVmLS02LTMhLi4vLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL3Z1ZS1sb2FkZXIvbGliL2luZGV4LmpzPz92dWUtbG9hZGVyLW9wdGlvbnMhLi9jb250cmF0b19lbXBsZWFkb19kb3dubG9hZC52dWU/dnVlJnR5cGU9c3R5bGUmaW5kZXg9MCZyZWw9c3R5bGVzaGVldCUyRnNjc3MmbGFuZz1zY3NzJlwiKTtcblxuXHRcdGlmKHR5cGVvZiBuZXdDb250ZW50ID09PSAnc3RyaW5nJykgbmV3Q29udGVudCA9IFtbbW9kdWxlLmlkLCBuZXdDb250ZW50LCAnJ11dO1xuXG5cdFx0dmFyIGxvY2FscyA9IChmdW5jdGlvbihhLCBiKSB7XG5cdFx0XHR2YXIga2V5LCBpZHggPSAwO1xuXG5cdFx0XHRmb3Ioa2V5IGluIGEpIHtcblx0XHRcdFx0aWYoIWIgfHwgYVtrZXldICE9PSBiW2tleV0pIHJldHVybiBmYWxzZTtcblx0XHRcdFx0aWR4Kys7XG5cdFx0XHR9XG5cblx0XHRcdGZvcihrZXkgaW4gYikgaWR4LS07XG5cblx0XHRcdHJldHVybiBpZHggPT09IDA7XG5cdFx0fShjb250ZW50LmxvY2FscywgbmV3Q29udGVudC5sb2NhbHMpKTtcblxuXHRcdGlmKCFsb2NhbHMpIHRocm93IG5ldyBFcnJvcignQWJvcnRpbmcgQ1NTIEhNUiBkdWUgdG8gY2hhbmdlZCBjc3MtbW9kdWxlcyBsb2NhbHMuJyk7XG5cblx0XHR1cGRhdGUobmV3Q29udGVudCk7XG5cdH0pO1xuXG5cdG1vZHVsZS5ob3QuZGlzcG9zZShmdW5jdGlvbigpIHsgdXBkYXRlKCk7IH0pO1xufSJdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSIsInNvdXJjZVJvb3QiOiIifQ==\n//# sourceURL=webpack-internal:///./node_modules/style-loader/index.js!./node_modules/css-loader/dist/cjs.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=style&index=0&rel=stylesheet%2Fscss&lang=scss&\n"); /***/ }), /***/ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=template&id=7477d3bc&": /*!*********************************************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=template&id=7477d3bc& ***! \*********************************************************************************************************************************************************************************************************************************************/ /*! exports provided: render, staticRenderFns */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"render\", function() { return render; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"staticRenderFns\", function() { return staticRenderFns; });\nvar render = function() {\n var _vm = this\n var _h = _vm.$createElement\n var _c = _vm._self._c || _h\n return _c(\n \"div\",\n {\n directives: [\n {\n name: \"loading\",\n rawName: \"v-loading.fullscreen.lock\",\n value: _vm.fullscreenLoading,\n expression: \"fullscreenLoading\",\n modifiers: { fullscreen: true, lock: true }\n }\n ],\n staticClass: \"main-article\",\n attrs: { \"element-loading-text\": \"Generando PDF\" }\n },\n [\n _c(\"div\", { ref: \"content\", staticClass: \"node-article-content\" }, [\n _c(\"div\", { attrs: { id: \"page-wrap\" } }, [\n _c(\"div\", { staticStyle: { clear: \"both\" } }),\n _vm._v(\" \"),\n _c(\"div\", { attrs: { id: \"customer\" } }, [\n _vm._v(\n \"\\n CONTRATO INDIVIDUAL DE TRABAJO POR TIEMPO DETERMINADO pactado por (2) dos meses, que celebran por una parte EL C. BRANDON MENDOZA TOVAR, designado en lo sucesivo como “LA EMPRESA”, por otra parte, y por su propio derecho, el C. ESPERICUETA NAVEJAR FERNANDO, a quien en lo sucesivo se le designará para términos del presente contrato como el “TRABAJADOR”, quedando así pactado por ambas partes y existiendo conformidad con las declaraciones y cláusulas siguientes:\\n \\n \"\n )\n ]),\n _vm._v(\" \"),\n _c(\"div\", { attrs: { id: \"ordenes\" } }, [_c(\"el-row\")], 1),\n _vm._v(\" \"),\n _c(\n \"div\",\n {\n staticStyle: { float: \"left\", \"margin-left\": \"32px\" },\n attrs: { id: \"terms\" }\n },\n [\n _c(\"h5\"),\n _c(\"textarea\", [\n _vm._v(\"Recibió (\" + _vm._s(_vm.embarque.nombre_chofer) + \")\")\n ])\n ]\n ),\n _vm._v(\" \"),\n _vm._m(0)\n ])\n ])\n ]\n )\n}\nvar staticRenderFns = [\n function() {\n var _vm = this\n var _h = _vm.$createElement\n var _c = _vm._self._c || _h\n return _c(\n \"div\",\n {\n staticStyle: { float: \"right\", \"margin-right\": \"32px\" },\n attrs: { id: \"terms\" }\n },\n [_c(\"h5\"), _c(\"textarea\", [_vm._v(\"Autorizó\")])]\n )\n }\n]\nrender._withStripped = true\n\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9ub2RlX21vZHVsZXMvdnVlLWxvYWRlci9saWIvbG9hZGVycy90ZW1wbGF0ZUxvYWRlci5qcz8hLi9ub2RlX21vZHVsZXMvdnVlLWxvYWRlci9saWIvaW5kZXguanM/IS4vcmVzb3VyY2VzL2pzL3ZpZXdzL2VtcGxlYWRvcy9jb21wb25lbnRzL2NvbnRyYXRvX2VtcGxlYWRvX2Rvd25sb2FkLnZ1ZT92dWUmdHlwZT10ZW1wbGF0ZSZpZD03NDc3ZDNiYyYuanMiLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvanMvdmlld3MvZW1wbGVhZG9zL2NvbXBvbmVudHMvY29udHJhdG9fZW1wbGVhZG9fZG93bmxvYWQudnVlP2RhMWQiXSwic291cmNlc0NvbnRlbnQiOlsidmFyIHJlbmRlciA9IGZ1bmN0aW9uKCkge1xuICB2YXIgX3ZtID0gdGhpc1xuICB2YXIgX2ggPSBfdm0uJGNyZWF0ZUVsZW1lbnRcbiAgdmFyIF9jID0gX3ZtLl9zZWxmLl9jIHx8IF9oXG4gIHJldHVybiBfYyhcbiAgICBcImRpdlwiLFxuICAgIHtcbiAgICAgIGRpcmVjdGl2ZXM6IFtcbiAgICAgICAge1xuICAgICAgICAgIG5hbWU6IFwibG9hZGluZ1wiLFxuICAgICAgICAgIHJhd05hbWU6IFwidi1sb2FkaW5nLmZ1bGxzY3JlZW4ubG9ja1wiLFxuICAgICAgICAgIHZhbHVlOiBfdm0uZnVsbHNjcmVlbkxvYWRpbmcsXG4gICAgICAgICAgZXhwcmVzc2lvbjogXCJmdWxsc2NyZWVuTG9hZGluZ1wiLFxuICAgICAgICAgIG1vZGlmaWVyczogeyBmdWxsc2NyZWVuOiB0cnVlLCBsb2NrOiB0cnVlIH1cbiAgICAgICAgfVxuICAgICAgXSxcbiAgICAgIHN0YXRpY0NsYXNzOiBcIm1haW4tYXJ0aWNsZVwiLFxuICAgICAgYXR0cnM6IHsgXCJlbGVtZW50LWxvYWRpbmctdGV4dFwiOiBcIkdlbmVyYW5kbyBQREZcIiB9XG4gICAgfSxcbiAgICBbXG4gICAgICBfYyhcImRpdlwiLCB7IHJlZjogXCJjb250ZW50XCIsIHN0YXRpY0NsYXNzOiBcIm5vZGUtYXJ0aWNsZS1jb250ZW50XCIgfSwgW1xuICAgICAgICBfYyhcImRpdlwiLCB7IGF0dHJzOiB7IGlkOiBcInBhZ2Utd3JhcFwiIH0gfSwgW1xuICAgICAgICAgIF9jKFwiZGl2XCIsIHsgc3RhdGljU3R5bGU6IHsgY2xlYXI6IFwiYm90aFwiIH0gfSksXG4gICAgICAgICAgX3ZtLl92KFwiIFwiKSxcbiAgICAgICAgICBfYyhcImRpdlwiLCB7IGF0dHJzOiB7IGlkOiBcImN1c3RvbWVyXCIgfSB9LCBbXG4gICAgICAgICAgICBfdm0uX3YoXG4gICAgICAgICAgICAgIFwiXFxuICAgICAgICBDT05UUkFUTyBJTkRJVklEVUFMIERFIFRSQUJBSk8gUE9SIFRJRU1QTyBERVRFUk1JTkFETyBwYWN0YWRvIHBvciAoMikgZG9zIG1lc2VzLCBxdWUgY2VsZWJyYW4gcG9yIHVuYSBwYXJ0ZSBFTCBDLiBCUkFORE9OIE1FTkRPWkEgVE9WQVIsIGRlc2lnbmFkbyBlbiBsbyBzdWNlc2l2byBjb21vIOKAnExBIEVNUFJFU0HigJ0sIHBvciBvdHJhIHBhcnRlLCB5IHBvciBzdSBwcm9waW8gZGVyZWNobywgZWwgQy4gRVNQRVJJQ1VFVEEgTkFWRUpBUiBGRVJOQU5ETywgYSBxdWllbiBlbiBsbyBzdWNlc2l2byBzZSBsZSBkZXNpZ25hcsOhIHBhcmEgdMOpcm1pbm9zIGRlbCBwcmVzZW50ZSBjb250cmF0byBjb21vIGVsIOKAnFRSQUJBSkFET1LigJ0sIHF1ZWRhbmRvIGFzw60gcGFjdGFkbyBwb3IgYW1iYXMgcGFydGVzIHkgZXhpc3RpZW5kbyBjb25mb3JtaWRhZCBjb24gbGFzIGRlY2xhcmFjaW9uZXMgeSBjbMOhdXN1bGFzIHNpZ3VpZW50ZXM6XFxuICAgICAgICAgXFxuICAgICAgXCJcbiAgICAgICAgICAgIClcbiAgICAgICAgICBdKSxcbiAgICAgICAgICBfdm0uX3YoXCIgXCIpLFxuICAgICAgICAgIF9jKFwiZGl2XCIsIHsgYXR0cnM6IHsgaWQ6IFwib3JkZW5lc1wiIH0gfSwgW19jKFwiZWwtcm93XCIpXSwgMSksXG4gICAgICAgICAgX3ZtLl92KFwiIFwiKSxcbiAgICAgICAgICBfYyhcbiAgICAgICAgICAgIFwiZGl2XCIsXG4gICAgICAgICAgICB7XG4gICAgICAgICAgICAgIHN0YXRpY1N0eWxlOiB7IGZsb2F0OiBcImxlZnRcIiwgXCJtYXJnaW4tbGVmdFwiOiBcIjMycHhcIiB9LFxuICAgICAgICAgICAgICBhdHRyczogeyBpZDogXCJ0ZXJtc1wiIH1cbiAgICAgICAgICAgIH0sXG4gICAgICAgICAgICBbXG4gICAgICAgICAgICAgIF9jKFwiaDVcIiksXG4gICAgICAgICAgICAgIF9jKFwidGV4dGFyZWFcIiwgW1xuICAgICAgICAgICAgICAgIF92bS5fdihcIlJlY2liacOzIChcIiArIF92bS5fcyhfdm0uZW1iYXJxdWUubm9tYnJlX2Nob2ZlcikgKyBcIilcIilcbiAgICAgICAgICAgICAgXSlcbiAgICAgICAgICAgIF1cbiAgICAgICAgICApLFxuICAgICAgICAgIF92bS5fdihcIiBcIiksXG4gICAgICAgICAgX3ZtLl9tKDApXG4gICAgICAgIF0pXG4gICAgICBdKVxuICAgIF1cbiAgKVxufVxudmFyIHN0YXRpY1JlbmRlckZucyA9IFtcbiAgZnVuY3Rpb24oKSB7XG4gICAgdmFyIF92bSA9IHRoaXNcbiAgICB2YXIgX2ggPSBfdm0uJGNyZWF0ZUVsZW1lbnRcbiAgICB2YXIgX2MgPSBfdm0uX3NlbGYuX2MgfHwgX2hcbiAgICByZXR1cm4gX2MoXG4gICAgICBcImRpdlwiLFxuICAgICAge1xuICAgICAgICBzdGF0aWNTdHlsZTogeyBmbG9hdDogXCJyaWdodFwiLCBcIm1hcmdpbi1yaWdodFwiOiBcIjMycHhcIiB9LFxuICAgICAgICBhdHRyczogeyBpZDogXCJ0ZXJtc1wiIH1cbiAgICAgIH0sXG4gICAgICBbX2MoXCJoNVwiKSwgX2MoXCJ0ZXh0YXJlYVwiLCBbX3ZtLl92KFwiQXV0b3JpesOzXCIpXSldXG4gICAgKVxuICB9XG5dXG5yZW5kZXIuX3dpdGhTdHJpcHBlZCA9IHRydWVcblxuZXhwb3J0IHsgcmVuZGVyLCBzdGF0aWNSZW5kZXJGbnMgfSJdLCJtYXBwaW5ncyI6IkFBQUE7QUFBQTtBQUFBO0FBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOyIsInNvdXJjZVJvb3QiOiIifQ==\n//# sourceURL=webpack-internal:///./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=template&id=7477d3bc&\n"); /***/ }), /***/ "./resources/js/api/resource.js": /*!**************************************!*\ !*** ./resources/js/api/resource.js ***! \**************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return Resource; });\n/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ \"./node_modules/@babel/runtime/helpers/classCallCheck.js\");\n/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ \"./node_modules/@babel/runtime/helpers/createClass.js\");\n/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);\n/* harmony import */ var _utils_request__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @/utils/request */ \"./resources/js/utils/request.js\");\n\n\n\n/**\n * Simple RESTful resource class\n */\n\nvar Resource = /*#__PURE__*/function () {\n function Resource(uri) {\n _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, Resource);\n\n this.uri = uri;\n }\n\n _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(Resource, [{\n key: \"list\",\n value: function list(query) {\n return Object(_utils_request__WEBPACK_IMPORTED_MODULE_2__[\"default\"])({\n url: '/' + this.uri,\n method: 'get',\n params: query\n });\n }\n }, {\n key: \"get\",\n value: function get(id) {\n return Object(_utils_request__WEBPACK_IMPORTED_MODULE_2__[\"default\"])({\n url: '/' + this.uri + '/' + id,\n method: 'get'\n });\n }\n }, {\n key: \"store\",\n value: function store(resource) {\n return Object(_utils_request__WEBPACK_IMPORTED_MODULE_2__[\"default\"])({\n url: '/' + this.uri,\n method: 'post',\n data: resource\n });\n }\n }, {\n key: \"update\",\n value: function update(id, resource) {\n return Object(_utils_request__WEBPACK_IMPORTED_MODULE_2__[\"default\"])({\n url: '/' + this.uri + '/' + id,\n method: 'put',\n data: resource\n });\n }\n }, {\n key: \"destroy\",\n value: function destroy(id) {\n return Object(_utils_request__WEBPACK_IMPORTED_MODULE_2__[\"default\"])({\n url: '/' + this.uri + '/' + id,\n method: 'delete'\n });\n }\n }]);\n\n return Resource;\n}();\n\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9yZXNvdXJjZXMvanMvYXBpL3Jlc291cmNlLmpzLmpzIiwic291cmNlcyI6WyJ3ZWJwYWNrOi8vLy4vcmVzb3VyY2VzL2pzL2FwaS9yZXNvdXJjZS5qcz85MWZjIl0sInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBfY2xhc3NDYWxsQ2hlY2sgZnJvbSBcIkBiYWJlbC9ydW50aW1lL2hlbHBlcnMvY2xhc3NDYWxsQ2hlY2tcIjtcbmltcG9ydCBfY3JlYXRlQ2xhc3MgZnJvbSBcIkBiYWJlbC9ydW50aW1lL2hlbHBlcnMvY3JlYXRlQ2xhc3NcIjtcbmltcG9ydCByZXF1ZXN0IGZyb20gJ0AvdXRpbHMvcmVxdWVzdCc7XG4vKipcbiAqIFNpbXBsZSBSRVNUZnVsIHJlc291cmNlIGNsYXNzXG4gKi9cblxudmFyIFJlc291cmNlID0gLyojX19QVVJFX18qL2Z1bmN0aW9uICgpIHtcbiAgZnVuY3Rpb24gUmVzb3VyY2UodXJpKSB7XG4gICAgX2NsYXNzQ2FsbENoZWNrKHRoaXMsIFJlc291cmNlKTtcblxuICAgIHRoaXMudXJpID0gdXJpO1xuICB9XG5cbiAgX2NyZWF0ZUNsYXNzKFJlc291cmNlLCBbe1xuICAgIGtleTogXCJsaXN0XCIsXG4gICAgdmFsdWU6IGZ1bmN0aW9uIGxpc3QocXVlcnkpIHtcbiAgICAgIHJldHVybiByZXF1ZXN0KHtcbiAgICAgICAgdXJsOiAnLycgKyB0aGlzLnVyaSxcbiAgICAgICAgbWV0aG9kOiAnZ2V0JyxcbiAgICAgICAgcGFyYW1zOiBxdWVyeVxuICAgICAgfSk7XG4gICAgfVxuICB9LCB7XG4gICAga2V5OiBcImdldFwiLFxuICAgIHZhbHVlOiBmdW5jdGlvbiBnZXQoaWQpIHtcbiAgICAgIHJldHVybiByZXF1ZXN0KHtcbiAgICAgICAgdXJsOiAnLycgKyB0aGlzLnVyaSArICcvJyArIGlkLFxuICAgICAgICBtZXRob2Q6ICdnZXQnXG4gICAgICB9KTtcbiAgICB9XG4gIH0sIHtcbiAgICBrZXk6IFwic3RvcmVcIixcbiAgICB2YWx1ZTogZnVuY3Rpb24gc3RvcmUocmVzb3VyY2UpIHtcbiAgICAgIHJldHVybiByZXF1ZXN0KHtcbiAgICAgICAgdXJsOiAnLycgKyB0aGlzLnVyaSxcbiAgICAgICAgbWV0aG9kOiAncG9zdCcsXG4gICAgICAgIGRhdGE6IHJlc291cmNlXG4gICAgICB9KTtcbiAgICB9XG4gIH0sIHtcbiAgICBrZXk6IFwidXBkYXRlXCIsXG4gICAgdmFsdWU6IGZ1bmN0aW9uIHVwZGF0ZShpZCwgcmVzb3VyY2UpIHtcbiAgICAgIHJldHVybiByZXF1ZXN0KHtcbiAgICAgICAgdXJsOiAnLycgKyB0aGlzLnVyaSArICcvJyArIGlkLFxuICAgICAgICBtZXRob2Q6ICdwdXQnLFxuICAgICAgICBkYXRhOiByZXNvdXJjZVxuICAgICAgfSk7XG4gICAgfVxuICB9LCB7XG4gICAga2V5OiBcImRlc3Ryb3lcIixcbiAgICB2YWx1ZTogZnVuY3Rpb24gZGVzdHJveShpZCkge1xuICAgICAgcmV0dXJuIHJlcXVlc3Qoe1xuICAgICAgICB1cmw6ICcvJyArIHRoaXMudXJpICsgJy8nICsgaWQsXG4gICAgICAgIG1ldGhvZDogJ2RlbGV0ZSdcbiAgICAgIH0pO1xuICAgIH1cbiAgfV0pO1xuXG4gIHJldHVybiBSZXNvdXJjZTtcbn0oKTtcblxuZXhwb3J0IHsgUmVzb3VyY2UgYXMgZGVmYXVsdCB9OyJdLCJtYXBwaW5ncyI6IkFBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOyIsInNvdXJjZVJvb3QiOiIifQ==\n//# sourceURL=webpack-internal:///./resources/js/api/resource.js\n"); /***/ }), /***/ "./resources/js/assets/empresa/logo-dsi.jpeg": /*!***************************************************!*\ !*** ./resources/js/assets/empresa/logo-dsi.jpeg ***! \***************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony default export */ __webpack_exports__[\"default\"] = (\"/images/logo-dsi.jpeg?a01e32d530b7989185e2a33d0d713222\");//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9yZXNvdXJjZXMvanMvYXNzZXRzL2VtcHJlc2EvbG9nby1kc2kuanBlZy5qcyIsInNvdXJjZXMiOlsid2VicGFjazovLy8uL3Jlc291cmNlcy9qcy9hc3NldHMvZW1wcmVzYS9sb2dvLWRzaS5qcGVnPzVjMmMiXSwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0IGRlZmF1bHQgXCIvaW1hZ2VzL2xvZ28tZHNpLmpwZWc/YTAxZTMyZDUzMGI3OTg5MTg1ZTJhMzNkMGQ3MTMyMjJcIjsiXSwibWFwcGluZ3MiOiJBQUFBO0FBQUEiLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///./resources/js/assets/empresa/logo-dsi.jpeg\n"); /***/ }), /***/ "./resources/js/views/empleados/components/contrato_empleado_download.vue": /*!********************************************************************************!*\ !*** ./resources/js/views/empleados/components/contrato_empleado_download.vue ***! \********************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _contrato_empleado_download_vue_vue_type_template_id_7477d3bc___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./contrato_empleado_download.vue?vue&type=template&id=7477d3bc& */ \"./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=template&id=7477d3bc&\");\n/* harmony import */ var _contrato_empleado_download_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./contrato_empleado_download.vue?vue&type=script&lang=js& */ \"./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=script&lang=js&\");\n/* empty/unused harmony star reexport *//* harmony import */ var _contrato_empleado_download_vue_vue_type_style_index_0_rel_stylesheet_2Fscss_lang_scss___WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./contrato_empleado_download.vue?vue&type=style&index=0&rel=stylesheet%2Fscss&lang=scss& */ \"./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=style&index=0&rel=stylesheet%2Fscss&lang=scss&\");\n/* harmony import */ var _node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js */ \"./node_modules/vue-loader/lib/runtime/componentNormalizer.js\");\n\n\n\n\n\n\n/* normalize component */\n\nvar component = Object(_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(\n _contrato_empleado_download_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__[\"default\"],\n _contrato_empleado_download_vue_vue_type_template_id_7477d3bc___WEBPACK_IMPORTED_MODULE_0__[\"render\"],\n _contrato_empleado_download_vue_vue_type_template_id_7477d3bc___WEBPACK_IMPORTED_MODULE_0__[\"staticRenderFns\"],\n false,\n null,\n null,\n null\n \n)\n\n/* hot reload */\nif (false) { var api; }\ncomponent.options.__file = \"resources/js/views/empleados/components/contrato_empleado_download.vue\"\n/* harmony default export */ __webpack_exports__[\"default\"] = (component.exports);//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9yZXNvdXJjZXMvanMvdmlld3MvZW1wbGVhZG9zL2NvbXBvbmVudHMvY29udHJhdG9fZW1wbGVhZG9fZG93bmxvYWQudnVlLmpzIiwic291cmNlcyI6WyJ3ZWJwYWNrOi8vLy4vcmVzb3VyY2VzL2pzL3ZpZXdzL2VtcGxlYWRvcy9jb21wb25lbnRzL2NvbnRyYXRvX2VtcGxlYWRvX2Rvd25sb2FkLnZ1ZT9lNjhiIl0sInNvdXJjZXNDb250ZW50IjpbImltcG9ydCB7IHJlbmRlciwgc3RhdGljUmVuZGVyRm5zIH0gZnJvbSBcIi4vY29udHJhdG9fZW1wbGVhZG9fZG93bmxvYWQudnVlP3Z1ZSZ0eXBlPXRlbXBsYXRlJmlkPTc0NzdkM2JjJlwiXG5pbXBvcnQgc2NyaXB0IGZyb20gXCIuL2NvbnRyYXRvX2VtcGxlYWRvX2Rvd25sb2FkLnZ1ZT92dWUmdHlwZT1zY3JpcHQmbGFuZz1qcyZcIlxuZXhwb3J0ICogZnJvbSBcIi4vY29udHJhdG9fZW1wbGVhZG9fZG93bmxvYWQudnVlP3Z1ZSZ0eXBlPXNjcmlwdCZsYW5nPWpzJlwiXG5pbXBvcnQgc3R5bGUwIGZyb20gXCIuL2NvbnRyYXRvX2VtcGxlYWRvX2Rvd25sb2FkLnZ1ZT92dWUmdHlwZT1zdHlsZSZpbmRleD0wJnJlbD1zdHlsZXNoZWV0JTJGc2NzcyZsYW5nPXNjc3MmXCJcblxuXG4vKiBub3JtYWxpemUgY29tcG9uZW50ICovXG5pbXBvcnQgbm9ybWFsaXplciBmcm9tIFwiIS4uLy4uLy4uLy4uLy4uL25vZGVfbW9kdWxlcy92dWUtbG9hZGVyL2xpYi9ydW50aW1lL2NvbXBvbmVudE5vcm1hbGl6ZXIuanNcIlxudmFyIGNvbXBvbmVudCA9IG5vcm1hbGl6ZXIoXG4gIHNjcmlwdCxcbiAgcmVuZGVyLFxuICBzdGF0aWNSZW5kZXJGbnMsXG4gIGZhbHNlLFxuICBudWxsLFxuICBudWxsLFxuICBudWxsXG4gIFxuKVxuXG4vKiBob3QgcmVsb2FkICovXG5pZiAobW9kdWxlLmhvdCkge1xuICB2YXIgYXBpID0gcmVxdWlyZShcIkM6XFxcXHhhbXBwXFxcXGh0ZG9jc1xcXFxsYXJhdnVlXFxcXG5vZGVfbW9kdWxlc1xcXFx2dWUtaG90LXJlbG9hZC1hcGlcXFxcZGlzdFxcXFxpbmRleC5qc1wiKVxuICBhcGkuaW5zdGFsbChyZXF1aXJlKCd2dWUnKSlcbiAgaWYgKGFwaS5jb21wYXRpYmxlKSB7XG4gICAgbW9kdWxlLmhvdC5hY2NlcHQoKVxuICAgIGlmICghYXBpLmlzUmVjb3JkZWQoJzc0NzdkM2JjJykpIHtcbiAgICAgIGFwaS5jcmVhdGVSZWNvcmQoJzc0NzdkM2JjJywgY29tcG9uZW50Lm9wdGlvbnMpXG4gICAgfSBlbHNlIHtcbiAgICAgIGFwaS5yZWxvYWQoJzc0NzdkM2JjJywgY29tcG9uZW50Lm9wdGlvbnMpXG4gICAgfVxuICAgIG1vZHVsZS5ob3QuYWNjZXB0KFwiLi9jb250cmF0b19lbXBsZWFkb19kb3dubG9hZC52dWU/dnVlJnR5cGU9dGVtcGxhdGUmaWQ9NzQ3N2QzYmMmXCIsIGZ1bmN0aW9uICgpIHtcbiAgICAgIGFwaS5yZXJlbmRlcignNzQ3N2QzYmMnLCB7XG4gICAgICAgIHJlbmRlcjogcmVuZGVyLFxuICAgICAgICBzdGF0aWNSZW5kZXJGbnM6IHN0YXRpY1JlbmRlckZuc1xuICAgICAgfSlcbiAgICB9KVxuICB9XG59XG5jb21wb25lbnQub3B0aW9ucy5fX2ZpbGUgPSBcInJlc291cmNlcy9qcy92aWV3cy9lbXBsZWFkb3MvY29tcG9uZW50cy9jb250cmF0b19lbXBsZWFkb19kb3dubG9hZC52dWVcIlxuZXhwb3J0IGRlZmF1bHQgY29tcG9uZW50LmV4cG9ydHMiXSwibWFwcGluZ3MiOiJBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsdUJBaUJBO0FBQ0E7QUFDQSIsInNvdXJjZVJvb3QiOiIifQ==\n//# sourceURL=webpack-internal:///./resources/js/views/empleados/components/contrato_empleado_download.vue\n"); /***/ }), /***/ "./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=script&lang=js&": /*!*********************************************************************************************************!*\ !*** ./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=script&lang=js& ***! \*********************************************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_contrato_empleado_download_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../../node_modules/babel-loader/lib??ref--4-0!../../../../../node_modules/vue-loader/lib??vue-loader-options!./contrato_empleado_download.vue?vue&type=script&lang=js& */ \"./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=script&lang=js&\");\n/* empty/unused harmony star reexport */ /* harmony default export */ __webpack_exports__[\"default\"] = (_node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_contrato_empleado_download_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__[\"default\"]); //# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9yZXNvdXJjZXMvanMvdmlld3MvZW1wbGVhZG9zL2NvbXBvbmVudHMvY29udHJhdG9fZW1wbGVhZG9fZG93bmxvYWQudnVlP3Z1ZSZ0eXBlPXNjcmlwdCZsYW5nPWpzJi5qcyIsInNvdXJjZXMiOlsid2VicGFjazovLy8uL3Jlc291cmNlcy9qcy92aWV3cy9lbXBsZWFkb3MvY29tcG9uZW50cy9jb250cmF0b19lbXBsZWFkb19kb3dubG9hZC52dWU/NDc3NSJdLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgbW9kIGZyb20gXCItIS4uLy4uLy4uLy4uLy4uL25vZGVfbW9kdWxlcy9iYWJlbC1sb2FkZXIvbGliL2luZGV4LmpzPz9yZWYtLTQtMCEuLi8uLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvdnVlLWxvYWRlci9saWIvaW5kZXguanM/P3Z1ZS1sb2FkZXItb3B0aW9ucyEuL2NvbnRyYXRvX2VtcGxlYWRvX2Rvd25sb2FkLnZ1ZT92dWUmdHlwZT1zY3JpcHQmbGFuZz1qcyZcIjsgZXhwb3J0IGRlZmF1bHQgbW9kOyBleHBvcnQgKiBmcm9tIFwiLSEuLi8uLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvYmFiZWwtbG9hZGVyL2xpYi9pbmRleC5qcz8/cmVmLS00LTAhLi4vLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL3Z1ZS1sb2FkZXIvbGliL2luZGV4LmpzPz92dWUtbG9hZGVyLW9wdGlvbnMhLi9jb250cmF0b19lbXBsZWFkb19kb3dubG9hZC52dWU/dnVlJnR5cGU9c2NyaXB0Jmxhbmc9anMmXCIiXSwibWFwcGluZ3MiOiJBQUFBO0FBQUE7QUFBQSIsInNvdXJjZVJvb3QiOiIifQ==\n//# sourceURL=webpack-internal:///./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=script&lang=js&\n"); /***/ }), /***/ "./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=style&index=0&rel=stylesheet%2Fscss&lang=scss&": /*!****************************************************************************************************************************************!*\ !*** ./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=style&index=0&rel=stylesheet%2Fscss&lang=scss& ***! \****************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _node_modules_style_loader_index_js_node_modules_css_loader_dist_cjs_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_6_2_node_modules_sass_loader_dist_cjs_js_ref_6_3_node_modules_vue_loader_lib_index_js_vue_loader_options_contrato_empleado_download_vue_vue_type_style_index_0_rel_stylesheet_2Fscss_lang_scss___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../../node_modules/style-loader!../../../../../node_modules/css-loader/dist/cjs.js!../../../../../node_modules/vue-loader/lib/loaders/stylePostLoader.js!../../../../../node_modules/postcss-loader/src??ref--6-2!../../../../../node_modules/sass-loader/dist/cjs.js??ref--6-3!../../../../../node_modules/vue-loader/lib??vue-loader-options!./contrato_empleado_download.vue?vue&type=style&index=0&rel=stylesheet%2Fscss&lang=scss& */ \"./node_modules/style-loader/index.js!./node_modules/css-loader/dist/cjs.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=style&index=0&rel=stylesheet%2Fscss&lang=scss&\");\n/* harmony import */ var _node_modules_style_loader_index_js_node_modules_css_loader_dist_cjs_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_6_2_node_modules_sass_loader_dist_cjs_js_ref_6_3_node_modules_vue_loader_lib_index_js_vue_loader_options_contrato_empleado_download_vue_vue_type_style_index_0_rel_stylesheet_2Fscss_lang_scss___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_index_js_node_modules_css_loader_dist_cjs_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_6_2_node_modules_sass_loader_dist_cjs_js_ref_6_3_node_modules_vue_loader_lib_index_js_vue_loader_options_contrato_empleado_download_vue_vue_type_style_index_0_rel_stylesheet_2Fscss_lang_scss___WEBPACK_IMPORTED_MODULE_0__);\n/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _node_modules_style_loader_index_js_node_modules_css_loader_dist_cjs_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_6_2_node_modules_sass_loader_dist_cjs_js_ref_6_3_node_modules_vue_loader_lib_index_js_vue_loader_options_contrato_empleado_download_vue_vue_type_style_index_0_rel_stylesheet_2Fscss_lang_scss___WEBPACK_IMPORTED_MODULE_0__) if([\"default\"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _node_modules_style_loader_index_js_node_modules_css_loader_dist_cjs_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_6_2_node_modules_sass_loader_dist_cjs_js_ref_6_3_node_modules_vue_loader_lib_index_js_vue_loader_options_contrato_empleado_download_vue_vue_type_style_index_0_rel_stylesheet_2Fscss_lang_scss___WEBPACK_IMPORTED_MODULE_0__[key]; }) }(__WEBPACK_IMPORT_KEY__));\n /* harmony default export */ __webpack_exports__[\"default\"] = (_node_modules_style_loader_index_js_node_modules_css_loader_dist_cjs_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_6_2_node_modules_sass_loader_dist_cjs_js_ref_6_3_node_modules_vue_loader_lib_index_js_vue_loader_options_contrato_empleado_download_vue_vue_type_style_index_0_rel_stylesheet_2Fscss_lang_scss___WEBPACK_IMPORTED_MODULE_0___default.a); //# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9yZXNvdXJjZXMvanMvdmlld3MvZW1wbGVhZG9zL2NvbXBvbmVudHMvY29udHJhdG9fZW1wbGVhZG9fZG93bmxvYWQudnVlP3Z1ZSZ0eXBlPXN0eWxlJmluZGV4PTAmcmVsPXN0eWxlc2hlZXQlMkZzY3NzJmxhbmc9c2NzcyYuanMiLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvanMvdmlld3MvZW1wbGVhZG9zL2NvbXBvbmVudHMvY29udHJhdG9fZW1wbGVhZG9fZG93bmxvYWQudnVlPzMxZTIiXSwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IG1vZCBmcm9tIFwiLSEuLi8uLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvc3R5bGUtbG9hZGVyL2luZGV4LmpzIS4uLy4uLy4uLy4uLy4uL25vZGVfbW9kdWxlcy9jc3MtbG9hZGVyL2Rpc3QvY2pzLmpzIS4uLy4uLy4uLy4uLy4uL25vZGVfbW9kdWxlcy92dWUtbG9hZGVyL2xpYi9sb2FkZXJzL3N0eWxlUG9zdExvYWRlci5qcyEuLi8uLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvcG9zdGNzcy1sb2FkZXIvc3JjL2luZGV4LmpzPz9yZWYtLTYtMiEuLi8uLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvc2Fzcy1sb2FkZXIvZGlzdC9janMuanM/P3JlZi0tNi0zIS4uLy4uLy4uLy4uLy4uL25vZGVfbW9kdWxlcy92dWUtbG9hZGVyL2xpYi9pbmRleC5qcz8/dnVlLWxvYWRlci1vcHRpb25zIS4vY29udHJhdG9fZW1wbGVhZG9fZG93bmxvYWQudnVlP3Z1ZSZ0eXBlPXN0eWxlJmluZGV4PTAmcmVsPXN0eWxlc2hlZXQlMkZzY3NzJmxhbmc9c2NzcyZcIjsgZXhwb3J0IGRlZmF1bHQgbW9kOyBleHBvcnQgKiBmcm9tIFwiLSEuLi8uLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvc3R5bGUtbG9hZGVyL2luZGV4LmpzIS4uLy4uLy4uLy4uLy4uL25vZGVfbW9kdWxlcy9jc3MtbG9hZGVyL2Rpc3QvY2pzLmpzIS4uLy4uLy4uLy4uLy4uL25vZGVfbW9kdWxlcy92dWUtbG9hZGVyL2xpYi9sb2FkZXJzL3N0eWxlUG9zdExvYWRlci5qcyEuLi8uLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvcG9zdGNzcy1sb2FkZXIvc3JjL2luZGV4LmpzPz9yZWYtLTYtMiEuLi8uLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvc2Fzcy1sb2FkZXIvZGlzdC9janMuanM/P3JlZi0tNi0zIS4uLy4uLy4uLy4uLy4uL25vZGVfbW9kdWxlcy92dWUtbG9hZGVyL2xpYi9pbmRleC5qcz8/dnVlLWxvYWRlci1vcHRpb25zIS4vY29udHJhdG9fZW1wbGVhZG9fZG93bmxvYWQudnVlP3Z1ZSZ0eXBlPXN0eWxlJmluZGV4PTAmcmVsPXN0eWxlc2hlZXQlMkZzY3NzJmxhbmc9c2NzcyZcIiJdLCJtYXBwaW5ncyI6IkFBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSIsInNvdXJjZVJvb3QiOiIifQ==\n//# sourceURL=webpack-internal:///./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=style&index=0&rel=stylesheet%2Fscss&lang=scss&\n"); /***/ }), /***/ "./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=template&id=7477d3bc&": /*!***************************************************************************************************************!*\ !*** ./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=template&id=7477d3bc& ***! \***************************************************************************************************************/ /*! exports provided: render, staticRenderFns */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_contrato_empleado_download_vue_vue_type_template_id_7477d3bc___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../../node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../../../../../node_modules/vue-loader/lib??vue-loader-options!./contrato_empleado_download.vue?vue&type=template&id=7477d3bc& */ \"./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=template&id=7477d3bc&\");\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"render\", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_contrato_empleado_download_vue_vue_type_template_id_7477d3bc___WEBPACK_IMPORTED_MODULE_0__[\"render\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"staticRenderFns\", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_contrato_empleado_download_vue_vue_type_template_id_7477d3bc___WEBPACK_IMPORTED_MODULE_0__[\"staticRenderFns\"]; });\n\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9yZXNvdXJjZXMvanMvdmlld3MvZW1wbGVhZG9zL2NvbXBvbmVudHMvY29udHJhdG9fZW1wbGVhZG9fZG93bmxvYWQudnVlP3Z1ZSZ0eXBlPXRlbXBsYXRlJmlkPTc0NzdkM2JjJi5qcyIsInNvdXJjZXMiOlsid2VicGFjazovLy8uL3Jlc291cmNlcy9qcy92aWV3cy9lbXBsZWFkb3MvY29tcG9uZW50cy9jb250cmF0b19lbXBsZWFkb19kb3dubG9hZC52dWU/NGE3MyJdLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgKiBmcm9tIFwiLSEuLi8uLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvdnVlLWxvYWRlci9saWIvbG9hZGVycy90ZW1wbGF0ZUxvYWRlci5qcz8/dnVlLWxvYWRlci1vcHRpb25zIS4uLy4uLy4uLy4uLy4uL25vZGVfbW9kdWxlcy92dWUtbG9hZGVyL2xpYi9pbmRleC5qcz8/dnVlLWxvYWRlci1vcHRpb25zIS4vY29udHJhdG9fZW1wbGVhZG9fZG93bmxvYWQudnVlP3Z1ZSZ0eXBlPXRlbXBsYXRlJmlkPTc0NzdkM2JjJlwiIl0sIm1hcHBpbmdzIjoiQUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7Iiwic291cmNlUm9vdCI6IiJ9\n//# sourceURL=webpack-internal:///./resources/js/views/empleados/components/contrato_empleado_download.vue?vue&type=template&id=7477d3bc&\n"); /***/ }) }]);
// custom typefaces import "typeface-montserrat" import "typeface-merriweather" // normalize CSS across browsers import "./src/css/normalize.css" // custom CSS styles import "./src/css/main.scss"
module.exports = { context: [{name: 'bar', value: 43}, 'lodash'], prompt: '[TEST] $', banner: () => 'TEST', };
from Default.settings import * from mappings import *
import * as auth from './auth/actions' import { actions as form } from 'redux-form' import { routerActions as router } from 'connected-react-router' export { auth, form, router }
const path = require('path'); module.exports = { entry: { app: ['babel-polyfill', './src/app.js'], }, output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist'), }, mode: 'development', watch: true, watchOptions: { aggregateTimeout: 100, }, module: { rules: [ { test: /\.css$/, use: ['style-loader', 'css-loader'], }, { test: /\.m?js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'], }, }, }, ], }, };
const Discord = require('discord.js'); const client = new Discord.Client(); const ayarlar = require('./ayarlar.json'); const chalk = require('chalk'); const moment = require('moment'); var Jimp = require('jimp'); const { Client, Util } = require('discord.js'); const weather = require('weather-js') const fs = require('fs'); const cha = require('cha'); const db = require('quick.db'); require('./util/eventLoader.js')(client); const path = require('path'); const request = require('request'); const { promisify } = require('util') const express = require('express'); const app = express(); //7-24 aktif tutma // //7-24aktif tutma son // let kufurEngel = JSON.parse(fs.readFileSync("./jsonlar/kufurEngelle.json", "utf8")); var prefix = ayarlar.prefix; var prefix = ayarlar.prefix; const log = message => { console.log(`${message}`); }; client.commands = new Discord.Collection(); client.aliases = new Discord.Collection(); fs.readdir('./komutlar/', (err, files) => { if (err) console.error(err); log(`${files.length} komut yüklenecek.`); files.forEach(f => { let props = require(`./komutlar/${f}`); log(`Yüklenen komut: ${props.help.name}.`); client.commands.set(props.help.name, props); props.conf.aliases.forEach(alias => { client.aliases.set(alias, props.help.name); }); }); }); client.reload = command => { return new Promise((resolve, reject) => { try { delete require.cache[require.resolve(`./komutlar/${command}`)]; let cmd = require(`./komutlar/${command}`); client.commands.delete(command); client.aliases.forEach((cmd, alias) => { if (cmd === command) client.aliases.delete(alias); }); client.commands.set(command, cmd); cmd.conf.aliases.forEach(alias => { client.aliases.set(alias, cmd.help.name); }); resolve(); } catch (e) { reject(e); } }); }; client.load = command => { return new Promise((resolve, reject) => { try { let cmd = require(`./komutlar/${command}`); client.commands.set(command, cmd); cmd.conf.aliases.forEach(alias => { client.aliases.set(alias, cmd.help.name); }); resolve(); } catch (e) { reject(e); } }); }; client.unload = command => { return new Promise((resolve, reject) => { try { delete require.cache[require.resolve(`./komutlar/${command}`)]; let cmd = require(`./komutlar/${command}`); client.commands.delete(command); client.aliases.forEach((cmd, alias) => { if (cmd === command) client.aliases.delete(alias); }); resolve(); } catch (e) { reject(e); } }); }; client.elevation = message => { if (!message.guild) { return; } let permlvl = 0; if (message.member.hasPermission("BAN_MEMBERS")) permlvl = 2; if (message.member.hasPermission("ADMINISTRATOR")) permlvl = 3; if (message.author.id === ayarlar.sahip) permlvl = 4; return permlvl; }; var regToken = /[\w\d]{24}\.[\w\d]{6}\.[\w\d-_]{27}/g; // client.on('debug', e => { // console.log(chalk.bgBlue.green(e.replace(regToken, 'that was redacted'))); // }); client.on('warn', e => { console.log(chalk.bgYellow(e.replace(regToken, 'that was redacted'))); }); client.on('error', e => { console.log(chalk.bgRed(e.replace(regToken, 'that was redacted'))); }); client.login(ayarlar.token); //---------------------------------KOMUTLAR---------------------------------\\ client.on('voiceStateUpdate', (oldMember, newMember) => { // todo create channel if (newMember.voiceChannel != null && newMember.voiceChannel.name.startsWith('➕│2 Kişilik Oda')) { newMember.guild.createChannel(`║👤 ${newMember.displayName}`, { type: 'voice', parent: newMember.voiceChannel.parent }).then(cloneChannel => { newMember.setVoiceChannel(cloneChannel) cloneChannel.setUserLimit(2) }) } // ! leave if (oldMember.voiceChannel != undefined) { if (oldMember.voiceChannel.name.startsWith('║👤 ')) { if (oldMember.voiceChannel.members.size == 0) { oldMember.voiceChannel.delete() } else { // change name let matchMember = oldMember.voiceChannel.members.cache.find(x => `║👤 ${x.displayName}` == oldMember.voiceChannel.name); if (matchMember == null) { oldMember.voiceChannel.setName(`║👤 ${oldMember.voiceChannel.members.random().displayName}`) } } } } }); //----------------------------------GEÇİCİ KANAL----------------------------// //----------------------------------GEÇİCİ KANAL----------------------------// client.on('voiceStateUpdate', (oldMember, newMember) => { // todo create channel if (newMember.voiceChannel != null && newMember.voiceChannel.name.startsWith('➕│3 Kişilik Oda')) { newMember.guild.createChannel(`║👤 ${newMember.displayName}`, { type: 'voice', parent: newMember.voiceChannel.parent }).then(cloneChannel => { newMember.setVoiceChannel(cloneChannel) cloneChannel.setUserLimit(3) }) } // ! leave if (oldMember.voiceChannel != undefined) { if (oldMember.voiceChannel.name.startsWith('║👤 ')) { if (oldMember.voiceChannel.members.size == 0) { oldMember.voiceChannel.delete() } else { // change name let matchMember = oldMember.voiceChannel.members.cache.find(x => `║👤 ${x.displayName}` == oldMember.voiceChannel.name); if (matchMember == null) { oldMember.voiceChannel.setName(`║👤 ${oldMember.voiceChannel.members.random().displayName}`) } } } } }); //----------------------------------GEÇİCİ KANAL----------------------------// //----------------------------------GEÇİCİ KANAL----------------------------// client.on('voiceStateUpdate', (oldMember, newMember) => { // todo create channel if (newMember.voiceChannel != null && newMember.voiceChannel.name.startsWith('➕│4 Kişilik Oda')) { newMember.guild.guild.channels.create(`║👤 ${newMember.displayName}`, { type: 'voice', parent: newMember.voiceChannel.parent }).then(cloneChannel => { newMember.setVoiceChannel(cloneChannel) cloneChannel.setUserLimit(4) }) } // ! leave if (oldMember.voiceChannel != undefined) { if (oldMember.voiceChannel.name.startsWith('║👤 ')) { if (oldMember.voiceChannel.members.size == 0) { oldMember.voiceChannel.delete() } else { // change name let matchMember = oldMember.voiceChannel.members.cache.find(x => `║👤 ${x.displayName}` == oldMember.voiceChannel.name); if (matchMember == null) { oldMember.voiceChannel.setName(`║👤 ${oldMember.voiceChannel.members.random().displayName}`) } } } } }); //----------------------------------GEÇİCİ KANAL----------------------------// //----------------------------------GEÇİCİ KANAL----------------------------// client.on('voiceStateUpdate', (oldMember, newMember) => { // todo create channel if (newMember.voiceChannel != null && newMember.voiceChannel.name.startsWith('➕│5 Kişilik Oda')) { newMember.guild.guild.channels.create(`║👤 ${newMember.displayName}`, { type: 'voice', parent: newMember.voiceChannel.parent }).then(cloneChannel => { newMember.setVoiceChannel(cloneChannel) cloneChannel.setUserLimit(5) }) } // ! leave if (oldMember.voiceChannel != undefined) { if (oldMember.voiceChannel.name.startsWith('║👤 ')) { if (oldMember.voiceChannel.members.size == 0) { oldMember.voiceChannel.delete() } else { // change name let matchMember = oldMember.voiceChannel.members.cache.find(x => `║👤 ${x.displayName}` == oldMember.voiceChannel.name); if (matchMember == null) { oldMember.voiceChannel.setName(`║👤 ${oldMember.voiceChannel.members.random().displayName}`) } } } } }); //----------------------------------GEÇİCİ KANAL----------------------------// //----------------------------------Özel oda sistemi----------------------------// client.on('message', async message => { const ms = require('ms'); const prefix = await require('quick.db').fetch(`prefix_${message.guild.id}`) || ayarlar.prefix const args = message.content.slice(prefix.length).trim().split(/ +/g); const command = args.shift().toLowerCase(); let u = message.mentions.users.first() || message.author; if (command === "özel-oda-sistemi") { if (message.guild.channels.cache.find(channel => channel.name === "Bot Kullanımı")) return message.channel.send(" Bot Paneli Zaten Ayarlanmış.") if (!message.member.hasPermission('ADMINISTRATOR')) return message.channel.send(" Bu Kodu `Yönetici` Yetkisi Olan Kişi Kullanabilir."); message.channel.send(`Özel Oda Sisteminin Kurulmasını İstiyorsanız **evet** Yazınız.`) message.channel.awaitMessages(response => response.content === 'evet', { max: 1, time: 10000, errors: ['time'], }) .then((collected) => { message.guild.channels.create('【🔐】2 Kişilik Odalar【🔐】', {type: "category"}, [{ id: message.guild.id, }]); message.guild.channels.create(`➕│2 Kişilik Oda`, {type: "voice"}) .then(channel => channel.setParent(message.guild.channels.cache.find(channel => channel.name === "【🔐】2 Kişilik Odalar【🔐】"))) message.guild.channels.create('【🔐】3 Kişilik Odalar【🔐】', {type: "category"}, [{ id: message.guild.id, }]); message.guild.channels.create(`➕│3 Kişilik Oda`, {type: "voice"}) .then(channel => channel.setParent(message.guild.channels.cache.find(channel => channel.name === "【🔐】3 Kişilik Odalar【🔐】"))) message.guild.channels.create('【🔐】4 Kişilik Odalar【🔐】', {type: "category"}, [{ id: message.guild.id, }]); message.guild.channels.create(`➕│4 Kişilik Oda`, {type: "voice"}) .then(channel => channel.setParent(message.guild.channels.cache.find(channel => channel.name === "【🔐】4 Kişilik Odalar【🔐】"))) message.guild.channels.create('【🔐】5 Kişilik Odalar【🔐】', {type: "category"}, [{ id: message.guild.id, }]); message.guild.channels.create(`➕│5 Kişilik Oda`, {type: "voice"}) .then(channel => channel.setParent(message.guild.channels.cache.find(channel => channel.name === "【🔐】5 Kişilik Odalar【🔐】"))) message.channel.send("Gelişmiş Özel Oda Sistemi Aktif!") }) } }); //---------------------------------Geçici Oda sistemi son---------------------------------\\ //---------------------------------OtoRol ---------------------------------\\ client.on('guildMemberAdd', async (member, guild, message) => { let role = db.fetch(`otorolisim_${member.guild.id}`) let otorol = db.fetch(`autoRole_${member.guild.id}`) let i = db.fetch(`otorolKanal_${member.guild.id}`) if (!otorol || otorol.toLowerCase() === 'yok') return; else { try { if (!i) return if (!role) { member.roles.add(member.guild.roles.cache.get(otorol)) var embed = new Discord.MessageEmbed() .setDescription("**Sunucuya Yeni Katılan** @" + member.user.tag + " **Kullanıcısına** <@&" + otorol + "> **Rolü verildi<a:evet:730102927426977943>**") .setColor('0x36393E') .setFooter(`Lydia Otorol Sistemi`) member.guild.channels.cache.get(i).send(embed) } else if (role) { member.roles.add(member.guild.roles.cache.get(otorol)) var embed = new Discord.MessageEmbed() .setDescription(`**Sunucuya Yeni Katılan** \`${member.user.tag}\` **Kullanıcısına** \`${role}\` **Rolü verildi<a:evet:730102927426977943>**`) .setColor('0x36393E') .setFooter(`Lydia otorol Sistemi`) member.guild.channels.cache.get(i).send(embed) } } catch (e) { console.log(e) } } }); //---------------------------------OtoRol Son ---------------------------------\\ //////////////////// var data = {}; async function copyChannel (channel) { data[channel.guild.ownerID].channels.push(channel); } async function copyRole (role) { data[role.guild.ownerID].roles.push(role); } async function paste (guild, copyData) { copyData.channels.forEach(async function (channel) { guild.channels.create(channel.name, channel.type, channel.permissionOverwrites, "- Sweetie paste").then(channel2 => { channel2.setPosition(channel.position); }); }); copyData.roles.forEach(async function (role) { guild.roles.create({ name: role.name, color: role.hexColor }).then(async function (role2) { role2.setPosition(role.position); }); }); } async function copyAll (guild) { if (!data[guild.ownerID]) { data[guild.ownerID] = { roles: [], channels: [], }; } guild.channels.sort(function (a,b) { return a.position - b.position; }).forEach(async function (channel) { copyChannel(channel); }); guild.roles.sort(function (a,b) { return a.position - b.position; }).forEach(async function (role) { copyRole(role); }); } client.on("message", async function (msg) { if (!prefix || typeof prefix !== "string") { var prefix = ayarlar.prefix; } if (!msg.author.bot) { if (msg.content.startsWith(prefix)) { var args = msg.content.slice(prefix.length).split(" "); var command = args[0]; switch (command) { case "sunucu-kopyala": if (!msg.guild.ownerID == msg.author.id) return msg.reply("Sunucunun Sahibi Olmalısınız."); copyAll(msg.guild); msg.reply("Başarıyla Kopyalandı."); break; case "yedek-yapıştır": if (!msg.guild.ownerID == msg.author.id) return msg.reply("Sunucunun Sahibi Olmalısınız."); if (!data[msg.guild.ownerID]) return msg.reply("Hiç Bir Şey Kopyalanmamış"); paste(msg.guild, data[msg.guild.ownerID]); break; } } } }) //////////////// ////////// /////// // client.on('guildDelete', guild => { let rrrsembed = new Discord.MessageEmbed() .setColor("RED") .setTitle(" Bot Kickledi ") .addField("Sunucu Adı:", guild.name) .addField("Sunucu sahibi", guild.owner) .addField("Sunucu Sahibi'nin ID'si", guild.ownerID) .addField("Sunucunun Kurulu Olduğu Bölge:", guild.region) .addField("Sunucudaki Kişi Sayısı:", guild.memberCount) client.channels.cache.get('730010143403540483').send(rrrsembed); }); client.on('guildCreate', guild => { let rrrsembed = new Discord.MessageEmbed() .setColor("GREEN") .setTitle(" Bot Eklendi ") .addField("Sunucu Adı:", guild.name) .addField("Sunucu sahibi", guild.owner) .addField("Sunucu Sahibi'nin ID'si", guild.ownerID) .addField("Sunucunun Kurulu Olduğu Bölge:", guild.region) .addField("Sunucudaki Kişi Sayısı:", guild.memberCount) client.channels.cache.get('730010143403540483').send(rrrsembed); }); //////////////////////////////////////////////reklamkivk client.on("message", async message => { let uyarisayisi = await db.fetch(`reklamuyari_${message.author.id}`); let reklamkick = await db.fetch(`reklamkick_${message.guild.id}`) let kullanici = message.member; if (reklamkick == 'kapali') return; if (reklamkick == 'acik') { const reklam = ["discord.app", "discord.gg", "discordgg", ".com", ".net", ".xyz", ".tk", ".pw", ".io", ".me", ".gg", "www.", "https", "http", ".gl", ".org", ".com.tr", ".biz", ".party", ".rf.gd", ".az",]; if (reklam.some(word => message.content.toLowerCase().includes(word))) { if (!message.member.hasPermission("MANAGE_MESSAGES")) { message.delete(); db.add(`reklamuyari_${message.author.id}`, 1) //uyarı puanı ekleme if (uyarisayisi === null) { let uyari = new Discord.MessageEmbed() .setColor("RANDOM") .setFooter('Reklam kick sistemi', client.user.avatarURL) .setDescription(`<@${message.author.id}> reklam kick sistemine yakalandın! Reklam yapmaya devam edersen kickleniceksin (1/3)`) .setTimestamp() message.channel.send(uyari) } if (uyarisayisi === 1) { let uyari = new Discord.MessageEmbed() .setColor("RANDOM") .setFooter('Reklam kick sistemi', client.user.avatarURL) .setDescription(`<@${message.author.id}> reklam kick sistemine yakalandın! Reklam yapmaya devam edersen kickleniceksin (2/3)`) .setTimestamp() message.channel.send(uyari) } if (uyarisayisi === 2) { message.delete(); await kullanici.kick({ reason: `Lydia Reklam kick sistemi`, }) let uyari = new Discord.MessageEmbed() .setColor("RANDOM") .setFooter('Reklam kick sistemi', client.user.avatarURL) .setDescription(`<@${message.author.id}> 3 adet reklam uyarısı aldığı için kicklendi. Bir kez daha yaparsa banlanacakç`) .setTimestamp() message.channel.send(uyari) } if (uyarisayisi === 3) { message.delete(); await kullanici.ban({ reason: `Lydia Reklam ban sistemi`, }) db.delete(`reklamuyari_${message.author.id}`) let uyari = new Discord.MessageEmbed() .setColor("RANDOM") .setFooter('Reklam kick sistemi', client.user.avatarURL) .setDescription(`<@${message.author.id}> kick yedikten sonra tekrar devam ettiği için banlandı.`) .setTimestamp() message.channel.send(uyari) } } } } }); ////////////////////////////////////////////////////////////////////////// ///sunucupanel client.on('guildMemberAdd', async member => { let tag = await db.fetch(`technotag_${member.guild.id}`); let tagsekil; if (tag == null) tagsekil = member.setNickname(`${member.user.username}`) else tagsekil = member.setNickname(`${tag} ${member.user.username}`) }); ///////////////////////////////////////// client.login(ayarlar.token); client.on("message", async message => { const a = message.content.toLowerCase(); if ( a === "slam" || a === "sa" || a === "selamun aleyküm" || a === "selamın aleyküm" || a === "selam" || a === "slm" ) { let i = await db.fetch(`saas_${message.guild.id}`); if (i === "acik") { const embed = new Discord.MessageEmbed() .setColor("RANDOM") .setTitle("Lydia") .setDescription( "**Aleyküm Selam, Hoşgeldin!**" ) .setFooter(client.user.username, client.user.avatarURL); message.channel.send(embed).then(msg => msg.delete(5000)); } } }); ////////////////////////////////// client.on("guildMemberAdd", async member => { let botrol = await db.fetch(`bototorol_${member.guild.id}`); let botrol2 = member.guild.roles.cache.find('id', botrol); if (!botrol2) return; if (botrol) { if (member.user.bot) { member.roles.add(botrol2) } } }); //////////////////////////////////////////////////////////sayaç client.on("guildMemberAdd", async member => { let sayac = await db.fetch(`sayac_${member.guild.id}`); let skanal9 = await db.fetch(`sayacK_${member.guild.id}`); if (!skanal9) return; const skanal31 = member.guild.channels.cache.find("name", skanal9); if (!skanal31) return; skanal31.send( `<a:evet:730102927426977943>| \`${ member.user.tag }\`, sunucuya katıldı \`${sayac}\` kişi olmamıza \`${sayac - member.guild.members.cache.size}\` kişi kaldı, \`${ member.guild.memberCount }\` kişiyiz!` ); }); client.on("guildMemberRemove", async member => { let sayac = await db.fetch(`sayac_${member.guild.id}`); let skanal9 = await db.fetch(`sayacK_${member.guild.id}`); if (!skanal9) return; const skanal31 = member.guild.channels.cache.find("name", skanal9); if (!skanal31) return; skanal31.send( `<a:hayr:730102927674572880> \`${ member.user.tag }\`, aramızdan ayrıldı, \`${sayac}\` kişi olmamıza \`${sayac - member.guild.members.cache.size}\` kişi kaldı, \`${ member.guild.memberCount }\` kişiyiz!` ); }); client.on("messageUpdate", async (oldMsg, newMsg) => { let prefix = "!"; if (newMsg.author.bot) return; if (!newMsg.content.startsWith(prefix)) return; let command = newMsg.content.split(" ")[0].slice(prefix.length); let params = newMsg.content.split(" ").slice(1); let perms = client.elevation(newMsg); let cmd; if (client.commands.has(command)) cmd = client.commands.get(command); else if (client.aliases.has(command)) cmd = client.commands.get(client.aliases.get(command)); if (cmd) { if (perms < cmd.conf.permLevel) return; cmd.run(client, newMsg, params, perms); } }); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////Destek client.on("message", message => { var prefix = ayarlar.prefix if (message.content.toLowerCase().startsWith(`${ayarlar.prefix}destek-kapat`)) { if (!message.channel.name.startsWith(`🎫destek-`)) return message.channel.send(`Bu komut sadece destek kanallarında kullanılabilir!`); var deneme = new Discord.MessageEmbed() .setColor("RANDOM") .setDescription(`Talebi kapatmak için **10** saniye içinde **evet** yazmalısın.`) message.channel.send(deneme) .then((m) => { message.channel.awaitMessages(response => response.content === 'evet', { max: 1, time: 10000, errors: ['time'], }) .then((collected) => { message.channel.delete(); }) .catch(() => { m.edit('Destek kanalı kapatma isteğin zaman aşımına uğradı.').then(m2 => { m2.delete(); }, 3000); }); }); } }); ////////////////////////////////////////////////////////////////////////////////////////////////Seviye client.on("message", async msg => { if(msg.content.startsWith(prefix)) return; const db = require('quick.db'); var id = msg.author.id; var gid = msg.guild.id; var xp = await db.fetch(`xp_${id}_${gid}`); var lvl = await db.fetch(`lvl_${id}_${gid}`); let seviyexp = await db.fetch(`seviyexp${msg.guild.id}`) const skanal = await db.fetch(`seviyekanal${msg.guild.id}`) let kanal = msg.guild.channels.cache.get(skanal) if (msg.author.bot === true) return; let seviyeEmbed = new Discord.MessageEmbed() seviyeEmbed.setDescription(`Tebrik ederim <@${msg.author.id}>! Seviye atladın ve **${lvl+1}** seviye oldun!`) seviyeEmbed.setFooter(`${client.user.username} | Seviye Sistemi`) seviyeEmbed.setColor("RANDOM") if(!lvl) { db.set(`xp_${id}_${gid}`, 5); db.set(`lvl_${id}_${gid}`, 1); db.set(`xpToLvl_${id}_${gid}`, 100); db.set(`top_${id}`, 1) } let veri1 = []; if(seviyexp) veri1 = seviyexp if(!seviyexp) veri1 = 5 if (msg.content.length > 7) { db.add(`xp_${id}_${gid}`, veri1) }; let seviyesınır = await db.fetch(`seviyesınır${msg.guild.id}`) let veri2 = []; if(seviyesınır) veri2 = seviyesınır if(!seviyesınır) veri2 = 250 if (await db.fetch(`xp_${id}_${gid}`) > veri2) { if(skanal) { kanal.send(new Discord.MessageEmbed() .setDescription(`Tebrik ederim <@${msg.author.id}>! Seviye atladın ve **${lvl+1}** seviye oldun:tada:`) .setFooter(`${client.user.username} | Seviye Sistemi`) .setColor("RANDOM")) } db.add(`lvl_${id}_${gid}`, 1) db.delete(`xp_${id}_${gid}`)}; db.set(`top_${id}`, Math.floor(lvl+1)) }); //SEVİYE-ROL----------------------------------- client.on('message', async message => { var id = message.author.id; var gid = message.guild.id; let rrol = await db.fetch(`rrol.${message.guild.id}`) var level = await db.fetch(`lvl_${id}_${gid}`); if(rrol) { rrol.forEach(async rols => { var rrol2 = await db.fetch(`rrol2.${message.guild.id}.${rols}`) if(Math.floor(rrol2) <= Math.floor(level)) { let author = message.guild.member(message.author) author.roles.add(rols) } else if(Math.floor(rrol2) >= Math.floor(level)) { let author = message.guild.member(message.author) author.roles.remove(rols) } }) } if(message.content == '!rütbeler') { if(!rrol) { message.channel.send(new Discord.MessageEmbed() .setColor("RANDOM") .setFooter(`${client.user.username} Seviye-Rol Sistemi!`, client.user.avatarURL) .setDescription(`Herhangi bir rol oluşturulmadı.`)) return; } const { MessageEmbed } = require('discord.js') let d = rrol.map(x => '<@&'+message.guild.roles.cache.get(x).id+'>' + ' **' + db.get(`rrol3.${message.guild.id}.${x}`)+' Seviye**' ).join("\n") message.channel.send(new MessageEmbed() .setColor("RANDOM") .setFooter(`${client.user.username} Seviye-Rol Sistemi!`, client.user.avatarURL) .setDescription(`${d}`)) } }) /*client.on('message', async message => { var id = message.author.id; var gid = message.guild.id; let srol = await db.fetch(`srol.${message.guild.id}`) var level = await db.fetch(`lvl_${id}_${gid}`); if(srol) { srol.forEach(async rols => { var srol2 = await db.fetch(`srol2.${message.guild.id}.${rols}`) if(Math.floor(srol2) <= Math.floor(level)) { let author = message.guild.member(message.author) author.roles.add(rols) } else if(Math.floor(srol2) >= Math.floor(level)) { let author = message.guild.member(message.author) author.roles.remove(rols) } }) } if(message.content == '!seviyerolleri' || message.content == "!levelroles") { if(!srol) { message.channel.send(new Discord.MessageEmbed() .setColor("RANDOM") .setFooter(`${client.user.username} Seviye-Rol Sistemi!`, client.user.avatarURL) .setDescription(`Herhangi bir rol oluşturulmadı.`)) return; } const { MessageEmbed } = require('discord.js') let d = srol.map(x => '<@&'+message.guild.roles.cache.get(x).id+'>' + ' **' + db.get(`srol3.${message.guild.id}.${x}`)+' Seviye**' ).join("\n") message.channel.send(new MessageEmbed() .setColor("RANDOM") //.setColor(message.guild.member(message.author).highestRole.hexColor) .setFooter(`${client.user.username} Seviye-Rol Sistemi!`, client.user.avatarURL) .setDescription(`${d}`)) } })*/ ///////////////////////////////////////////////////////////////////////////////////////////////////////////////gelen-giden client.on('guildMemberAdd', async member => { let fc = await db.fetch(`FrenzyResimsizHGBB_${member.guild.id}`) let frenzychannel = client.channels.cache.get(fc) if(!frenzychannel) return frenzychannel.send(`${member} Sunucuya Hoşgeldin İyi Vakit Geçirmen Dileğiyle`) }) client.on('guildMemberRemove', async member => { let fc = await db.fetch(`FrenzyResimsizHGBB_${member.guild.id}`) let frenzychannel = client.channels.cache.get(fc) if(!frenzychannel) return frenzychannel.send(`${member.user.username} Sunucudan Ayrıldı :(`) }) /////////////////////////////////////////////////////////////////////////////////////////////////////////////eklendim atıldım //---------------------------------------Mod Log----------------------------// client.on('channelCreate', async channel => { const c = channel.guild.channels.cache.get(db.fetch(`codeminglog_${channel.guild.id}`)); if (!c) return; var embed = new Discord.MessageEmbed() .addField(`Kanal oluşturuldu`, ` İsmi: \`${channel.name}\`\n Türü: **${channel.type}**\n ID: ${channel.id}`) .setTimestamp() .setColor("RANDOM") .setFooter(`${channel.client.user.username}#${channel.client.user.discriminator}`, channel.client.user.avatarURL) c.send(embed) }); client.on('channelDelete', async channel => { const c = channel.guild.channels.cache.get(db.fetch(`codeminglog_${channel.guild.id}`)); if (!c) return; let embed = new Discord.MessageEmbed() .addField(`Kanal silindi`, ` İsmi: \`${channel.name}\`\n Türü: **${channel.type}**\n ID: ${channel.id}`) .setTimestamp() .setColor("RANDOM") .setFooter(`${channel.client.user.username}#${channel.client.user.discriminator}`, channel.client.user.avatarURL) c.send(embed) }); client.on('channelNameUpdate', async channel => { const c = channel.guild.channels.cache.get(db.fetch(`codeminglog_${channel.guild.id}`)); if (!c) return; var embed = new Discord.MessageEmbed() .addField(`Kanal İsmi değiştirildi`, ` Yeni İsmi: \`${channel.name}\`\n ID: ${channel.id}`) .setTimestamp() .setColor("RANDOM") .setFooter(`${channel.client.user.username}#${channel.client.user.discriminator}`, channel.client.user.avatarURL) c.send(embed) }); client.on('emojiCreate', emoji => { const c = emoji.guild.channels.cache.get(db.fetch(`codeminglog_${emoji.guild.id}`)); if (!c) return; let embed = new Discord.MessageEmbed() .addField(`Emoji oluşturuldu`, ` İsmi: \`${emoji.name}\`\n GIF?: **${emoji.animated}**\n ID: ${emoji.id}`) .setTimestamp() .setColor("RANDOM") .setFooter(`${emoji.client.user.username}#${emoji.client.user.discriminator}`, emoji.client.user.avatarURL) c.send(embed) }); client.on('emojiDelete', emoji => { const c = emoji.guild.channels.cache.get(db.fetch(`codeminglog_${emoji.guild.id}`)); if (!c) return; let embed = new Discord.MessageEmbed() .addField(`Emoji silindi`, ` İsmi: \`${emoji.name}\`\n GIF? : **${emoji.animated}**\n ID: ${emoji.id}`) .setTimestamp() .setColor("RANDOM") .setFooter(`${emoji.client.user.username}#${emoji.client.user.discriminator}`, emoji.client.user.avatarURL) c.send(embed) }); client.on('emojiUpdate', (oldEmoji, newEmoji) => { const c = newEmoji.guild.channels.cache.get(db.fetch(`codeminglog_${newEmoji.guild.id}`)); if (!c) return; let embed = new Discord.MessageEmbed() .addField(`Emoji güncellendi`, ` Eski ismi: \`${oldEmoji.name}\`\n Yeni ismi: \`${newEmoji.name}\`\n► ID: ${oldEmoji.id}`) .setTimestamp() .setColor("RANDOM") .setFooter(`${newEmoji.client.user.username}#${newEmoji.client.user.discriminator}`, newEmoji.client.user.avatarURL) c.send(embed) }); client.on('guildBanAdd', async (guild, user) => { const channel = guild.channels.cache.get(db.fetch(`codeminglog_${guild.id}`)); if (!channel) return; const entry = await guild.fetchAuditLogs({type: 'MEMBER_BAN_ADD'}).then(audit => audit.entries.first()) let embed = new Discord.MessageEmbed() .setAuthor(`${user.username}#${user.discriminator}`, user.avatarURL) .addField(`Kullanıcı banlandı`, ` İsmi: \`${user.username}\`\n ID: **${user.id}**\n Sebep: **${entry.reason || 'Belirtmedi'}**\n Banlayan: **${entry.executor.username}#${entry.executor.discriminator}**`) .setTimestamp() .setColor("RANDOM") .setFooter(`${entry.executor.username}#${entry.executor.discriminator} tarafından`, entry.executor.avatarURL) channel.send(embed) }); client.on('guildBanRemove', async (guild, user) => { const channel = guild.channels.cache.get(db.fetch(`codeminglog_${guild.id}`)); if (!channel) return; const entry = await guild.fetchAuditLogs({type: 'MEMBER_BAN_ADD'}).then(audit => audit.entries.first()) let embed = new Discord.MessageEmbed() .setAuthor(`${user.username}#${user.discriminator}`, user.avatarURL) .addField(`Kullanıcının banı açıldı`, ` İsmi: \`${user.username}\`\n ID: **${user.id}**\n Banı Kaldıran: **${entry.executor.username}#${entry.executor.discriminator}**`) .setTimestamp() .setColor("RANDOM") .setFooter(`${entry.executor.username}#${entry.executor.discriminator} tarafından`, entry.executor.avatarURL) channel.send(embed) }); client.on('messageDelete', async message => { if(message.author.bot) return const channel = message.guild.channels.cache.get(db.fetch(`codeminglog_${message.guild.id}`)); if (!channel) return; let embed = new Discord.MessageEmbed() .setAuthor(`${message.author.username}#${message.author.discriminator}`, message.author.avatarURL) .setTitle("Mesaj silindi") .addField(`Silinen mesaj : ${message.content}`,`Kanal: ${message.channel.name}`) // .addField(`Kanal:`,`${message.channel.name}`) .setTimestamp() .setColor("RANDOM") .setFooter(`${message.client.user.username}#${message.client.user.discriminator}`, message.client.user.avatarURL) channel.send(embed) }); client.on('messageUpdate', async(oldMessage, newMessage) => { if(oldMessage.author.bot) return; if(oldMessage.content == newMessage.content) return; const channel = oldMessage.guild.channels.cache.get(db.fetch(`codeminglog_${oldMessage.guild.id}`)); if(!channel) return; let embed = new Discord.MessageEmbed() .setTitle("Mesaj güncellendi!") .addField("Eski mesaj : ",`${oldMessage.content}`) .addField("Yeni mesaj : ",`${newMessage.content}`) .addField("Kanal : ",`${oldMessage.channel.name}`) .setTimestamp() .setColor("RANDOM") .setFooter(`${oldMessage.client.user.username}#${oldMessage.client.user.discriminator}`,`${oldMessage.client.user.avatarURL}`) channel.send(embed) }); client.on('roles.create', async (role) => { const channel = role.guild.channels.cache.get(db.fetch(`codeminglog_${role.guild.id}`)); if (!channel) return; let embed = new Discord.MessageEmbed() .addField(`Rol oluşturuldu`, ` ismi: \`${role.name}\`\n ID: ${role.id}`) .setTimestamp() .setColor("RANDOM") .addField("Rol renk kodu : ",`${role.hexColor}`) .setFooter(`${role.client.user.username}#${role.client.user.discriminator}`, role.client.user.avatarURL) channel.send(embed) }); client.on('roleDelete', async (role) => { const channel = role.guild.channels.cache.get(db.fetch(`codeminglog_${role.guild.id}`)); if (!channel) return; let embed = new Discord.MessageEmbed() .addField(`Rol silindi`, ` ismi: \`${role.name}\`\n ID: ${role.id}`) .setTimestamp() .setColor("RANDOM") .addField("Rol renk kodu : ",`${role.hexColor}`) .setFooter(`${role.client.user.username}#${role.client.user.discriminator}`, role.client.user.avatarURL) channel.send(embed) }) client.on('voiceStateUpdate', (oldMember, newMember) => { // if (!logA[oldMember.guild.id]) return; if (db.has(`codeminglog_${oldMember.guild.id}`) === false) return; var kanal = oldMember.guild.channels.cache.get(db.fetch(`codeminglog_${oldMember.guild.id}`).replace("<#", "").replace(">", "")) if (!kanal) return; let newUserChannel = newMember.voiceChannel let oldUserChannel = oldMember.voiceChannel if(oldUserChannel === undefined && newUserChannel !== undefined) { const embed = new Discord.MessageEmbed() .setColor("RANDOM") .setDescription(`${newMember.user.tag} adlı kullanıcı \`${newUserChannel.name}\` isimli sesli kanala giriş yaptı!`) kanal.send(embed); } else if(newUserChannel === undefined){ const embed = new Discord.MessageEmbed() .setColor("RANDOM") .setDescription(`${newMember.user.tag} adlı kullanıcı sesli kanaldan çıkış yaptı!`) kanal.send(embed); } }); client.on("channelDelete", async channel => { let kontrol = await db.fetch(`dil_${channel.guild.id}`); let kanal = await db.fetch(`kanalk_${channel.guild.id}`); if (!kanal) return; if (kontrol == "TR_tr") { const entry = await channel.guild .fetchAuditLogs({ type: "CHANNEL_DELETE" }) .then(audit => audit.entries.first()); if (entry.executor.id == client.user.id) return; if (entry.executor.id == channel.guild.owner.id) return; channel.guild.channels.create(channel.name, channel.type, [ { id: channel.guild.id, position: channel.calculatedPosition } ]); const embed = new Discord.MessageEmbed() .setTitle(`Bir Kanal Silindi!`) .addField(`Silen`, entry.executor.tag) .addField(`Silinen Kanal`, channel.name) .addField(`Sonuç`, `Kanal Geri Açıldı!`) .setColor("BLACK"); client.channels.cache.get(kanal).send(embed); } else { const entry = await channel.guild .fetchAuditLogs({ type: "CHANNEL_DELETE" }) .then(audit => audit.entries.first()); if (entry.executor.id == client.user.id) return; if (entry.executor.id == channel.guild.owner.id) return; channel.guild.channels.create(channel.name, channel.type, [ { id: channel.guild.id, position: channel.calculatedPosition } ]); const embed = new Discord.MessageEmbed() .setTitle(`One Channel Deleted!`) .addField(`Deleter Channel`, entry.executor.tag) .setColor("BLACK") .addField(`Deleted Channel`, channel.name) .addField(`Result`, `Channel Back Opened!`); client.channels.cache.get(kanal).send(embed); } }); client.on("channelCreate", async channel => { let kontrol = await db.fetch(`dil_${channel.guild.id}`); let kanal = await db.fetch(`kanalk_${channel.guild.id}`); if (!kanal) return; if (kontrol == "TR_tr") { const entry = await channel.guild .fetchAuditLogs({ type: "CHANNEL_CREATE" }) .then(audit => audit.entries.first()); if (entry.executor.id == client.user.id) return; if (entry.executor.id == channel.guild.owner.id) return; channel.delete(); const embed = new Discord.MessageEmbed() .setTitle(`Bir Kanal Açıldı!`) .setColor("BLACK") .addField(`Açan`, entry.executor.tag) .addField(`Açılan Kanal`, channel.name) .addField(`Sonuç`, `Kanal Geri Silindi!`); client.channels.cache.get(kanal).send(embed); } else { const entry = await channel.guild .fetchAuditLogs({ type: "CHANNEL_CREATE" }) .then(audit => audit.entries.first()); if (entry.executor.id == client.user.id) return; if (entry.executor.id == channel.guild.owner.id) return; channel.delete(); const embed = new Discord.MessageEmbed() .setTitle(`A Channel Opened!`) .setColor("BLACK") .addField(`Channel Opener`, entry.executor.tag) .addField(`Drop Down Channel`, channel.name) .addField(`Result`, `Channel Back Deleted!`); client.channels.cache.get(kanal).send(embed); } }); client.on("roles.create", async role => { const entry = await role.guild .fetchAuditLogs({ type: "ROLE_CREATE" }) .then(audit => audit.entries.first()); let rol = await db.fetch(`rolrol_${role.guild.id}`); let kontrol = await db.fetch(`dil_${role.guild.id}`); let kanal = await db.fetch(`rolk_${role.guild.id}`); if (!kanal) return; if (kontrol == "TR_tr") { if (!rol) { if (entry.executor.id == client.user.id) return; if (entry.executor.id == role.guild.owner.id) return; role.delete(); const embed = new Discord.MessageEmbed() .setTitle(`Bir Rol Açıldı!`) .setColor("BLACK") .addField(`Açan`, entry.executor.tag) .addField(`Açılan Rol`, role.name) .addField(`Sonuç`, `Rol Geri Silindi!`); client.channels.cache.get(kanal).send(embed); } else { if (entry.executor.roles.cache.has(rol)) { let limito = await db.fetch(`limitrol_${entry.executor.id}`); let slimito = await db.fetch(`rollim_${role.guild.id}`); if (slimito == limito || slimito > limito) { role.delete(); role.guild.members.cache.get(entry.executor.id).kick(); const embed = new Discord.MessageEmbed() .setTitle(`Bir Rol Silen!`) .setColor("BLACK") .addField(`Rolü Açan`, entry.executor.tag) .addField(`Açılan Rol`, role.name) .addField(`Sonuç`, `Rol geri silindi! Rolü açan sunucudan atıldı!`); client.channels.cache.get(kanal).send(embed); } else { let limito = await db.fetch(`limitrol_${entry.executor.id}`); let slimito = await db.fetch(`rollim_${role.guild.id}`); role.delete(); role.guild.members.cache.get(entry.executor.id).kick(); const embed = new Discord.MessageEmbed() .setTitle(`Bir Rol Silen!`) .setColor("BLACK") .addField(`Rolü Silen`, entry.executor.tag) .addField(`Silinen Rol`, role.name) .addField( `Sonuç`, `Rol geri silinmedi! Rolü açan ${limito}/${slimito} sınırına ulaştı!` ); client.channels.cache.get(kanal).send(embed); } } else { role.delete(); const embed = new Discord.MessageEmbed() .setTitle(`Bir Rol Silindi!`) .setColor("BLACK") .addField(`Rolü Açan`, entry.executor.tag) .addField(`Açılan Rol`, role.name) .addField(`Sonuç`, `Rol Geri Silindi!`); client.channels.cache.get(kanal).send(embed); } } } else { if (!rol) { if (entry.executor.id == client.user.id) return; if (entry.executor.id == role.guild.owner.id) return; role.delete(); const embed = new Discord.MessageEmbed() .setTitle(`A Role Created!`) .setColor("BLACK") .addField(`Role Creator`, entry.executor.tag) .addField(`Creating Role`, role.name) .addField(`Result`, `Role Back A Deleted!`); client.channels.cache.get(kanal).send(embed); } else { if (entry.executor.roles.cache.has(rol)) { let limito = await db.fetch(`limitrol_${entry.executor.id}`); let slimito = await db.fetch(`rollim_${role.guild.id}`); if (slimito == limito || slimito > limito) { role.delete(); role.guild.members.cache.get(entry.executor.id).kick(); const embed = new Discord.MessageEmbed() .setTitle(`A Role Created!`) .setColor("BLACK") .addField(`Role Creator`, entry.executor.tag) .addField(`Creating Role`, role.name) .addField( `Result`, `Role Back A Deleted! Role Creator Kicking Has Guild!` ); client.channels.cache.get(kanal).send(embed); } else { let limito = await db.fetch(`limitrol_${entry.executor.id}`); let slimito = await db.fetch(`rollim_${role.guild.id}`); role.delete(); role.guild.members.cache.get(entry.executor.id).kick(); const embed = new Discord.MessageEmbed() .setTitle(`A Role Created!`) .setColor("BLACK") .addField(`Role Creator`, entry.executor.tag) .addField(`Creating Role`, role.name) .addField( `Result`, `The role could not be turned delete back! Reached ${limito}/${slimito} limit, which opens the role!` ); client.channels.cache.get(kanal).send(embed); } } else { role.delete(); const embed = new Discord.MessageEmbed() .setTitle(`A Role Created!`) .setColor("BLACK") .addField(`Role Creator`, entry.executor.tag) .addField(`Creating Role`, role.name) .addField(`Result`, `Role Back A Open`); client.channels.cache.get(kanal).send(embed); } } } }); client.on("roleDelete", async role => { const entry = await role.guild .fetchAuditLogs({ type: "ROLE_DELETE" }) .then(audit => audit.entries.first()); let rol = await db.fetch(`rolrol_${role.guild.id}`); let kontrol = await db.fetch(`dil_${role.guild.id}`); let kanal = await db.fetch(`rolk_${role.guild.id}`); if (!kanal) return; if (kontrol == "TR_tr") { if (!rol) { if (entry.executor.id == client.user.id) return; if (entry.executor.id == role.guild.owner.id) return; role.guild .roles.create({ name: role.name, color: role.color, hoist: role.hoist, permissions: role.permissions, mentionable: role.mentionable, position: role.position }) .then(r => r.setPosition(role.position)); const embed = new Discord.MessageEmbed() .setTitle(`Bir Rol Silindi!`) .setColor("BLACK") .addField(`Silen`, entry.executor.tag) .addField(`Silinen Rol`, role.name) .addField(`Sonuç`, `Rol Geri Açıldı!`); client.channels.cache.get(kanal).send(embed); } else { if (entry.executor.roles.cache.has(rol)) { let limito = await db.fetch(`limitrol_${entry.executor.id}`); let slimito = await db.fetch(`rollim_${role.guild.id}`); if (slimito == limito || slimito > limito) { role.guild .roles.create({ name: role.name, color: role.color, hoist: role.hoist, permissions: role.permissions, mentionable: role.mentionable, position: role.position }) .then(r => r.setPosition(role.position)); role.guild.members.cache.get(entry.executor.id).kick(); const embed = new Discord.MessageEmbed() .setTitle(`Bir Rol Silen!`) .setColor("BLACK") .addField(`Rolü Silen`, entry.executor.tag) .addField(`Silinen Rol`, role.name) .addField(`Sonuç`, `Rol geri açıldı! Rolü silen sunucudan atıldı!`); client.channels.cache.get(kanal).send(embed); } else { let limito = await db.fetch(`limitrol_${entry.executor.id}`); let slimito = await db.fetch(`rollim_${role.guild.id}`); role.guild .roles.create({ name: role.name, color: role.color, hoist: role.hoist, permissions: role.permissions, mentionable: role.mentionable, position: role.position }) .then(r => r.setPosition(role.position)); role.guild.members.cache.get(entry.executor.id).kick(); const embed = new Discord.MessageEmbed() .setTitle(`Bir Rol Silen!`) .setColor("BLACK") .addField(`Rolü Silen`, entry.executor.tag) .addField(`Silinen Rol`, role.name) .addField( `Sonuç`, `Rol geri açılamadı! Rolü silen ${limito}/${slimito} sınırına ulaştı!` ); client.channels.cache.get(kanal).send(embed); } } else { role.guild .roles.create({ name: role.name, color: role.color, hoist: role.hoist, permissions: role.permissions, mentionable: role.mentionable, position: role.position }) .then(r => r.setPosition(role.position)); const embed = new Discord.MessageEmbed() .setTitle(`Bir Rol Silindi!`) .setColor("BLACK") .addField(`Silen`, entry.executor.tag) .addField(`Silinen Rol`, role.name) .addField(`Sonuç`, `Rol Geri Açıldı!`); client.channels.cache.get(kanal).send(embed); } } } else { if (!rol) { if (entry.executor.id == client.user.id) return; if (entry.executor.id == role.guild.owner.id) return; role.guild .roles.create({ name: role.name, color: role.color, hoist: role.hoist, permissions: role.permissions, mentionable: role.mentionable, position: role.position }) .then(r => r.setPosition(role.position)); const embed = new Discord.MessageEmbed() .setTitle(`A Role Deleted!`) .setColor("BLACK") .addField(`Role Deleter`, entry.executor.tag) .addField(`Deleting Role`, role.name) .addField(`Result`, `Role Back A Open!`); client.channels.cache.get(kanal).send(embed); } else { if (entry.executor.roles.cache.has(rol)) { let limito = await db.fetch(`limitrol_${entry.executor.id}`); let slimito = await db.fetch(`rollim_${role.guild.id}`); if (slimito == limito || slimito > limito) { role.guild .roles.create({ name: role.name, color: role.color, hoist: role.hoist, permissions: role.permissions, mentionable: role.mentionable, position: role.position }) .then(r => r.setPosition(role.position)); role.guild.members.cache.get(entry.executor.id).kick(); const embed = new Discord.MessageEmbed() .setTitle(`A Role Deleted!`) .setColor("BLACK") .addField(`Role Deleter`, entry.executor.tag) .addField(`Deleting Role`, role.name) .addField( `Result`, `Role Back A Open! Role Deleter Kicking Has Guild!` ); client.channels.cache.get(kanal).send(embed); } else { let limito = await db.fetch(`limitrol_${entry.executor.id}`); let slimito = await db.fetch(`rollim_${role.guild.id}`); role.guild .roles.create({ name: role.name, color: role.color, hoist: role.hoist, permissions: role.permissions, mentionable: role.mentionable, position: role.position }) .then(r => r.setPosition(role.position)); role.guild.members.cache.get(entry.executor.id).kick(); const embed = new Discord.MessageEmbed() .setTitle(`A Role Deleted!`) .setColor("BLACK") .addField(`Role Deleter`, entry.executor.tag) .addField(`Deleting Role`, role.name) .addField( `Result`, `The role could not be turned back! Reached ${limito}/${slimito} limit, which opens the role!` ); client.channels.cache.get(kanal).send(embed); } } else { role.guild .roles.create({ name: role.name, color: role.color, hoist: role.hoist, permissions: role.permissions, mentionable: role.mentionable, position: role.position }) .then(r => r.setPosition(role.position)); const embed = new Discord.MessageEmbed() .setTitle(`A Role Deleted!`) .setColor("BLACK") .addField(`Role Deleter`, entry.executor.tag) .addField(`Deleting Role`, role.name) .addField(`Result`, `Role Back A Open`); client.channels.cache.get(kanal).send(embed); } } } }); setInterval(async() => { client.guilds.cache.forEach(async guild => { let mid = await db.fetch(`cfxmid${guild.id}`) let channel = await db.fetch(`cfxcn${guild.id}`) if(!mid) return; if(!channel) return; guild.channels.get(`${channel}`).fetchMessage(mid).then(async m => { let time = await db.fetch(`cfxcekilis${guild.id}`) if(!time) return; let sures = await db.fetch(`cfxsure${guild.id}`) let cont = await db.fetch(`cfxm${guild.id}`) let timing = Date.now() - time let aracheck = new Discord.MessageEmbed() .setFooter(`© ${client.guilds.cache.get(guild.id).name}`) .setAuthor('Çekiliş ödülü:' + ' [ ' +cont+ ' ]') .setColor("ff0000") .setDescription(`**Çekilişe kalan**:` + ` \`${moment.duration(sures - timing).format(`DD **[Gün,]** HH **[Saat,]** mm **[Dakika,]** ss **[Saniye]**`)}\` ` ) m.edit(aracheck) await m.react('🎉'); if(timing >= sures) { let users = await db.fetch(`cfxcdb.${guild.id}`) let list = users.filter(u => u); let joins = list[Math.floor(Math.random() * list.length)] if (joins == undefined) joins = `Çekilişe kimse katılmadı!` if(joins != `Çekilişe kimse katılmadı!` && joins != undefined) { let kazananlar = new Discord.MessageEmbed() .addField('** **', '**Kazananlar:** \n'+ guild.members.get(joins)) .setAuthor('Çekiliş ödülü:' + ' [ ' +cont+ ' ]') .setFooter(`© ${client.guilds.cache.get(guild.id).name}`) .setColor("ff0000") guild.channels.cache.get(channel).send(kazananlar) } let endEmbed = new Discord.MessageEmbed() .setFooter(`${client.guilds.cache.get(guild.id).name}`) .setColor("ff0000") .setAuthor('Çekiliş ödülü:' + ' [ ' +cont+ ' ]') .setDescription('**Kazananlar**: \n'+ guild.members.cache.get(joins)) m.edit(endEmbed) db.delete(`cfxcekilis${guild.id}`) } }) }) }, 5000) client.on('raw', async event => { if(event.t === 'MESSAGE_REACTION_ADD' || event.t === 'MESSAGE_REACTION_REMOVE'){ client.guilds.cache.forEach(async guild => { let channel_id = await db.fetch(`cfxcn${guild.id}`) let mid = await db.fetch(`cfxmid${guild.id}`) let channel = guild.channels.cache.find(x => x.id === channel_id) if(!mid) return; if(!channel) return; let message = channel.fetchMessage(mid).then(async msg => { let user = msg.guild.members.cache.get(event.d.user_id) if(user.id != client.user.id){ var objmember = msg.guild.members.cache.get(user.id); if(objmember.user.bot) return; if(event.t === 'MESSAGE_REACTION_ADD'){ let cfxcdb = await db.fetch(`cfxcdb.${guild.id}`) if(cfxcdb == null) db.push(`cfxcdb.${guild.id}`, `${user.id}`) if(cfxcdb.includes(user.id)) return; db.push(`cfxcdb.${guild.id}`, `${user.id}`) } } }) }) } }) /*client.on("message", async (lydia) => { let crawll = await db.fetch(`küfürengel_${lydia.guild.id}`) if(!crawl) return let crawl = lydia.content if(lydia.member.permissions.has("ADMINISTRATOR")) return let küfürler = ["aq","amk","sikik","sik","yarak","pezevenk","orospu","orosbu","sikiş","sokuş","anal","annenin","oç", "oc","piç", "amq", "sik", "amcık", "çocu", "sex", "seks", "amına", "orospu çocuğu", "sg", "siktir git"] if (küfürler.some(word => lydia.content.toLowerCase().includes(word)) ) { lydia.delete(30) let dc = await db.fetch(`küfür_${lydia.guild.id}_${lydia.author.id}`) if(!dc) dc = 1 lydia.channel.send("<@!"+lydia.author.id+"> Bu sunucuda küfürler **"+client.user.username+"** tarafından engelleniyor.Bu sunucu da toplam **"+dc+"** kere küfür etmişsin!").then(m => m.delete(5000)) db.add(`küfür_${lydia.guild.id}_${lydia.author.id}`, 1) } }) client.on("message", async (lydia1) => { let crawll1 = await db.fetch(`reklamengel_${lydia1.guild.id}`) if(!crawl2) return let crawl2 = lydia1.content if(lydia1.member.permissions.has("ADMINISTRATOR")) return let reklamlar = ["discord.app", "discord.gg","discordapp","discordgg", ".com", ".net", ".xyz", ".tk", ".pw", ".io", ".me", ".gg", "www.", "https", "http", ".gl", ".org", ".com.tr", ".biz", ".party", ".rf.gd", ".az", ".ee"] if (reklamlar.some(word => lydia1.content.toLowerCase().includes(word)) ) { lydia1.delete(30) let dc = await db.fetch(`reklam_${lydia1.guild.id}_${lydia1.author.id}`) if(!dc) dc = 1 lydia1.channel.send("<@!"+lydia1.author.id+"> Bu sunucuda reklamlar **"+client.user.username+"** tarafından engelleniyor.Bu sunucu da toplam **"+dc+"** kere reklam yapmışsın!").then(m => m.delete(5000)) db.add(`reklam_${lydia1.guild.id}_${lydia1.author.id}`, 1) } })*/
import sys # Find jVMC package sys.path.append(sys.path[0]+"/..") import unittest import jax from jax.config import config config.update("jax_enable_x64", True) import jax.random as random import jax.numpy as jnp import numpy as np from scipy.interpolate import interp1d import jVMC import jVMC.global_defs as global_defs import jVMC.util.stepper as jVMCstepper import jVMC.nets as nets from jVMC.vqs import NQS import jVMC.operator as op import jVMC.sampler as sampler from jVMC.util import measure, ground_state_search class TestGsSearch(unittest.TestCase): def test_gs_search_cpx(self): L=4 J=-1.0 hxs=[-1.3, -0.3] exEs=[-6.10160339, -4.09296160] for hx,exE in zip(hxs,exEs): # Set up variational wave function rbm = nets.CpxRBM(numHidden=6,bias=False) psi = NQS(rbm) # Set up hamiltonian for ground state search hamiltonianGS = op.BranchFreeOperator() for l in range(L): hamiltonianGS.add( op.scal_opstr( J, ( op.Sz(l), op.Sz((l+1)%L) ) ) ) hamiltonianGS.add( op.scal_opstr( hx, ( op.Sx(l), ) ) ) # Set up exact sampler exactSampler=sampler.ExactSampler(psi,L) delta=2 tdvpEquation = jVMC.util.TDVP(exactSampler, snrTol=1, svdTol=1e-8, rhsPrefactor=1., diagonalShift=delta, makeReal='real') # Perform ground state search to get initial state ground_state_search(psi, hamiltonianGS, tdvpEquation, exactSampler, numSteps=100, stepSize=2e-2) obs = measure({"energy":hamiltonianGS}, psi, exactSampler) self.assertTrue( jnp.max( jnp.abs( ( obs['energy']['mean'] - exE ) / exE) ) < 1e-3 ) class TestTimeEvolution(unittest.TestCase): def test_time_evolution(self): L=4 J=-1.0 hx=-0.3 weights=jnp.array( [ 0.23898957, 0.12614753, 0.19479055, 0.17325271, 0.14619853, 0.21392751, 0.19648707, 0.17103704, -0.15457255, 0.10954413, 0.13228065, -0.14935214, -0.09963073, 0.17610707, 0.13386381, -0.14836467] ) # Set up variational wave function rbm = nets.CpxRBM(numHidden=2,bias=False) psi = NQS(rbm) psi(jnp.array([[[1,1,1,1]]])) psi.set_parameters(weights) # Set up hamiltonian for time evolution hamiltonian = op.BranchFreeOperator() for l in range(L): hamiltonian.add( op.scal_opstr( J, ( op.Sz(l), op.Sz((l+1)%L) ) ) ) hamiltonian.add( op.scal_opstr( hx, ( op.Sx(l), ) ) ) # Set up ZZ observable ZZ = op.BranchFreeOperator() for l in range(L): ZZ.add( ( op.Sz(l), op.Sz((l+1)%L) ) ) # Set up exact sampler exactSampler=sampler.ExactSampler(psi,L) # Set up adaptive time stepper stepper = jVMCstepper.AdaptiveHeun(timeStep=1e-3, tol=1e-5) tdvpEquation = jVMC.util.TDVP(exactSampler, snrTol=1, svdTol=1e-8, rhsPrefactor=1.j, diagonalShift=0., makeReal='imag') t=0 obs=[] times=[] times.append(t) newMeas = measure({'E':hamiltonian, 'ZZ':ZZ}, psi, exactSampler) obs.append([newMeas['E']['mean'], newMeas['ZZ']['mean']]) while t<0.5: dp, dt = stepper.step(0, tdvpEquation, psi.get_parameters(), hamiltonian=hamiltonian, psi=psi, numSamples=0) psi.set_parameters(dp) t += dt times.append(t) newMeas = measure({'E':hamiltonian, 'ZZ':ZZ}, psi, exactSampler) obs.append([newMeas['E']['mean'], newMeas['ZZ']['mean']]) obs = np.array(jnp.asarray(obs)) # Check energy conservation obs[:,0] = np.abs( (obs[:,0] - obs[0,0]) / obs[0,0] ) self.assertTrue( np.max(obs[:,0]) < 1e-3 ) # Check observable dynamics zz = interp1d(np.array(times), obs[:,1,0]) refTimes = np.arange(0,0.5,0.05) netZZ=zz(refTimes) refZZ = np.array( [0.882762129306284, 0.8936168721790617, 0.9257753299594491, 0.9779836185039352, 1.0482156449061142, 1.1337654450614298, 1.231369697427413, 1.337354107391303, 1.447796176316155, 1.558696104640795, 1.666147269524912, 1.7664978782554912, 1.8564960156892512, 1.9334113379450693, 1.9951280521882777, 2.0402054805651546, 2.067904337137255, 2.078178742959828, 2.071635856483114, 2.049466698269522, 2.049466698269522] ) self.assertTrue( np.max(np.abs( netZZ - refZZ[:len(netZZ)] )) < 1e-3 ) if __name__ == "__main__": unittest.main()
export const messages = { title: 'Match management...', cancel: 'Cancel', start: 'Start', pause: 'Pause', resume: 'Resume', endPeriod: 'End', startPeriod: 'Start', endGame: 'End game' };
// import models const Product = require('./Product'); const Category = require('./Category'); const Tag = require('./Tag'); const ProductTag = require('./ProductTag'); // Products belongsTo Category Product.belongsTo(Category, { foreignKey: 'category_id', onDelete: 'CASCADE' }) // Categories have many Products Category.hasMany(Product, { foreignKey: 'category_id', onDelete: 'CASCADE' }) // Products belongToMany Tags (through ProductTag) Product.belongsToMany(Tag, { through: { model: ProductTag, foreignKey: "product_id" } }) // Tags belongToMany Products (through ProductTag) Tag.belongsToMany(Product, { through: { model: ProductTag, foreignKey: "tag_id" } }) module.exports = { Product, Category, Tag, ProductTag, };
# Copyright 2021 The TensorFlow 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. # Lint as: python3 """Dataset utilities for vision tasks using TFDS and tf.data.Dataset.""" from __future__ import absolute_import from __future__ import division # from __future__ import google_type_annotations from __future__ import print_function import dataclasses import os from typing import Any, List, Mapping, Optional, Tuple, Union from absl import logging import tensorflow as tf import tensorflow_datasets as tfds from official.legacy.image_classification import augment from official.legacy.image_classification import preprocessing from official.modeling.hyperparams import base_config AUGMENTERS = { 'autoaugment': augment.AutoAugment, 'randaugment': augment.RandAugment, } @dataclasses.dataclass class AugmentConfig(base_config.Config): """Configuration for image augmenters. Attributes: name: The name of the image augmentation to use. Possible options are None (default), 'autoaugment', or 'randaugment'. params: Any parameters used to initialize the augmenter. """ name: Optional[str] = None params: Optional[Mapping[str, Any]] = None def build(self) -> augment.ImageAugment: """Build the augmenter using this config.""" params = self.params or {} augmenter = AUGMENTERS.get(self.name, None) return augmenter(**params) if augmenter is not None else None @dataclasses.dataclass class DatasetConfig(base_config.Config): """The base configuration for building datasets. Attributes: name: The name of the Dataset. Usually should correspond to a TFDS dataset. data_dir: The path where the dataset files are stored, if available. filenames: Optional list of strings representing the TFRecord names. builder: The builder type used to load the dataset. Value should be one of 'tfds' (load using TFDS), 'records' (load from TFRecords), or 'synthetic' (generate dummy synthetic data without reading from files). split: The split of the dataset. Usually 'train', 'validation', or 'test'. image_size: The size of the image in the dataset. This assumes that `width` == `height`. Set to 'infer' to infer the image size from TFDS info. This requires `name` to be a registered dataset in TFDS. num_classes: The number of classes given by the dataset. Set to 'infer' to infer the image size from TFDS info. This requires `name` to be a registered dataset in TFDS. num_channels: The number of channels given by the dataset. Set to 'infer' to infer the image size from TFDS info. This requires `name` to be a registered dataset in TFDS. num_examples: The number of examples given by the dataset. Set to 'infer' to infer the image size from TFDS info. This requires `name` to be a registered dataset in TFDS. batch_size: The base batch size for the dataset. use_per_replica_batch_size: Whether to scale the batch size based on available resources. If set to `True`, the dataset builder will return batch_size multiplied by `num_devices`, the number of device replicas (e.g., the number of GPUs or TPU cores). This setting should be `True` if the strategy argument is passed to `build()` and `num_devices > 1`. num_devices: The number of replica devices to use. This should be set by `strategy.num_replicas_in_sync` when using a distribution strategy. dtype: The desired dtype of the dataset. This will be set during preprocessing. one_hot: Whether to apply one hot encoding. Set to `True` to be able to use label smoothing. augmenter: The augmenter config to use. No augmentation is used by default. download: Whether to download data using TFDS. shuffle_buffer_size: The buffer size used for shuffling training data. file_shuffle_buffer_size: The buffer size used for shuffling raw training files. skip_decoding: Whether to skip image decoding when loading from TFDS. cache: whether to cache to dataset examples. Can be used to avoid re-reading from disk on the second epoch. Requires significant memory overhead. tf_data_service: The URI of a tf.data service to offload preprocessing onto during training. The URI should be in the format "protocol://address", e.g. "grpc://tf-data-service:5050". mean_subtract: whether or not to apply mean subtraction to the dataset. standardize: whether or not to apply standardization to the dataset. """ name: Optional[str] = None data_dir: Optional[str] = None filenames: Optional[List[str]] = None builder: str = 'tfds' split: str = 'train' image_size: Union[int, str] = 'infer' num_classes: Union[int, str] = 'infer' num_channels: Union[int, str] = 'infer' num_examples: Union[int, str] = 'infer' batch_size: int = 128 use_per_replica_batch_size: bool = True num_devices: int = 1 dtype: str = 'float32' one_hot: bool = True augmenter: AugmentConfig = AugmentConfig() download: bool = False shuffle_buffer_size: int = 10000 file_shuffle_buffer_size: int = 1024 skip_decoding: bool = True cache: bool = False tf_data_service: Optional[str] = None mean_subtract: bool = False standardize: bool = False @property def has_data(self): """Whether this dataset is has any data associated with it.""" return self.name or self.data_dir or self.filenames @dataclasses.dataclass class ImageNetConfig(DatasetConfig): """The base ImageNet dataset config.""" name: str = 'imagenet2012' # Note: for large datasets like ImageNet, using records is faster than tfds builder: str = 'records' image_size: int = 224 num_channels: int = 3 num_examples: int = 1281167 num_classes: int = 1000 batch_size: int = 128 @dataclasses.dataclass class Cifar10Config(DatasetConfig): """The base CIFAR-10 dataset config.""" name: str = 'cifar10' image_size: int = 224 batch_size: int = 128 download: bool = True cache: bool = True class DatasetBuilder: """An object for building datasets. Allows building various pipelines fetching examples, preprocessing, etc. Maintains additional state information calculated from the dataset, i.e., training set split, batch size, and number of steps (batches). """ def __init__(self, config: DatasetConfig, **overrides: Any): """Initialize the builder from the config.""" self.config = config.replace(**overrides) self.builder_info = None if self.config.augmenter is not None: logging.info('Using augmentation: %s', self.config.augmenter.name) self.augmenter = self.config.augmenter.build() else: self.augmenter = None @property def is_training(self) -> bool: """Whether this is the training set.""" return self.config.split == 'train' @property def batch_size(self) -> int: """The batch size, multiplied by the number of replicas (if configured).""" if self.config.use_per_replica_batch_size: return self.config.batch_size * self.config.num_devices else: return self.config.batch_size @property def global_batch_size(self): """The global batch size across all replicas.""" return self.batch_size @property def local_batch_size(self): """The base unscaled batch size.""" if self.config.use_per_replica_batch_size: return self.config.batch_size else: return self.config.batch_size // self.config.num_devices @property def num_steps(self) -> int: """The number of steps (batches) to exhaust this dataset.""" # Always divide by the global batch size to get the correct # of steps return self.num_examples // self.global_batch_size @property def dtype(self) -> tf.dtypes.DType: """Converts the config's dtype string to a tf dtype. Returns: A mapping from string representation of a dtype to the `tf.dtypes.DType`. Raises: ValueError if the config's dtype is not supported. """ dtype_map = { 'float32': tf.float32, 'bfloat16': tf.bfloat16, 'float16': tf.float16, 'fp32': tf.float32, 'bf16': tf.bfloat16, } try: return dtype_map[self.config.dtype] except: raise ValueError('Invalid DType provided. Supported types: {}'.format( dtype_map.keys())) @property def image_size(self) -> int: """The size of each image (can be inferred from the dataset).""" if self.config.image_size == 'infer': return self.info.features['image'].shape[0] else: return int(self.config.image_size) @property def num_channels(self) -> int: """The number of image channels (can be inferred from the dataset).""" if self.config.num_channels == 'infer': return self.info.features['image'].shape[-1] else: return int(self.config.num_channels) @property def num_examples(self) -> int: """The number of examples (can be inferred from the dataset).""" if self.config.num_examples == 'infer': return self.info.splits[self.config.split].num_examples else: return int(self.config.num_examples) @property def num_classes(self) -> int: """The number of classes (can be inferred from the dataset).""" if self.config.num_classes == 'infer': return self.info.features['label'].num_classes else: return int(self.config.num_classes) @property def info(self) -> tfds.core.DatasetInfo: """The TFDS dataset info, if available.""" try: if self.builder_info is None: self.builder_info = tfds.builder(self.config.name).info except ConnectionError as e: logging.error('Failed to use TFDS to load info. Please set dataset info ' '(image_size, num_channels, num_examples, num_classes) in ' 'the dataset config.') raise e return self.builder_info def build( self, strategy: Optional[tf.distribute.Strategy] = None) -> tf.data.Dataset: """Construct a dataset end-to-end and return it using an optional strategy. Args: strategy: a strategy that, if passed, will distribute the dataset according to that strategy. If passed and `num_devices > 1`, `use_per_replica_batch_size` must be set to `True`. Returns: A TensorFlow dataset outputting batched images and labels. """ if strategy: if strategy.num_replicas_in_sync != self.config.num_devices: logging.warn( 'Passed a strategy with %d devices, but expected' '%d devices.', strategy.num_replicas_in_sync, self.config.num_devices) dataset = strategy.distribute_datasets_from_function(self._build) else: dataset = self._build() return dataset def _build( self, input_context: Optional[tf.distribute.InputContext] = None ) -> tf.data.Dataset: """Construct a dataset end-to-end and return it. Args: input_context: An optional context provided by `tf.distribute` for cross-replica training. Returns: A TensorFlow dataset outputting batched images and labels. """ builders = { 'tfds': self.load_tfds, 'records': self.load_records, 'synthetic': self.load_synthetic, } builder = builders.get(self.config.builder, None) if builder is None: raise ValueError('Unknown builder type {}'.format(self.config.builder)) self.input_context = input_context dataset = builder() dataset = self.pipeline(dataset) return dataset def load_tfds(self) -> tf.data.Dataset: """Return a dataset loading files from TFDS.""" logging.info('Using TFDS to load data.') builder = tfds.builder(self.config.name, data_dir=self.config.data_dir) if self.config.download: builder.download_and_prepare() decoders = {} if self.config.skip_decoding: decoders['image'] = tfds.decode.SkipDecoding() read_config = tfds.ReadConfig( interleave_cycle_length=10, interleave_block_length=1, input_context=self.input_context) dataset = builder.as_dataset( split=self.config.split, as_supervised=True, shuffle_files=True, decoders=decoders, read_config=read_config) return dataset def load_records(self) -> tf.data.Dataset: """Return a dataset loading files with TFRecords.""" logging.info('Using TFRecords to load data.') if self.config.filenames is None: if self.config.data_dir is None: raise ValueError('Dataset must specify a path for the data files.') file_pattern = os.path.join(self.config.data_dir, '{}*'.format(self.config.split)) dataset = tf.data.Dataset.list_files(file_pattern, shuffle=False) else: dataset = tf.data.Dataset.from_tensor_slices(self.config.filenames) return dataset def load_synthetic(self) -> tf.data.Dataset: """Return a dataset generating dummy synthetic data.""" logging.info('Generating a synthetic dataset.') def generate_data(_): image = tf.zeros([self.image_size, self.image_size, self.num_channels], dtype=self.dtype) label = tf.zeros([1], dtype=tf.int32) return image, label dataset = tf.data.Dataset.range(1) dataset = dataset.repeat() dataset = dataset.map( generate_data, num_parallel_calls=tf.data.experimental.AUTOTUNE) return dataset def pipeline(self, dataset: tf.data.Dataset) -> tf.data.Dataset: """Build a pipeline fetching, shuffling, and preprocessing the dataset. Args: dataset: A `tf.data.Dataset` that loads raw files. Returns: A TensorFlow dataset outputting batched images and labels. """ if (self.config.builder != 'tfds' and self.input_context and self.input_context.num_input_pipelines > 1): dataset = dataset.shard(self.input_context.num_input_pipelines, self.input_context.input_pipeline_id) logging.info( 'Sharding the dataset: input_pipeline_id=%d ' 'num_input_pipelines=%d', self.input_context.num_input_pipelines, self.input_context.input_pipeline_id) if self.is_training and self.config.builder == 'records': # Shuffle the input files. dataset.shuffle(buffer_size=self.config.file_shuffle_buffer_size) if self.is_training and not self.config.cache: dataset = dataset.repeat() if self.config.builder == 'records': # Read the data from disk in parallel dataset = dataset.interleave( tf.data.TFRecordDataset, cycle_length=10, block_length=1, num_parallel_calls=tf.data.experimental.AUTOTUNE) if self.config.cache: dataset = dataset.cache() if self.is_training: dataset = dataset.shuffle(self.config.shuffle_buffer_size) dataset = dataset.repeat() # Parse, pre-process, and batch the data in parallel if self.config.builder == 'records': preprocess = self.parse_record else: preprocess = self.preprocess dataset = dataset.map( preprocess, num_parallel_calls=tf.data.experimental.AUTOTUNE) if self.input_context and self.config.num_devices > 1: if not self.config.use_per_replica_batch_size: raise ValueError( 'The builder does not support a global batch size with more than ' 'one replica. Got {} replicas. Please set a ' '`per_replica_batch_size` and enable ' '`use_per_replica_batch_size=True`.'.format( self.config.num_devices)) # The batch size of the dataset will be multiplied by the number of # replicas automatically when strategy.distribute_datasets_from_function # is called, so we use local batch size here. dataset = dataset.batch( self.local_batch_size, drop_remainder=self.is_training) else: dataset = dataset.batch( self.global_batch_size, drop_remainder=self.is_training) # Prefetch overlaps in-feed with training dataset = dataset.prefetch(tf.data.experimental.AUTOTUNE) if self.config.tf_data_service: if not hasattr(tf.data.experimental, 'service'): raise ValueError('The tf_data_service flag requires Tensorflow version ' '>= 2.3.0, but the version is {}'.format( tf.__version__)) dataset = dataset.apply( tf.data.experimental.service.distribute( processing_mode='parallel_epochs', service=self.config.tf_data_service, job_name='resnet_train')) dataset = dataset.prefetch(buffer_size=tf.data.experimental.AUTOTUNE) return dataset def parse_record(self, record: tf.Tensor) -> Tuple[tf.Tensor, tf.Tensor]: """Parse an ImageNet record from a serialized string Tensor.""" keys_to_features = { 'image/encoded': tf.io.FixedLenFeature((), tf.string, ''), 'image/format': tf.io.FixedLenFeature((), tf.string, 'jpeg'), 'image/class/label': tf.io.FixedLenFeature([], tf.int64, -1), 'image/class/text': tf.io.FixedLenFeature([], tf.string, ''), 'image/object/bbox/xmin': tf.io.VarLenFeature(dtype=tf.float32), 'image/object/bbox/ymin': tf.io.VarLenFeature(dtype=tf.float32), 'image/object/bbox/xmax': tf.io.VarLenFeature(dtype=tf.float32), 'image/object/bbox/ymax': tf.io.VarLenFeature(dtype=tf.float32), 'image/object/class/label': tf.io.VarLenFeature(dtype=tf.int64), } parsed = tf.io.parse_single_example(record, keys_to_features) label = tf.reshape(parsed['image/class/label'], shape=[1]) # Subtract one so that labels are in [0, 1000) label -= 1 image_bytes = tf.reshape(parsed['image/encoded'], shape=[]) image, label = self.preprocess(image_bytes, label) return image, label def preprocess(self, image: tf.Tensor, label: tf.Tensor) -> Tuple[tf.Tensor, tf.Tensor]: """Apply image preprocessing and augmentation to the image and label.""" if self.is_training: image = preprocessing.preprocess_for_train( image, image_size=self.image_size, mean_subtract=self.config.mean_subtract, standardize=self.config.standardize, dtype=self.dtype, augmenter=self.augmenter) else: image = preprocessing.preprocess_for_eval( image, image_size=self.image_size, num_channels=self.num_channels, mean_subtract=self.config.mean_subtract, standardize=self.config.standardize, dtype=self.dtype) label = tf.cast(label, tf.int32) if self.config.one_hot: label = tf.one_hot(label, self.num_classes) label = tf.reshape(label, [self.num_classes]) return image, label @classmethod def from_params(cls, *args, **kwargs): """Construct a dataset builder from a default config and any overrides.""" config = DatasetConfig.from_args(*args, **kwargs) return cls(config)
class PlayerArrow { constructor(x, y, width, height, archerAngle) { var options = { isStatic: true, density: 0.1 }; this.width = width; this.height = height; this.body = Bodies.rectangle(x, y, this.width, this.height, options); this.image = loadImage("assets/arrow.png"); this.archerAngle = archerAngle; this.velocity = 0; World.add(world, this.body); } display() { var pos = this.body.position; var angle = this.body.angle; push(); rotate(angle); imageMode(CENTER); image(this.image, 0, 0, this. width, this. height); pop(); } }
'use strict'; const objectFromEntries = require('object.fromentries'); objectFromEntries.shim(); const { entries, fromEntries, keys } = Object; const APIGATEWAY_INTEGRATION_TYPE_HTTP_PROXY = 'HTTP_PROXY'; const APIGATEWAY_ROOT_ID = 'RootResourceId'; const APIGATEWAY_TYPE_METHOD = 'AWS::ApiGateway::Method'; const APIGATEWAY_TYPE_RESOURCE = 'AWS::ApiGateway::Resource'; function getApiGatewayTemplateObjects(resources) { const Resources = resources && resources.Resources; if (!Resources) { return {}; } const methodObjects = []; const pathObjects = []; entries(Resources).forEach(([key, value]) => { const resourceObj = value || {}; const { Type } = resourceObj; const keyValuePair = [key, resourceObj]; if (Type === APIGATEWAY_TYPE_METHOD) { methodObjects.push(keyValuePair); } else if (Type === APIGATEWAY_TYPE_RESOURCE) { pathObjects.push(keyValuePair); } }); return { methodObjects: fromEntries(methodObjects), pathObjects: fromEntries(pathObjects), }; } /* Example of a Resource Object * "ApiGatewayResourceFavicon": { * "Type": "AWS::ApiGateway::Resource", * "Properties": { * "ParentId": { "Fn::GetAtt": [ "ApiGatewayRestApi", "RootResourceId" ] }, * "PathPart": "favicon.ico", * "RestApiId": { "Ref": "ApiGatewayRestApi" } * } * } */ /* Resource Helpers */ function isRoot(resourceId) { return resourceId === APIGATEWAY_ROOT_ID; } function getPathPart(resourceObj) { if (!resourceObj || !resourceObj.Properties) { return undefined; } return resourceObj.Properties.PathPart; } function getParentId(resourceObj) { if (!resourceObj || !resourceObj.Properties) { return undefined; } const parentIdObj = resourceObj.Properties.ParentId || {}; const { Ref } = parentIdObj; if (Ref) return Ref; const getAtt = parentIdObj['Fn::GetAtt'] || []; return getAtt[1]; } function getFullPath(pathObjects, resourceId) { let currentId = resourceId; let currentObj; const arrResourceObjects = []; while (currentId && !isRoot(currentId)) { currentObj = pathObjects[currentId]; arrResourceObjects.push(currentObj); currentId = getParentId(currentObj); } const arrPath = arrResourceObjects.map(getPathPart).reverse(); if (arrPath.some((s) => !s)) { return undefined; } return `/${arrPath.join('/')}`; } /* Example of an HTTP Proxy Method Object * "ApiGatewayResourcePublicAnyProxyMethod": { * "Type": "AWS::ApiGateway::Method", * "Properties": { * "ResourceId": { "Ref": "ApiGatewayResourcePublicAny" }, * "RestApiId": { "Ref": "ApiGatewayRestApi" }, * "AuthorizationType": "NONE", * "HttpMethod": "GET", * "MethodResponses": [ { "StatusCode": 200 } ], * "RequestParameters": { "method.request.path.proxy": true }, * "Integration": { * "Type": "HTTP_PROXY", * "IntegrationHttpMethod": "GET", * "Uri": "https://www.example.com/us-west-2/{proxy}", // Note that ${self:provider.region} is expanded * "IntegrationResponses": [ { "StatusCode": 200 } ], * "RequestParameters": { "integration.request.path.proxy": "method.request.path.proxy" }, * "PassthroughBehavior": "WHEN_NO_MATCH" * } * } * } */ /* Method Helpers */ function getResourceId(methodObj) { if (!methodObj || !methodObj.Properties) { return undefined; } if (!methodObj.Properties.ResourceId) { return undefined; } return methodObj.Properties.ResourceId.Ref; } function getHttpMethod(methodObj) { if (!methodObj || !methodObj.Properties) { return undefined; } return methodObj.Properties.HttpMethod; } function getIntegrationObj(methodObj) { if (!methodObj || !methodObj.Properties) { return undefined; } return methodObj.Properties.Integration; } function templatePathToHapiPath(path) { return path.replace('+', ''); } function constructHapiInterface(pathObjects, methodObjects, methodId) { // returns all info necessary so that routes can be added in index.js const methodObj = methodObjects[methodId]; const resourceId = getResourceId(methodObj); const Integration = getIntegrationObj(methodObj) || {}; const pathResource = getFullPath(pathObjects, resourceId); const method = getHttpMethod(methodObj); // let integrationType; let proxyUri; if (!pathResource) { return {}; } const path = templatePathToHapiPath(pathResource); if (Integration.Type === APIGATEWAY_INTEGRATION_TYPE_HTTP_PROXY) { proxyUri = Integration.Uri; } return { isProxy: !!proxyUri, method, path, pathResource, proxyUri, }; } module.exports = function parseResources(resources) { const { methodObjects, pathObjects } = getApiGatewayTemplateObjects( resources, ); return fromEntries( keys(methodObjects).map((key) => [ key, constructHapiInterface(pathObjects, methodObjects, key), ]), ); };
'use strict'; var _ = require('lodash'); var parse = require('url-parse'); var glimpse = require('glimpse'); var _strategies = []; var getContentTypeCategory = (function() { var listing = { 'text/html': {'document': true, 'highlight': 'xml'}, 'text/plain': {'document': true}, 'application/xhtml+xml': {'document': true, 'highlight': 'xml'}, 'text/xml': {'data': true, 'highlight': 'xml'}, 'application/json': {'data': true, 'highlight': 'json'}, 'text/css': {'stylesheet': true, 'highlight': 'css'}, 'text/xsl': {'stylesheet': true, 'highlight': 'xml'}, 'image/jpg': {'image': true}, 'image/jpeg': {'image': true}, 'image/pjpeg': {'image': true}, 'image/png': {'image': true}, 'image/gif': {'image': true}, 'image/bmp': {'image': true}, 'image/svg+xml': {'image': true, 'font': true, 'document': true}, 'image/vnd.microsoft.icon': {'image': true}, 'image/webp': {'image': true}, 'image/x-icon': {'image': true}, 'image/x-xbitmap': {'image': true}, 'font/ttf': {'font': true}, 'font/otf': {'font': true}, 'font/woff': {'font': true}, 'font/woff2': {'font': true}, 'font/truetype': {'font': true}, 'font/opentype': {'font': true}, 'application/octet-stream': {'font': true, 'image': true}, 'application/font-woff': {'font': true}, 'application/font-woff2': {'font': true}, 'application/x-font-woff': {'font': true}, 'application/x-font-type1': {'font': true}, 'application/x-font-ttf': {'font': true}, 'application/x-truetype-font': {'font': true}, 'text/javascript': {'script': true, 'highlight': 'javascript'}, 'text/ecmascript': {'script': true, 'highlight': 'javascript'}, 'application/javascript': {'script': true, 'highlight': 'javascript'}, 'application/ecmascript': {'script': true, 'highlight': 'javascript'}, 'application/x-javascript': {'script': true, 'highlight': 'javascript'}, 'text/javascript1.1': {'script': true, 'highlight': 'javascript'}, 'text/javascript1.2': {'script': true, 'highlight': 'javascript'}, 'text/javascript1.3': {'script': true, 'highlight': 'javascript'}, 'text/jscript': {'script': true, 'highlight': 'javascript'}, 'text/livescript': {'script': true, 'highlight': 'livescript'}, 'text/vtt': {'texttrack': true}, }; return function(contentType) { if (contentType) { var target = ''; for (var i = 0; i < contentType.length; i++) { var char = contentType[i]; if (char == ';') { break; } target += char } return listing[target]; } }; })(); var getStatusCodeText = (function() { var listing = { 100: 'Continue', 101: 'Switching Protocols', 102: 'Processing', 200: 'OK', 201: 'Created', 202: 'Accepted', 203: 'Non-Authoritative Information', 204: 'No Content', 205: 'Reset Content', 206: 'Partial Content', 207: 'Multi-Status', 208: 'Already Reported', 226: 'IM Used', 300: 'Multiple Choices', 301: 'Moved Permanentl', 302: 'Found', 303: 'See Other', 304: 'Not Modified', 305: 'Use Proxy', 307: 'Temporary Redirect', 308: 'Permanent Redirect', 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required', 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed', 406: 'Not Acceptable', 407: 'Proxy Authentication Required', 408: 'Request Timeout', 409: 'Conflict', 410: 'Gone', 411: 'Length Required', 412: 'Precondition Failed', 413: 'Payload Too Large', 414: 'URI Too Long', 415: 'Unsupported Media Type', 416: 'Range Not Satisfiable', 417: 'Expectation Failed', 421: 'Misdirected Request', 422: 'Unprocessable Entity', 423: 'Locked', 424: 'Failed Dependency', 425: 'Unassigned', 426: 'Upgrade Required', 427: 'Unassigned', 428: 'Precondition Required', 429: 'Too Many Requests', 430: 'Unassigned', 431: 'Request Header Fields Too Large', 500: 'Internal Server Error', 501: 'Not Implemented', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Timeout', 505: 'HTTP Version Not Supported', 506: 'Variant Also Negotiates', 507: 'Insufficient Storage', 508: 'Loop Detected', 509: 'Unassigned', 510: 'Not Extended', 511: 'Network Authentication Required' }; return function(statusCode) { return listing[statusCode]; }; })(); var modifyPayload = (function() { // TODO: need to work out what we are doing with derived data, etc... // should this be a message strategy or should we support message vs type // strategies. Do i need to promote these index strategies above others.. return { deriveProperties: function(request, type, payload) { if (type == 'web-request' || type == 'data-http-request') { var url = parse(payload.url); payload.path = url.pathname; payload.query = url.query; } else if (type == 'web-response' || type == 'data-http-response') { var contentType = payload.headers && glimpse.util.getPropertyCaseInsensitive(payload.headers, 'Content-Type')[0]; payload.contentType = contentType; payload.statusText = getStatusCodeText(payload.statusCode); payload.contentCategory = getContentTypeCategory(payload.contentType); } }, setupIndex: function(request, type, payload) { if (type == 'web-request') { request._requestStartTime = payload.startTime; request._requestMethod = payload.method; request._requestUrl = payload.path + payload.query; request._requestIsAjax = payload.requestIsAjax; } else if (type == 'web-response') { request._responseStatusCode = payload.statusCode; request._responseStatusText = payload.statusText; request._responseContentType = payload.contentType; request._responseContentCategory = payload.contentCategory; } else if (type == 'web-response') { request._userId = payload.userId; } } }; })(); module.exports = { registerStrategy: function(strategy) { _strategies.push(strategy); glimpse.emit('system.request.converter.strategy.added', { strategy: strategy }); }, createRequest: function(requestId) { return { id: requestId, messages: {} }; }, convertMessages: function(request, messages) { var didUpdate = false; // setup the type index if (!request.types) { request.types = {}; } _.forEach(messages, function(message) { if (!request.messages[message.id]) { // copy across the messages into the message index request.messages[message.id] = message; // copy across the messages into the type index _.forEach(message.types, function(type) { // TODO: hack, find better way to do this modifyPayload.deriveProperties(request, type, message.payload); if (!request.types[type]) { request.types[type] = []; // TODO: hack, find better way to do this modifyPayload.setupIndex(request, type, message.payload); } request.types[type].push(message.id); }); // run through the registered providers _.forEach(_strategies, function(action) { action(request, message) || didUpdate; }); didUpdate = true; } }); return didUpdate; }, getContentTypeCategory: getContentTypeCategory }; // TODO: Need to come up with a better self registration process (function() { var registerStrategy = module.exports.registerStrategy; // NOTE: Removing for the time being... doesn't looks like this will be needed // TODO: Check if this can be removed registerStrategy(require('./request-converter-strategy-tab___TEMP')); registerStrategy(require('./request-converter-strategy-tab-message___TEMP')); })();
const localResolve = require('@haensl/rollup-plugin-local-resolve'); module.exports = { input: './index.js', output: { file: 'build/test-app.cjs.js', format: 'cjs', name: 'test-app', indent: false }, plugins: [ localResolve() ] };
import { layout as templateLayout, tagName } from '@ember-decorators/component'; import { computed } from '@ember/object'; import Component from '@ember/component'; import ComponentChild from 'ember-bootstrap/mixins/component-child'; import layout from 'ember-bootstrap/templates/components/bs-carousel/slide'; import { next } from '@ember/runloop'; import overrideableCP from 'ember-bootstrap/utils/cp/overrideable'; import { addObserver } from '@ember/object/observers'; import deprecateSubclassing from 'ember-bootstrap/utils/deprecate-subclassing'; /** A visible user-defined slide. See [Components.Carousel](Components.Carousel.html) for examples. @class CarouselSlide @namespace Components @extends Ember.Component @public */ @tagName('') @deprecateSubclassing @templateLayout(layout) export default class CarouselSlide extends Component.extend(ComponentChild) { /** * Defines slide visibility. * * @property active * @type boolean * @private */ @overrideableCP('isCurrentSlide', 'presentationState', function () { return this.isCurrentSlide && this.presentationState === null; }) active; /** * @private * @property isCurrentSlide * @type boolean */ @(computed('currentSlide').readOnly()) get isCurrentSlide() { return this.currentSlide === this; } /** * @private * @property isFollowingSlide * @type boolean */ @(computed('followingSlide').readOnly()) get isFollowingSlide() { return this.followingSlide === this; } /** * Slide is moving to the left. * * @property left * @type boolean * @private */ left = false; /** * Next to appear in a left sliding. * * @property next * @type boolean * @private */ next = false; /** * Next to appear in a right sliding. * * @property prev * @type boolean * @private */ prev = false; /** * Slide is moving to the right. * * @property right * @type boolean * @private */ right = false; /** * Coordinates the execution of a presentation. * * @method presentationStateObserver * @private */ presentationStateObserver() { let presentationState = this.presentationState; if (this.isCurrentSlide) { switch (presentationState) { case 'didTransition': this.currentSlideDidTransition(); break; case 'willTransit': this.currentSlideWillTransit(); break; } } if (this.isFollowingSlide) { switch (presentationState) { case 'didTransition': this.followingSlideDidTransition(); break; case 'willTransit': this.followingSlideWillTransit(); break; } } } init() { super.init(...arguments); addObserver(this, 'presentationState', null, this.presentationStateObserver, true); } /** * @method currentSlideDidTransition * @private */ currentSlideDidTransition() { this.set(this.directionalClassName, false); this.set('active', false); } /** * @method currentSlideWillTransit * @private */ currentSlideWillTransit() { this.set('active', true); next(this, function () { this.set(this.directionalClassName, true); }); } /** * @method followingSlideDidTransition * @private */ followingSlideDidTransition() { this.set('active', true); this.set(this.directionalClassName, false); this.set(this.orderClassName, false); } /** * @method followingSlideWillTransit * @private */ followingSlideWillTransit() { this.set(this.orderClassName, true); next(this, function () { this.reflow(); this.set(this.directionalClassName, true); }); } /** * Makes things more stable, especially when fast changing. */ reflow() { this._element.offsetHeight; } }
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Evaluate the Kronecker delta. * * @module @stdlib/math/base/special/kronecker-delta * * @example * var kroneckerDelta = require( '@stdlib/math/base/special/kronecker-delta' ); * * var v = kroneckerDelta( 3.14, 3.14 ); * // returns 1.0 * * v = kroneckerDelta( 3.14, 0.0 ); * // returns 0.0 * * v = kroneckerDelta( NaN, 3.14 ); * // returns NaN * * v = kroneckerDelta( 3.14, NaN ); * // returns NaN * * v = kroneckerDelta( NaN, NaN ); * // returns NaN */ // MODULES // var kroneckerDelta = require( './kronecker_delta.js' ); // EXPORTS // module.exports = kroneckerDelta;
export const ADD_ALL_GENRES = 'ADD_ALL_GENRES'; export const ADD_RESULTS = 'ADD_RESULTS'; export const TOGGLE_FAVORITE = 'TOGGLE_FAVORITE'; export const ADD_DETAILS_ID = 'ADD_DETAILS_ID'; export const UPDATE = 'UPDATE'; export const RESET_FILTERS = 'RESET_FILTERS'; export const RESET_OPTIONS = 'RESET_OPTIONS'; export const CHANGE_CARD_NUM = 'CHANGE_CARD_NUM'; export const ADD_QUERY = 'ADD_QUERY'; export const ADD_URL_DATA = 'ADD_URL_DATA'; export const ADD_MOVIE_DATA = 'ADD_MOVIE_DATA'; export const ADD_STATUS_DATA = 'ADD_STATUS_DATA'; export const CHANGE_UI_PAGE = 'CHANGE_UI_PAGE';
const express = require("express"); const mongoose = require("mongoose"); const port = process.env.PORT || 5000; const app = express(); mongoose.connect( "mongodb+srv://BlogUser:jAVhPqR9YORwjwXW@cluster0-fc8do.gcp.mongodb.net/BlogDB?retryWrites=true&w=majority", { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true, } ); const connection = mongoose.connection; connection.once("open", () => { console.log("MongoDb connected"); }); //middleware app.use("/uploads", express.static("uploads")); app.use(express.json()); const userRoute = require("./routes/user"); app.use("/user", userRoute); const profileRoute = require("./routes/profile"); app.use("/profile", profileRoute); const blogRoute = require("./routes/blogpost"); app.use("/blogPost", blogRoute); data = { msg: "Welcome on DevStack Blog App development YouTube video series", info: "This is a root endpoint", Working: "Documentations of other endpoints will be release soon :)", request: "Hey if you did'nt subscribed my YouTube channle please subscribe it", }; app.route("/").get((req, res) => res.json(data)); app.listen(port, "0.0.0.0", () => console.log(`welcome your listinnig at port ${port}`) );
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..compat import compat_urlparse from ..utils import ( int_or_none, js_to_json, parse_duration, ) class NTVDeIE(InfoExtractor): IE_NAME = 'n-tv.de' _VALID_URL = r'https?://(?:www\.)?n-tv\.de/mediathek/videos/[^/?#]+/[^/?#]+-article(?P<id>.+)\.html' _TESTS = [{ 'url': 'http://www.n-tv.de/mediathek/videos/panorama/Schnee-und-Glaette-fuehren-zu-zahlreichen-Unfaellen-und-Staus-article14438086.html', 'md5': '6ef2514d4b1e8e03ca24b49e2f167153', 'info_dict': { 'id': '14438086', 'ext': 'mp4', 'thumbnail': 're:^https?://.*\.jpg$', 'title': 'Schnee und Glätte führen zu zahlreichen Unfällen und Staus', 'alt_title': 'Winterchaos auf deutschen Straßen', 'description': 'Schnee und Glätte sorgen deutschlandweit für einen chaotischen Start in die Woche: Auf den Straßen kommt es zu kilometerlangen Staus und Dutzenden Glätteunfällen. In Düsseldorf und München wirbelt der Schnee zudem den Flugplan durcheinander. Dutzende Flüge landen zu spät, einige fallen ganz aus.', 'duration': 4020, 'timestamp': 1422892797, 'upload_date': '20150202', }, }] def _real_extract(self, url): video_id = self._match_id(url) webpage = self._download_webpage(url, video_id) info = self._parse_json(self._search_regex( r'(?s)ntv\.pageInfo\.article\s*=\s*(\{.*?\});', webpage, 'info'), video_id, transform_source=js_to_json) timestamp = int_or_none(info.get('publishedDateAsUnixTimeStamp')) vdata = self._parse_json(self._search_regex( r'(?s)\$\(\s*"\#player"\s*\)\s*\.data\(\s*"player",\s*(\{.*?\})\);', webpage, 'player data'), video_id, transform_source=lambda s: js_to_json(re.sub(r'advertising:\s*{[^}]+},', '', s))) duration = parse_duration(vdata.get('duration')) formats = [] if vdata.get('video'): formats.append({ 'format_id': 'flash', 'url': 'rtmp://fms.n-tv.de/%s' % vdata['video'], }) if vdata.get('videoMp4'): formats.append({ 'format_id': 'mobile', 'url': compat_urlparse.urljoin('http://video.n-tv.de', vdata['videoMp4']), 'tbr': 400, # estimation }) if vdata.get('videoM3u8'): m3u8_url = compat_urlparse.urljoin('http://video.n-tv.de', vdata['videoM3u8']) formats.extend(self._extract_m3u8_formats( m3u8_url, video_id, ext='mp4', entry_protocol='m3u8_native', preference=0, m3u8_id='hls', fatal=False)) self._sort_formats(formats) return { 'id': video_id, 'title': info['headline'], 'description': info.get('intro'), 'alt_title': info.get('kicker'), 'timestamp': timestamp, 'thumbnail': vdata.get('html5VideoPoster'), 'duration': duration, 'formats': formats, }
import Vue from 'vue' import App from './App.vue' import router from './router' Vue.config.productionTip = false Vue.config.devtools = true new Vue({ store, router, render: h => h(App), }).$mount('#app')
const express = require('express') const cors = require('cors') const bodyParser = require('body-parser') const morgan = require('morgan') require('dotenv').config() const { screenResponse, apiCallResponse, navigate, apiCall, copyToClipboard, showToast, Screen, Text, Button, Image } = require('@chatium/json') const { getChatiumContext, triggerHotReload } = require('@chatium/sdk') const app = express() app.use(cors()) app.use(bodyParser.urlencoded({ extended: false })) app.use(bodyParser.json()) app.use(morgan('combined')) app.get('/', async (req, res) => res.json( screenResponse({ data: await Screen({ title: 'Node Template' }, [ Text({ text: 'Template for developing custom Chatium backends using NodeJS' }), Image({ downloadUrl: 'https://chatium.com/chatium.png' }), Button({ title: 'Show request info', onClick: navigate('/request') }), Button({ title: 'Toast random number 100 ... 500', onClick: apiCall('/random', { min: 100, max: 500 }) }), ])}) )) app.get('/request', async (req, res) => { try { const ctx = getContext(req) return res.json( screenResponse({ data: await Screen({ title: 'Request info' }, [ Text({ text: 'Account Id' }), Button({ title: ctx.account.id, onClick: copyToClipboard(ctx.account.id), buttonType: 'flat' }), Text({ text: 'Account Host' }), Button({ title: ctx.account.host, onClick: copyToClipboard(ctx.account.host), buttonType: 'flat' }), Text({ text: 'Auth' }), Button({ title: ctx.auth.id, onClick: copyToClipboard(ctx.auth.id), buttonType: 'flat' }), Button({ title: 'Main page', onClick: navigate('/') }), ])}) ) } catch (e) { return res.json( screenResponse({ data: await Screen({ title: 'Request info' }, [ Text({ text: 'Sign error' }), Button({ title: 'Main page', onClick: navigate('/') }), ])}) ) } }) app.post('/random', async (req, res) => { const number = req.body.min + Math.round(Math.random() * (req.body.max - req.body.min)) res.json( apiCallResponse({ appAction: showToast(number) }) ) }) console.log(``) console.log(`Application started:`) const port = process.env.PORT || 5050 app.listen(port, '0.0.0.0', () => { console.log(`Listening at port :${port}`) if (process.env.API_KEY && process.env.API_SECRET) { triggerHotReload(appCtx).catch(err => console.log('triggerHotReload error:', err)); } }) console.log(``) console.log(` APP_ENDPOINT = ${process.env.APP_ENDPOINT ? process.env.APP_ENDPOINT : 'undefined (setup .env file)'}`) console.log(` API_KEY = ${process.env.API_KEY ? process.env.API_KEY : 'undefined (setup .env file)'}`) console.log(` API_SECRET = ${process.env.API_SECRET ? process.env.API_SECRET.slice(0, 10) + 'xXxXxXxXxXxXxXxXxXxXxX' : 'undefined (setup .env file)'}`) console.log(``) const appCtx = { app: { apiKey: process.env.API_KEY, apiSecret: process.env.API_SECRET, } } function getContext(req) { return getChatiumContext(appCtx, req.headers) }
// Copyright 2018 Twitter, Inc. // Licensed under the Apache License, Version 2.0 // http://www.apache.org/licenses/LICENSE-2.0 function show(type) { count = 0; for (var key in methods) { var row = document.getElementById(key); if ((methods[key] & type) != 0) { row.style.display = ''; row.className = (count++ % 2) ? rowColor : altColor; } else row.style.display = 'none'; } updateTabs(type); } function updateTabs(type) { for (var value in tabs) { var sNode = document.getElementById(tabs[value][0]); var spanNode = sNode.firstChild; if (value == type) { sNode.className = activeTableTab; spanNode.innerHTML = tabs[value][1]; } else { sNode.className = tableTab; spanNode.innerHTML = "<a href=\"javascript:show("+ value + ");\">" + tabs[value][1] + "</a>"; } } }
# problem 27 # Project Euler import math __author__ = 'Libao Jin' __date__ = 'July 18, 2015' def isPrime(n): if n < 0: return None if n == 1: return None elif n > 1 and n <= 3: return True UPPER_BOUND = math.sqrt(n) i = 2 while i <= UPPER_BOUND: if n % i != 0: i += 1 else: return False return True def quadraticPrimes(a,b): qPrimes = [] n = 0 number = n ** 2 + a * n + b while isPrime(number): qPrimes.append((n, number)) n += 1 number = n ** 2 + a * n + b return ((a,b), len(qPrimes), qPrimes) def bruteForce(BOUND_a, BOUND_b): aSeries = range(-BOUND_a, BOUND_a+1) bSeries = range(-BOUND_b, BOUND_b+1) currentMAX = -1 MAX = None for a in aSeries: for b in bSeries: qPrimesInfo = quadraticPrimes(a,b) if qPrimesInfo[1] > currentMAX: currentMAX = qPrimesInfo[1] MAX = qPrimesInfo return MAX def solution(): MAX = bruteForce(1000, 1000) maxProduct = MAX[0][0] * MAX[0][1] print(MAX, maxProduct) def test(): for i in range(1,100): print('{0:d}:'.format(i), isPrime(i)) solution()
var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; import React from 'react'; import styled from 'styled-components'; export var Functions = styled.svg.attrs({ children: function (props) { return (props.title != null ? [React.createElement("title", { key: "Functions-title" }, props.title), React.createElement("path", { d: "M18 4H6v2l6.5 6L6 18v2h12v-3h-7l5-5-5-5h7z", key: "k0" }) ] : [React.createElement("path", { d: "M18 4H6v2l6.5 6L6 18v2h12v-3h-7l5-5-5-5h7z", key: "k0" }) ]); }, viewBox: '0 0 24 24', height: function (props) { return (props.height !== undefined ? props.height : props.size); }, width: function (props) { return (props.width !== undefined ? props.width : props.size); }, // @ts-ignore - aria is not always defined on SVG in React TypeScript types 'aria-hidden': function (props) { return (props.title == null ? 'true' : undefined); }, focusable: 'false', role: function (props) { return (props.title != null ? 'img' : undefined); }, "fill": "currentColor", })(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n display: inline-block;\n vertical-align: middle;\n overflow: hidden;\n"], ["\n display: inline-block;\n vertical-align: middle;\n overflow: hidden;\n"]))); Functions.displayName = 'Functions'; export var FunctionsDimensions = { height: 24, width: 24 }; var templateObject_1;
(function() { 'use strict'; angular .module('uniConnectApp') .config(stateConfig); stateConfig.$inject = ['$stateProvider']; function stateConfig($stateProvider) { $stateProvider.state('jhi-health', { parent: 'admin', url: '/health', data: { authorities: ['ROLE_ADMIN'], pageTitle: 'Health Checks' }, views: { 'content@': { templateUrl: 'app/admin/health/health.html', controller: 'JhiHealthCheckController', controllerAs: 'vm' } } }); } })();
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var key = require('interface-datastore/key'); var libp2pRecord = require('libp2p-record'); var errCode = require('err-code'); var debug = require('debug'); var toString = require('uint8arrays/to-string'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var errCode__default = /*#__PURE__*/_interopDefaultLegacy(errCode); var debug__default = /*#__PURE__*/_interopDefaultLegacy(debug); const log = Object.assign(debug__default["default"]('ipfs:ipns:offline-datastore'), { error: debug__default["default"]('ipfs:ipns:offline-datastore:error') }); class OfflineDatastore { constructor(repo) { this._repo = repo; this.stores = []; } async put(key, value) { if (!(key instanceof Uint8Array)) { throw errCode__default["default"](new Error('Offline datastore key must be a Uint8Array'), 'ERR_INVALID_KEY'); } if (!(value instanceof Uint8Array)) { throw errCode__default["default"](new Error('Offline datastore value must be a Uint8Array'), 'ERR_INVALID_VALUE'); } let routingKey; try { routingKey = this._routingKey(key); } catch (err) { log.error(err); throw errCode__default["default"](new Error('Not possible to generate the routing key'), 'ERR_GENERATING_ROUTING_KEY'); } const record = new libp2pRecord.Record(key, value); return this._repo.datastore.put(routingKey, record.serialize()); } async get(key) { if (!(key instanceof Uint8Array)) { throw errCode__default["default"](new Error('Offline datastore key must be a Uint8Array'), 'ERR_INVALID_KEY'); } let routingKey; try { routingKey = this._routingKey(key); } catch (err) { log.error(err); throw errCode__default["default"](new Error('Not possible to generate the routing key'), 'ERR_GENERATING_ROUTING_KEY'); } const res = await this._repo.datastore.get(routingKey); let record; try { record = libp2pRecord.Record.deserialize(res); } catch (err) { log.error(err); throw err; } return record.value; } _routingKey(key$1) { return new key.Key('/dht/record/' + toString.toString(key$1, 'base32'), false); } } exports.OfflineDatastore = OfflineDatastore;
;if (!check) var check={}; check.html5 = html5(); /** * 检测是否支持html5 * @return {[type]} [description] */ function html5() { var rs = false; return rs; //if (typeof(Worker) !== "undefined") // rs = true; //return rs; } jQuery(document).ready(function(){ var strPath=window.document.location.pathname; var postPath=strPath.substring(1,strPath.substr(1).indexOf('/')+1); if (!!check.html5) { $("#archivesCemeteryFile").uploadifive({ 'fileObjName' : 'archivesCemeteryFile', 'buttonText' : '选择', 'buttonClass' : 'touxiang-images', 'width' : 10, 'height' : 10, 'fileSizeLimit' : '2MB', 'fileType' : 'image', 'itemTemplate' : '<div class="uploadifive-queue-item" style="display: none;"></div>', // 'removeCompleted' : true, 'formData' : { }, 'uploadScript' : base_url + 'upload/uploadheader', 'onInit' : function() { $(".uploadifive-button").removeClass('uploadifive-button'); }, 'onUploadComplete' : function(file, data) { var d = eval('('+data+')'); if(d != ''){ var u = '/'+ postPath +"/upload/pic/"+ d[0].filePath +"?"+ Math.floor(Math.random()*9999+1000); $("#cemeteryFileId").attr("value",d[0].id); $("#cemeteryFilePic").attr("src",u); } }, 'onError' : function(errorType) { showDoctorError(errorType); } }); } else { $("#archivesCemeteryFile").uploadify({ 'width' : 60, 'height' :24, 'queueSizeLimit':5, 'buttonText':'点击上传', 'button_image_url' : '/'+ postPath +'/images/right-11.jpg', 'fileSizeLimit' : '10MB', 'fileTypeDesc' : '文件', 'fileTypeExts' : '*.gif; *.jpg; *.png; *.jpeg;*.rar;*.doc', 'itemTemplate' : '<div class="uploadifive-queue-item" style="display: none;"></div>', 'swf' : '/'+ postPath +'/jscript/uploadify/uploadify.swf', 'uploader' : '/'+ postPath +'/file/archivesCemeteryFileController.fj?method=uploadFile', 'onInit' : function() { //$(".uploadify-button").removeClass('uploadify-button'); }, 'onUploadSuccess' : function(file, data, response) { var d = eval('('+data+')'); if(d != ''){ $("#filename").append(d[0].fileName+"</br>"); document.all.fileId.value += d[0].id+","; } }, 'onUploadError' : function(file, errorCode, errorMsg, errorString) { showDoctorError(errorString); } }); } }); function showDoctorError(errorType) { var m; if ('FILE_SIZE_LIMIT_EXCEEDED' === errorType) { m = ("只能上传2M的图片"); } else if ('FORBIDDEN_FILE_TYPE' === errorType) { m = ("图片格式限定在JPG, JPEG, GIF, PNG或BMP"); } else { m = ('上传失败: ' + errorType); } alert(m); }
//Client-side Javascript code for handling random numbers $(document).ready(function(){ //connect to the socket server. var socket = io.connect('http://' + document.domain + ':' + location.port + '/test'); var numbers_received = []; //receive details from server socket.on('newnumber', function(msg) { console.log("Received number" + msg.number); //maintain a list of ten numbers if (numbers_received.length >= 10){ numbers_received.shift() } numbers_received.push(msg.number); numbers_string = ''; for (var i = 0; i < numbers_received.length; i++){ numbers_string = numbers_string + '<p>' + numbers_received[i].toString() + '</p>'; } $('#log').html(numbers_string); }); });
import React from 'react'; import ProfileHeader from './ProfileHeader/ProfileHeader' import ProfileContactInfo from './ProfileContactInfo/ProfileContactInfo' import ProfileSocialLinks from './ProfileSocialLinks/ProfileSocialLinks' import ProfileResumeFormatLinks from './ProfileResumeFormatLinks/ProfileResumeFormatLinks' import './ProfileCard.css' export default function ProfileCard({ name, label, image, location, phone, email, languages, social, formats }) { return ( <section className="card-wrapper profile-card-wrapper"> <div className="card profile-card"> <ProfileHeader name={name} label={label} imageUrl={image}/> <hr /> <div className="profile-info-container"> <ProfileContactInfo location={location} phone={phone} email={email} languages={languages} /> <div className="spacer"></div> <ProfileSocialLinks profiles={social}/> <div className="spacer"></div> <ProfileResumeFormatLinks formats={formats}></ProfileResumeFormatLinks> </div> </div> </section> ) }
#!/usr/bin/env python2 # Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################## """Perform inference on a single image or all images with a certain extension (e.g., .jpg) in a folder. Allows for using a combination of multiple models. For example, one model may be used for RPN, another model for Fast R-CNN style box detection, yet another model to predict masks, and yet another model to predict keypoints. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import cv2 # NOQA (Must import before importing caffe2 due to bug in cv2) import logging import os import sys import yaml from caffe2.python import workspace from core.config import assert_and_infer_cfg from core.config import cfg from core.config import merge_cfg_from_cfg from core.config import merge_cfg_from_file from utils.io import cache_url import core.rpn_generator as rpn_engine import core.test_engine as model_engine import datasets.dummy_datasets as dummy_datasets import utils.c2 as c2_utils import utils.logging import utils.vis as vis_utils c2_utils.import_detectron_ops() # OpenCL may be enabled by default in OpenCV3; disable it because it's not # thread safe and causes unwanted GPU memory allocations. cv2.ocl.setUseOpenCL(False) # infer.py # --im [path/to/image.jpg] # --rpn-model [path/to/rpn/model.pkl] # --rpn-config [path/to/rpn/config.yaml] # [model1] [config1] [model2] [config2] ... def parse_args(): parser = argparse.ArgumentParser(description='Inference on an image') parser.add_argument( '--im', dest='im_file', help='input image', default=None, type=str ) parser.add_argument( '--rpn-pkl', dest='rpn_pkl', help='rpn model file (pkl)', default=None, type=str ) parser.add_argument( '--rpn-cfg', dest='rpn_cfg', help='cfg model file (yaml)', default=None, type=str ) parser.add_argument( '--output-dir', dest='output_dir', help='directory for visualization pdfs (default: /tmp/infer)', default='/tmp/infer', type=str ) parser.add_argument( 'models_to_run', help='list of pkl, yaml pairs', default=None, nargs=argparse.REMAINDER ) parser.add_argument( '--use-vg3k', dest='use_vg3k', help='use Visual Genome 3k classes (instead of COCO 80 classes)', action='store_true' ) parser.add_argument( '--thresh', default=0.7, type=float, help='score threshold for predictions', ) if len(sys.argv) == 1: parser.print_help() sys.exit(1) return parser.parse_args() def get_rpn_box_proposals(im, args): cfg.immutable(False) merge_cfg_from_file(args.rpn_cfg) cfg.NUM_GPUS = 1 cfg.MODEL.RPN_ONLY = True cfg.TEST.RPN_PRE_NMS_TOP_N = 10000 cfg.TEST.RPN_POST_NMS_TOP_N = 2000 assert_and_infer_cfg(cache_urls=False) model = model_engine.initialize_model_from_cfg(args.rpn_pkl) with c2_utils.NamedCudaScope(0): boxes, scores = rpn_engine.im_proposals(model, im) return boxes, scores def main(args): logger = logging.getLogger(__name__) dummy_coco_dataset = ( dummy_datasets.get_vg3k_dataset() if args.use_vg3k else dummy_datasets.get_coco_dataset()) cfg_orig = yaml.load(yaml.dump(cfg)) im = cv2.imread(args.im_file) if args.rpn_pkl is not None: proposal_boxes, _proposal_scores = get_rpn_box_proposals(im, args) workspace.ResetWorkspace() else: proposal_boxes = None cls_boxes, cls_segms, cls_keyps = None, None, None for i in range(0, len(args.models_to_run), 2): pkl = args.models_to_run[i] yml = args.models_to_run[i + 1] cfg.immutable(False) merge_cfg_from_cfg(cfg_orig) merge_cfg_from_file(yml) if len(pkl) > 0: weights_file = pkl else: weights_file = cfg.TEST.WEIGHTS cfg.NUM_GPUS = 1 assert_and_infer_cfg(cache_urls=False) model = model_engine.initialize_model_from_cfg(weights_file) with c2_utils.NamedCudaScope(0): cls_boxes_, cls_segms_, cls_keyps_ = \ model_engine.im_detect_all(model, im, proposal_boxes) cls_boxes = cls_boxes_ if cls_boxes_ is not None else cls_boxes cls_segms = cls_segms_ if cls_segms_ is not None else cls_segms cls_keyps = cls_keyps_ if cls_keyps_ is not None else cls_keyps workspace.ResetWorkspace() out_name = os.path.join( args.output_dir, '{}'.format(os.path.basename(args.im_file) + '.pdf') ) logger.info('Processing {} -> {}'.format(args.im_file, out_name)) vis_utils.vis_one_image( im[:, :, ::-1], args.im_file, args.output_dir, cls_boxes, cls_segms, cls_keyps, dataset=dummy_coco_dataset, box_alpha=0.3, show_class=True, thresh=args.thresh, kp_thresh=2 ) def check_args(args): assert ( (args.rpn_pkl is not None and args.rpn_cfg is not None) or (args.rpn_pkl is None and args.rpn_cfg is None) ) if args.rpn_pkl is not None: args.rpn_pkl = cache_url(args.rpn_pkl, cfg.DOWNLOAD_CACHE) assert os.path.exists(args.rpn_pkl) assert os.path.exists(args.rpn_cfg) if args.models_to_run is not None: assert len(args.models_to_run) % 2 == 0 for i, model_file in enumerate(args.models_to_run): if len(model_file) > 0: if i % 2 == 0: model_file = cache_url(model_file, cfg.DOWNLOAD_CACHE) args.models_to_run[i] = model_file assert os.path.exists(model_file), \ '\'{}\' does not exist'.format(model_file) if __name__ == '__main__': workspace.GlobalInit(['caffe2', '--caffe2_log_level=0']) utils.logging.setup_logging(__name__) args = parse_args() check_args(args) main(args)
# Copyright 2019 The TensorFlow 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. # ============================================================================== """BERT library to process data for classification task.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import csv import importlib import os from absl import logging import tensorflow as tf import tensorflow_datasets as tfds from official.nlp.bert import tokenization class InputExample(object): """A single training/test example for simple sequence classification.""" def __init__(self, guid, text_a, text_b=None, label=None): """Constructs a InputExample. Args: guid: Unique id for the example. text_a: string. The untokenized text of the first sequence. For single sequence tasks, only this sequence must be specified. text_b: (Optional) string. The untokenized text of the second sequence. Only must be specified for sequence pair tasks. label: (Optional) string. The label of the example. This should be specified for train and dev examples, but not for test examples. """ self.guid = guid self.text_a = text_a self.text_b = text_b self.label = label class InputFeatures(object): """A single set of features of data.""" def __init__(self, input_ids, input_mask, segment_ids, label_id, is_real_example=True): self.input_ids = input_ids self.input_mask = input_mask self.segment_ids = segment_ids self.label_id = label_id self.is_real_example = is_real_example class DataProcessor(object): """Base class for data converters for sequence classification data sets.""" def __init__(self, process_text_fn=tokenization.convert_to_unicode): self.process_text_fn = process_text_fn def get_train_examples(self, data_dir): """Gets a collection of `InputExample`s for the train set.""" raise NotImplementedError() def get_dev_examples(self, data_dir): """Gets a collection of `InputExample`s for the dev set.""" raise NotImplementedError() def get_test_examples(self, data_dir): """Gets a collection of `InputExample`s for prediction.""" raise NotImplementedError() def get_labels(self): """Gets the list of labels for this data set.""" raise NotImplementedError() @staticmethod def get_processor_name(): """Gets the string identifier of the processor.""" raise NotImplementedError() @classmethod def _read_tsv(cls, input_file, quotechar=None): """Reads a tab separated value file.""" with tf.io.gfile.GFile(input_file, "r") as f: reader = csv.reader(f, delimiter="\t", quotechar=quotechar) lines = [] for line in reader: lines.append(line) return lines class XnliProcessor(DataProcessor): """Processor for the XNLI data set.""" supported_languages = [ "ar", "bg", "de", "el", "en", "es", "fr", "hi", "ru", "sw", "th", "tr", "ur", "vi", "zh" ] def __init__(self, language="en", process_text_fn=tokenization.convert_to_unicode): super(XnliProcessor, self).__init__(process_text_fn) if language == "all": self.languages = XnliProcessor.supported_languages elif language not in XnliProcessor.supported_languages: raise ValueError("language %s is not supported for XNLI task." % language) else: self.languages = [language] def get_train_examples(self, data_dir): """See base class.""" lines = [] for language in self.languages: lines.extend( self._read_tsv( os.path.join(data_dir, "multinli", "multinli.train.%s.tsv" % language))) examples = [] for (i, line) in enumerate(lines): if i == 0: continue guid = "train-%d" % i text_a = self.process_text_fn(line[0]) text_b = self.process_text_fn(line[1]) label = self.process_text_fn(line[2]) if label == self.process_text_fn("contradictory"): label = self.process_text_fn("contradiction") examples.append( InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) return examples def get_dev_examples(self, data_dir): """See base class.""" lines = self._read_tsv(os.path.join(data_dir, "xnli.dev.tsv")) examples = [] for (i, line) in enumerate(lines): if i == 0: continue guid = "dev-%d" % i text_a = self.process_text_fn(line[6]) text_b = self.process_text_fn(line[7]) label = self.process_text_fn(line[1]) examples.append( InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) return examples def get_test_examples(self, data_dir): """See base class.""" lines = self._read_tsv(os.path.join(data_dir, "xnli.test.tsv")) examples_by_lang = {k: [] for k in XnliProcessor.supported_languages} for (i, line) in enumerate(lines): if i == 0: continue guid = "test-%d" % i language = self.process_text_fn(line[0]) text_a = self.process_text_fn(line[6]) text_b = self.process_text_fn(line[7]) label = self.process_text_fn(line[1]) examples_by_lang[language].append( InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) return examples_by_lang def get_labels(self): """See base class.""" return ["contradiction", "entailment", "neutral"] @staticmethod def get_processor_name(): """See base class.""" return "XNLI" class PawsxProcessor(DataProcessor): """Processor for the PAWS-X data set.""" supported_languages = [ "de", "en", "es", "fr", "ja", "ko", "zh" ] def __init__(self, language="en", process_text_fn=tokenization.convert_to_unicode): super(PawsxProcessor, self).__init__(process_text_fn) if language == "all": self.languages = PawsxProcessor.supported_languages elif language not in PawsxProcessor.supported_languages: raise ValueError("language %s is not supported for PAWS-X task." % language) else: self.languages = [language] def get_train_examples(self, data_dir): """See base class.""" lines = [] for language in self.languages: if language == "en": train_tsv = "train.tsv" else: train_tsv = "translated_train.tsv" # Skips the header. lines.extend( self._read_tsv( os.path.join(data_dir, language, train_tsv))[1:]) examples = [] for (i, line) in enumerate(lines): guid = "train-%d" % i text_a = self.process_text_fn(line[1]) text_b = self.process_text_fn(line[2]) label = self.process_text_fn(line[3]) examples.append( InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) return examples def get_dev_examples(self, data_dir): """See base class.""" lines = [] for language in PawsxProcessor.supported_languages: # Skips the header. lines.extend( self._read_tsv(os.path.join(data_dir, language, "dev_2k.tsv"))[1:]) examples = [] for (i, line) in enumerate(lines): guid = "dev-%d" % i text_a = self.process_text_fn(line[1]) text_b = self.process_text_fn(line[2]) label = self.process_text_fn(line[3]) examples.append( InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) return examples def get_test_examples(self, data_dir): """See base class.""" examples_by_lang = {k: [] for k in PawsxProcessor.supported_languages} for language in PawsxProcessor.supported_languages: lines = self._read_tsv(os.path.join(data_dir, language, "test_2k.tsv")) for (i, line) in enumerate(lines): if i == 0: continue guid = "test-%d" % i text_a = self.process_text_fn(line[1]) text_b = self.process_text_fn(line[2]) label = self.process_text_fn(line[3]) examples_by_lang[language].append( InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) return examples_by_lang def get_labels(self): """See base class.""" return ["0", "1"] @staticmethod def get_processor_name(): """See base class.""" return "PAWS-X" class MnliProcessor(DataProcessor): """Processor for the MultiNLI data set (GLUE version).""" def get_train_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") def get_dev_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "dev_matched.tsv")), "dev_matched") def get_test_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "test_matched.tsv")), "test") def get_labels(self): """See base class.""" return ["contradiction", "entailment", "neutral"] @staticmethod def get_processor_name(): """See base class.""" return "MNLI" def _create_examples(self, lines, set_type): """Creates examples for the training and dev sets.""" examples = [] for (i, line) in enumerate(lines): if i == 0: continue guid = "%s-%s" % (set_type, self.process_text_fn(line[0])) text_a = self.process_text_fn(line[8]) text_b = self.process_text_fn(line[9]) if set_type == "test": label = "contradiction" else: label = self.process_text_fn(line[-1]) examples.append( InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) return examples class MrpcProcessor(DataProcessor): """Processor for the MRPC data set (GLUE version).""" def get_train_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") def get_dev_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") def get_test_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") def get_labels(self): """See base class.""" return ["0", "1"] @staticmethod def get_processor_name(): """See base class.""" return "MRPC" def _create_examples(self, lines, set_type): """Creates examples for the training and dev sets.""" examples = [] for (i, line) in enumerate(lines): if i == 0: continue guid = "%s-%s" % (set_type, i) text_a = self.process_text_fn(line[3]) text_b = self.process_text_fn(line[4]) if set_type == "test": label = "0" else: label = self.process_text_fn(line[0]) examples.append( InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) return examples class QqpProcessor(DataProcessor): """Processor for the QQP data set (GLUE version).""" def get_train_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") def get_dev_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") def get_test_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") def get_labels(self): """See base class.""" return ["0", "1"] @staticmethod def get_processor_name(): """See base class.""" return "QQP" def _create_examples(self, lines, set_type): """Creates examples for the training and dev sets.""" examples = [] for (i, line) in enumerate(lines): if i == 0: continue guid = "%s-%s" % (set_type, line[0]) try: text_a = line[3] text_b = line[4] label = line[5] except IndexError: continue examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) return examples class ColaProcessor(DataProcessor): """Processor for the CoLA data set (GLUE version).""" def get_train_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") def get_dev_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") def get_test_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") def get_labels(self): """See base class.""" return ["0", "1"] @staticmethod def get_processor_name(): """See base class.""" return "COLA" def _create_examples(self, lines, set_type): """Creates examples for the training and dev sets.""" examples = [] for (i, line) in enumerate(lines): # Only the test set has a header if set_type == "test" and i == 0: continue guid = "%s-%s" % (set_type, i) if set_type == "test": text_a = self.process_text_fn(line[1]) label = "0" else: text_a = self.process_text_fn(line[3]) label = self.process_text_fn(line[1]) examples.append( InputExample(guid=guid, text_a=text_a, text_b=None, label=label)) return examples class SstProcessor(DataProcessor): """Processor for the SST-2 data set (GLUE version).""" def get_train_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") def get_dev_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") def get_test_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") def get_labels(self): """See base class.""" return ["0", "1"] @staticmethod def get_processor_name(): """See base class.""" return "SST-2" def _create_examples(self, lines, set_type): """Creates examples for the training and dev sets.""" examples = [] for (i, line) in enumerate(lines): if i == 0: continue guid = "%s-%s" % (set_type, i) if set_type == "test": text_a = tokenization.convert_to_unicode(line[1]) label = "0" else: text_a = tokenization.convert_to_unicode(line[0]) label = tokenization.convert_to_unicode(line[1]) examples.append( InputExample(guid=guid, text_a=text_a, text_b=None, label=label)) return examples class QnliProcessor(DataProcessor): """Processor for the QNLI data set (GLUE version).""" def get_train_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") def get_dev_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev_matched") def get_test_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") def get_labels(self): """See base class.""" return ["entailment", "not_entailment"] @staticmethod def get_processor_name(): """See base class.""" return "QNLI" def _create_examples(self, lines, set_type): """Creates examples for the training and dev sets.""" examples = [] for (i, line) in enumerate(lines): if i == 0: continue guid = "%s-%s" % (set_type, 1) if set_type == "test": text_a = tokenization.convert_to_unicode(line[1]) text_b = tokenization.convert_to_unicode(line[2]) label = "entailment" else: text_a = tokenization.convert_to_unicode(line[1]) text_b = tokenization.convert_to_unicode(line[2]) label = tokenization.convert_to_unicode(line[-1]) examples.append( InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) return examples class TfdsProcessor(DataProcessor): """Processor for generic text classification and regression TFDS data set. The TFDS parameters are expected to be provided in the tfds_params string, in a comma-separated list of parameter assignments. Examples: tfds_params="dataset=scicite,text_key=string" tfds_params="dataset=imdb_reviews,test_split=,dev_split=test" tfds_params="dataset=glue/cola,text_key=sentence" tfds_params="dataset=glue/sst2,text_key=sentence" tfds_params="dataset=glue/qnli,text_key=question,text_b_key=sentence" tfds_params="dataset=glue/mrpc,text_key=sentence1,text_b_key=sentence2" tfds_params="dataset=glue/stsb,text_key=sentence1,text_b_key=sentence2," "is_regression=true,label_type=float" Possible parameters (please refer to the documentation of Tensorflow Datasets (TFDS) for the meaning of individual parameters): dataset: Required dataset name (potentially with subset and version number). data_dir: Optional TFDS source root directory. module_import: Optional Dataset module to import. train_split: Name of the train split (defaults to `train`). dev_split: Name of the dev split (defaults to `validation`). test_split: Name of the test split (defaults to `test`). text_key: Key of the text_a feature (defaults to `text`). text_b_key: Key of the second text feature if available. label_key: Key of the label feature (defaults to `label`). test_text_key: Key of the text feature to use in test set. test_text_b_key: Key of the second text feature to use in test set. test_label: String to be used as the label for all test examples. label_type: Type of the label key (defaults to `int`). is_regression: Whether the task is a regression problem (defaults to False). """ def __init__(self, tfds_params, process_text_fn=tokenization.convert_to_unicode): super(TfdsProcessor, self).__init__(process_text_fn) self._process_tfds_params_str(tfds_params) if self.module_import: importlib.import_module(self.module_import) self.dataset, info = tfds.load(self.dataset_name, data_dir=self.data_dir, with_info=True) if self.is_regression: self._labels = None else: self._labels = list(range(info.features[self.label_key].num_classes)) def _process_tfds_params_str(self, params_str): """Extracts TFDS parameters from a comma-separated assignements string.""" dtype_map = {"int": int, "float": float} cast_str_to_bool = lambda s: s.lower() not in ["false", "0"] tuples = [x.split("=") for x in params_str.split(",")] d = {k.strip(): v.strip() for k, v in tuples} self.dataset_name = d["dataset"] # Required. self.data_dir = d.get("data_dir", None) self.module_import = d.get("module_import", None) self.train_split = d.get("train_split", "train") self.dev_split = d.get("dev_split", "validation") self.test_split = d.get("test_split", "test") self.text_key = d.get("text_key", "text") self.text_b_key = d.get("text_b_key", None) self.label_key = d.get("label_key", "label") self.test_text_key = d.get("test_text_key", self.text_key) self.test_text_b_key = d.get("test_text_b_key", self.text_b_key) self.test_label = d.get("test_label", "test_example") self.label_type = dtype_map[d.get("label_type", "int")] self.is_regression = cast_str_to_bool(d.get("is_regression", "False")) def get_train_examples(self, data_dir): assert data_dir is None return self._create_examples(self.train_split, "train") def get_dev_examples(self, data_dir): assert data_dir is None return self._create_examples(self.dev_split, "dev") def get_test_examples(self, data_dir): assert data_dir is None return self._create_examples(self.test_split, "test") def get_labels(self): return self._labels def get_processor_name(self): return "TFDS_" + self.dataset_name def _create_examples(self, split_name, set_type): """Creates examples for the training and dev sets.""" if split_name not in self.dataset: raise ValueError("Split {} not available.".format(split_name)) dataset = self.dataset[split_name].as_numpy_iterator() examples = [] text_b = None for i, example in enumerate(dataset): guid = "%s-%s" % (set_type, i) if set_type == "test": text_a = self.process_text_fn(example[self.test_text_key]) if self.test_text_b_key: text_b = self.process_text_fn(example[self.test_text_b_key]) label = self.test_label else: text_a = self.process_text_fn(example[self.text_key]) if self.text_b_key: text_b = self.process_text_fn(example[self.text_b_key]) label = self.label_type(example[self.label_key]) examples.append( InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) return examples def convert_single_example(ex_index, example, label_list, max_seq_length, tokenizer): """Converts a single `InputExample` into a single `InputFeatures`.""" label_map = {} if label_list: for (i, label) in enumerate(label_list): label_map[label] = i tokens_a = tokenizer.tokenize(example.text_a) tokens_b = None if example.text_b: tokens_b = tokenizer.tokenize(example.text_b) if tokens_b: # Modifies `tokens_a` and `tokens_b` in place so that the total # length is less than the specified length. # Account for [CLS], [SEP], [SEP] with "- 3" _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3) else: # Account for [CLS] and [SEP] with "- 2" if len(tokens_a) > max_seq_length - 2: tokens_a = tokens_a[0:(max_seq_length - 2)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens = [] segment_ids = [] tokens.append("[CLS]") segment_ids.append(0) for token in tokens_a: tokens.append(token) segment_ids.append(0) tokens.append("[SEP]") segment_ids.append(0) if tokens_b: for token in tokens_b: tokens.append(token) segment_ids.append(1) tokens.append("[SEP]") segment_ids.append(1) input_ids = tokenizer.convert_tokens_to_ids(tokens) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. input_mask = [1] * len(input_ids) # Zero-pad up to the sequence length. while len(input_ids) < max_seq_length: input_ids.append(0) input_mask.append(0) segment_ids.append(0) assert len(input_ids) == max_seq_length assert len(input_mask) == max_seq_length assert len(segment_ids) == max_seq_length label_id = label_map[example.label] if label_map else example.label if ex_index < 5: logging.info("*** Example ***") logging.info("guid: %s", (example.guid)) logging.info("tokens: %s", " ".join([tokenization.printable_text(x) for x in tokens])) logging.info("input_ids: %s", " ".join([str(x) for x in input_ids])) logging.info("input_mask: %s", " ".join([str(x) for x in input_mask])) logging.info("segment_ids: %s", " ".join([str(x) for x in segment_ids])) logging.info("label: %s (id = %d)", example.label, label_id) feature = InputFeatures( input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids, label_id=label_id, is_real_example=True) return feature def file_based_convert_examples_to_features(examples, label_list, max_seq_length, tokenizer, output_file, label_type=None): """Convert a set of `InputExample`s to a TFRecord file.""" tf.io.gfile.makedirs(os.path.dirname(output_file)) writer = tf.io.TFRecordWriter(output_file) for (ex_index, example) in enumerate(examples): if ex_index % 10000 == 0: logging.info("Writing example %d of %d", ex_index, len(examples)) feature = convert_single_example(ex_index, example, label_list, max_seq_length, tokenizer) def create_int_feature(values): f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values))) return f def create_float_feature(values): f = tf.train.Feature(float_list=tf.train.FloatList(value=list(values))) return f features = collections.OrderedDict() features["input_ids"] = create_int_feature(feature.input_ids) features["input_mask"] = create_int_feature(feature.input_mask) features["segment_ids"] = create_int_feature(feature.segment_ids) if label_type is not None and label_type == float: features["label_ids"] = create_float_feature([feature.label_id]) else: features["label_ids"] = create_int_feature([feature.label_id]) features["is_real_example"] = create_int_feature( [int(feature.is_real_example)]) tf_example = tf.train.Example(features=tf.train.Features(feature=features)) writer.write(tf_example.SerializeToString()) writer.close() def _truncate_seq_pair(tokens_a, tokens_b, max_length): """Truncates a sequence pair in place to the maximum length.""" # This is a simple heuristic which will always truncate the longer sequence # one token at a time. This makes more sense than truncating an equal percent # of tokens from each, since if one sequence is very short then each token # that's truncated likely contains more information than a longer sequence. while True: total_length = len(tokens_a) + len(tokens_b) if total_length <= max_length: break if len(tokens_a) > len(tokens_b): tokens_a.pop() else: tokens_b.pop() def generate_tf_record_from_data_file(processor, data_dir, tokenizer, train_data_output_path=None, eval_data_output_path=None, test_data_output_path=None, max_seq_length=128): """Generates and saves training data into a tf record file. Arguments: processor: Input processor object to be used for generating data. Subclass of `DataProcessor`. data_dir: Directory that contains train/eval data to process. Data files should be in from "dev.tsv", "test.tsv", or "train.tsv". tokenizer: The tokenizer to be applied on the data. train_data_output_path: Output to which processed tf record for training will be saved. eval_data_output_path: Output to which processed tf record for evaluation will be saved. test_data_output_path: Output to which processed tf record for testing will be saved. Must be a pattern template with {} if processor is XNLI. max_seq_length: Maximum sequence length of the to be generated training/eval data. Returns: A dictionary containing input meta data. """ assert train_data_output_path or eval_data_output_path label_list = processor.get_labels() label_type = getattr(processor, "label_type", None) is_regression = getattr(processor, "is_regression", False) assert train_data_output_path train_input_data_examples = processor.get_train_examples(data_dir) file_based_convert_examples_to_features(train_input_data_examples, label_list, max_seq_length, tokenizer, train_data_output_path, label_type) num_training_data = len(train_input_data_examples) if eval_data_output_path: eval_input_data_examples = processor.get_dev_examples(data_dir) file_based_convert_examples_to_features(eval_input_data_examples, label_list, max_seq_length, tokenizer, eval_data_output_path, label_type) if test_data_output_path: test_input_data_examples = processor.get_test_examples(data_dir) if isinstance(test_input_data_examples, dict): for language, examples in test_input_data_examples.items(): file_based_convert_examples_to_features( examples, label_list, max_seq_length, tokenizer, test_data_output_path.format(language), label_type) else: file_based_convert_examples_to_features(test_input_data_examples, label_list, max_seq_length, tokenizer, test_data_output_path, label_type) meta_data = { "processor_type": processor.get_processor_name(), "train_data_size": num_training_data, "max_seq_length": max_seq_length, } if is_regression: meta_data["task_type"] = "bert_regression" meta_data["label_type"] = {int: "int", float: "float"}[label_type] else: meta_data["task_type"] = "bert_classification" meta_data["num_labels"] = len(processor.get_labels()) if eval_data_output_path: meta_data["eval_data_size"] = len(eval_input_data_examples) if test_data_output_path: test_input_data_examples = processor.get_test_examples(data_dir) if isinstance(test_input_data_examples, dict): for language, examples in test_input_data_examples.items(): meta_data["test_{}_data_size".format(language)] = len(examples) else: meta_data["test_data_size"] = len(test_input_data_examples) return meta_data
# Generated by Django 2.2.13 on 2020-06-12 16:04 from django.db import migrations, models def backfill_old_banned_users(apps, schema_editor): # We already attempted this: # https://github.com/mozilla/addons-server/blob/2019.08.15/src/olympia/migrations/1116-add-banned-field.sql # NOQA # but it only backfilled accounts that had both fxa_id AND email set, so # ignored older accounts that didn't have an fxa_id, for example. UserProfile = apps.get_model('users', 'UserProfile') qs = UserProfile.objects.filter( deleted=True, banned=None).exclude(email=None, fxa_id=None) qs.update(banned=models.F('modified')) class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.RunPython(backfill_old_banned_users) ]
""" Labs DS Data Engineer Role - Database Interface - Visualization Interface """
'use strict'; /* global bootstrapModeler, inject */ var modelingModule = require('../../../../../lib/features/modeling'), coreModule = require('../../../../../lib/core'); describe('features/modeling - #PlanItemDefinitionUpdater', function() { var testModules = [ coreModule, modelingModule ]; describe('remove plan item definition when removing', function() { var diagramXML = require('./PlanItemDefinitionUpdater.simple-remove.cmmn'); beforeEach(bootstrapModeler(diagramXML, { modules: testModules })); describe('plan item', function() { var casePlanModel, taskDefinition; beforeEach(inject(function(elementRegistry, modeling) { // given var shape = elementRegistry.get('PI_Task_1'); taskDefinition = shape.businessObject.definitionRef; casePlanModel = elementRegistry.get('CasePlanModel_1').businessObject; // when modeling.removeShape(shape); })); it('should execute', function() { expect(casePlanModel.planItemDefinitions).not.to.include(taskDefinition); expect(taskDefinition.$parent).to.be.null; }); it('should undo', inject(function(commandStack) { // when commandStack.undo(); // then expect(casePlanModel.planItemDefinitions).to.include(taskDefinition); expect(taskDefinition.$parent).to.equal(casePlanModel); })); it('should redo', inject(function(commandStack) { // when commandStack.undo(); commandStack.redo(); // then expect(casePlanModel.planItemDefinitions).not.to.include(taskDefinition); expect(taskDefinition.$parent).to.be.null; })); }); describe('discretionary item', function() { var casePlanModel, taskDefinition; beforeEach(inject(function(elementRegistry, modeling) { // given var shape = elementRegistry.get('DIS_Task_2'); taskDefinition = shape.businessObject.definitionRef; casePlanModel = elementRegistry.get('CasePlanModel_1').businessObject; // when modeling.removeShape(shape); })); it('should execute', function() { expect(casePlanModel.planItemDefinitions).not.to.include(taskDefinition); expect(taskDefinition.$parent).to.be.null; }); it('should undo', inject(function(commandStack) { // when commandStack.undo(); // then expect(casePlanModel.planItemDefinitions).to.include(taskDefinition); expect(taskDefinition.$parent).to.equal(casePlanModel); })); it('should redo', inject(function(commandStack) { // when commandStack.undo(); commandStack.redo(); // then expect(casePlanModel.planItemDefinitions).not.to.include(taskDefinition); expect(taskDefinition.$parent).to.be.null; })); }); describe('plan item inside stage', function() { var stage, taskDefinition; beforeEach(inject(function(elementRegistry, modeling) { // given var shape = elementRegistry.get('PI_Task_3'); taskDefinition = shape.businessObject.definitionRef; stage = elementRegistry.get('PI_Stage_1').businessObject.definitionRef; // when modeling.removeShape(shape); })); it('should execute', function() { expect(stage.planItemDefinitions).not.to.include(taskDefinition); expect(taskDefinition.$parent).to.be.null; }); it('should undo', inject(function(commandStack) { // when commandStack.undo(); // then expect(stage.planItemDefinitions).to.include(taskDefinition); expect(taskDefinition.$parent).to.equal(stage); })); it('should redo', inject(function(commandStack) { // when commandStack.undo(); commandStack.redo(); // then expect(stage.planItemDefinitions).not.to.include(taskDefinition); expect(taskDefinition.$parent).to.be.null; })); }); describe('discretionary item inside stage', function() { var stage, taskDefinition; beforeEach(inject(function(elementRegistry, modeling) { // given var shape = elementRegistry.get('DIS_Task_4'); taskDefinition = shape.businessObject.definitionRef; stage = elementRegistry.get('PI_Stage_1').businessObject.definitionRef; // when modeling.removeShape(shape); })); it('should execute', function() { expect(stage.planItemDefinitions).not.to.include(taskDefinition); expect(taskDefinition.$parent).to.be.null; }); it('should undo', inject(function(commandStack) { // when commandStack.undo(); // then expect(stage.planItemDefinitions).to.include(taskDefinition); expect(taskDefinition.$parent).to.equal(stage); })); it('should redo', inject(function(commandStack) { // when commandStack.undo(); commandStack.redo(); // then expect(stage.planItemDefinitions).not.to.include(taskDefinition); expect(taskDefinition.$parent).to.be.null; })); }); describe('plan item inside plan fragment', function() { var casePlanModel, taskDefinition; beforeEach(inject(function(elementRegistry, modeling) { // given var shape = elementRegistry.get('PI_Task_5'); taskDefinition = shape.businessObject.definitionRef; casePlanModel = elementRegistry.get('CasePlanModel_1').businessObject; // when modeling.removeShape(shape); })); it('should execute', function() { expect(casePlanModel.planItemDefinitions).not.to.include(taskDefinition); expect(taskDefinition.$parent).to.be.null; }); it('should undo', inject(function(commandStack) { // when commandStack.undo(); // then expect(casePlanModel.planItemDefinitions).to.include(taskDefinition); expect(taskDefinition.$parent).to.equal(casePlanModel); })); it('should redo', inject(function(commandStack) { // when commandStack.undo(); commandStack.redo(); // then expect(casePlanModel.planItemDefinitions).not.to.include(taskDefinition); expect(taskDefinition.$parent).to.be.null; })); }); }); describe('should add to previous parent', function() { var stage, taskDefinition; var diagramXML = require('./PlanItemDefinitionUpdater.different-parents.cmmn'); beforeEach(bootstrapModeler(diagramXML, { modules: testModules })); beforeEach(inject(function(elementRegistry, modeling) { // given var shape = elementRegistry.get('PI_Task_1'); taskDefinition = shape.businessObject.definitionRef; stage = elementRegistry.get('PI_Stage_1').businessObject.definitionRef; // when modeling.removeShape(shape); })); it('should execute', function() { expect(stage.planItemDefinitions).not.to.include(taskDefinition); expect(taskDefinition.$parent).to.be.null; }); it('should undo', inject(function(commandStack) { // when commandStack.undo(); // then expect(stage.planItemDefinitions).to.include(taskDefinition); expect(taskDefinition.$parent).to.equal(stage); })); it('should redo', inject(function(commandStack) { // when commandStack.undo(); commandStack.redo(); // then expect(stage.planItemDefinitions).not.to.include(taskDefinition); expect(taskDefinition.$parent).to.be.null; })); }); describe('remain plan item definition when removing', function() { var diagramXML = require('./PlanItemDefinitionUpdater.shared-definition.cmmn'); beforeEach(bootstrapModeler(diagramXML, { modules: testModules })); describe('plan item', function() { var casePlanModel, taskDefinition; beforeEach(inject(function(elementRegistry, modeling) { // given var shape = elementRegistry.get('PI_Task_1'); taskDefinition = shape.businessObject.definitionRef; casePlanModel = elementRegistry.get('CasePlanModel_1').businessObject; // when modeling.removeShape(shape); })); it('should execute', function() { expect(casePlanModel.planItemDefinitions).to.include(taskDefinition); expect(taskDefinition.$parent).to.equal(casePlanModel); }); it('should undo', inject(function(commandStack) { // when commandStack.undo(); // then expect(casePlanModel.planItemDefinitions).to.include(taskDefinition); expect(taskDefinition.$parent).to.equal(casePlanModel); })); it('should redo', inject(function(commandStack) { // when commandStack.undo(); commandStack.redo(); // then expect(casePlanModel.planItemDefinitions).to.include(taskDefinition); expect(taskDefinition.$parent).to.equal(casePlanModel); })); }); describe('discretionary item', function() { var casePlanModel, taskDefinition; beforeEach(inject(function(elementRegistry, modeling) { // given var shape = elementRegistry.get('DIS_Task_2'); taskDefinition = shape.businessObject.definitionRef; casePlanModel = elementRegistry.get('CasePlanModel_1').businessObject; // when modeling.removeShape(shape); })); it('should execute', function() { expect(casePlanModel.planItemDefinitions).to.include(taskDefinition); expect(taskDefinition.$parent).to.equal(casePlanModel); }); it('should undo', inject(function(commandStack) { // when commandStack.undo(); // then expect(casePlanModel.planItemDefinitions).to.include(taskDefinition); expect(taskDefinition.$parent).to.equal(casePlanModel); })); it('should redo', inject(function(commandStack) { // when commandStack.undo(); commandStack.redo(); // then expect(casePlanModel.planItemDefinitions).to.include(taskDefinition); expect(taskDefinition.$parent).to.equal(casePlanModel); })); }); describe('plan item inside stage', function() { var stage, taskDefinition; beforeEach(inject(function(elementRegistry, modeling) { // given var shape = elementRegistry.get('PI_Task_3'); taskDefinition = shape.businessObject.definitionRef; stage = elementRegistry.get('PI_Stage_1').businessObject.definitionRef; // when modeling.removeShape(shape); })); it('should execute', function() { expect(stage.planItemDefinitions).to.include(taskDefinition); expect(taskDefinition.$parent).to.equal(stage); }); it('should undo', inject(function(commandStack) { // when commandStack.undo(); // then expect(stage.planItemDefinitions).to.include(taskDefinition); expect(taskDefinition.$parent).to.equal(stage); })); it('should redo', inject(function(commandStack) { // when commandStack.undo(); commandStack.redo(); // then expect(stage.planItemDefinitions).to.include(taskDefinition); expect(taskDefinition.$parent).to.equal(stage); })); }); describe('discretionary item inside stage', function() { var stage, taskDefinition; beforeEach(inject(function(elementRegistry, modeling) { // given var shape = elementRegistry.get('DIS_Task_4'); taskDefinition = shape.businessObject.definitionRef; stage = elementRegistry.get('PI_Stage_1').businessObject.definitionRef; // when modeling.removeShape(shape); })); it('should execute', function() { expect(stage.planItemDefinitions).to.include(taskDefinition); expect(taskDefinition.$parent).to.equal(stage); }); it('should undo', inject(function(commandStack) { // when commandStack.undo(); // then expect(stage.planItemDefinitions).to.include(taskDefinition); expect(taskDefinition.$parent).to.equal(stage); })); it('should redo', inject(function(commandStack) { // when commandStack.undo(); commandStack.redo(); // then expect(stage.planItemDefinitions).to.include(taskDefinition); expect(taskDefinition.$parent).to.equal(stage); })); }); describe('plan item inside plan fragment', function() { var casePlanModel, taskDefinition; beforeEach(inject(function(elementRegistry, modeling) { // given var shape = elementRegistry.get('PI_Task_5'); taskDefinition = shape.businessObject.definitionRef; casePlanModel = elementRegistry.get('CasePlanModel_1').businessObject; // when modeling.removeShape(shape); })); it('should execute', function() { expect(casePlanModel.planItemDefinitions).to.include(taskDefinition); expect(taskDefinition.$parent).to.equal(casePlanModel); }); it('should undo', inject(function(commandStack) { // when commandStack.undo(); // then expect(casePlanModel.planItemDefinitions).to.include(taskDefinition); expect(taskDefinition.$parent).to.equal(casePlanModel); })); it('should redo', inject(function(commandStack) { // when commandStack.undo(); commandStack.redo(); // then expect(casePlanModel.planItemDefinitions).to.include(taskDefinition); expect(taskDefinition.$parent).to.equal(casePlanModel); })); }); }); describe('delete nested planning table', function() { var diagramXML = require('./PlanItemDefinitionUpdater.nested-planning-table.cmmn'); var stage; beforeEach(bootstrapModeler(diagramXML, { modules: testModules })); beforeEach(inject(function(elementRegistry, modeling) { // given var shape = elementRegistry.get('DIS_HumanTask_1'); stage = elementRegistry.get('PI_Stage_1').businessObject.definitionRef; // when modeling.removeElements([ shape ]); })); it('should execute', function() { // then expect(stage.planningTable).not.to.exist; }); it('should undo', inject(function(commandStack) { // when commandStack.undo(); // then expect(stage.planningTable).to.exist; })); it('should redo', inject(function(commandStack) { // when commandStack.undo(); commandStack.redo(); // then expect(stage.planningTable).not.to.exist; })); }); });
// COPYRIGHT © 2021 Esri // // All rights reserved under the copyright laws of the United States // and applicable international laws, treaties, and conventions. // // This material is licensed for use under the Esri Master License // Agreement (MLA), and is bound by the terms of that agreement. // You may redistribute and use this code without modification, // provided you adhere to the terms of the MLA and include this // copyright notice. // // See use restrictions at http://www.esri.com/legal/pdfs/mla_e204_e300/english // // For additional information, contact: // Environmental Systems Research Institute, Inc. // Attn: Contracts and Legal Services Department // 380 New York Street // Redlands, California, USA 92373 // USA // // email: contracts@esri.com // // See http://js.arcgis.com/3.37/esri/copyright.txt for details. define(["dojo/_base/declare","dojo/_base/lang","dojo/dom-style","dojo/has","../base/Templated","dojo/text!./templates/EditDocumentPane.html","../../../kernel"],(function(e,t,s,o,n,a,d){var i=e([n],{gxeDocument:null,templateString:a,postCreate:function(){this.inherited(arguments)},hideMessage:function(){this.messageNode.innerHTML="",s.set(this.messageNode,"display","none")},showMessage:function(e){this.setNodeText(this.messageNode,e),s.set(this.messageNode,"display","")}});return o("extend-esri")&&t.setObject("dijit.metadata.editor.EditDocumentPane",i,d),i}));
from typing import Union, List from torch import Tensor import torch.nn as nn import torch.nn.functional as F from extorch.nn import ResNetBasicBlock, ResNetBottleneckBlock, ConvBNReLU class CIFARResNet(nn.Module): def __init__(self, block: Union[ResNetBasicBlock, ResNetBottleneckBlock], num_blocks: List[int], num_classes: int = 10) -> None: super(CIFARResNet, self).__init__() self.in_planes = 64 self.op = ConvBNReLU(3, 64, kernel_size = 3, stride = 1, padding = 1, bias = False) self.layer1 = self._make_layer(block, 64, num_blocks[0], stride = 1) self.layer2 = self._make_layer(block, 128, num_blocks[1], stride = 2) self.layer3 = self._make_layer(block, 256, num_blocks[2], stride = 2) self.layer4 = self._make_layer(block, 512, num_blocks[3], stride = 2) self.linear = nn.Linear(512 * block.expansion, num_classes) def _make_layer(self, block: Union[ResNetBottleneckBlock, ResNetBasicBlock], planes: int, num_blocks: int, stride: int) -> nn.Module: strides = [stride] + [1] * (num_blocks - 1) layers = [] for stride in strides: out_planes = planes * block.expansion layers.append(block(self.in_planes, out_planes, stride)) self.in_planes = out_planes return nn.Sequential(*layers) def forward(self, x: Tensor) -> Tensor: out = self.op(x) out = self.layer1(out) out = self.layer2(out) out = self.layer3(out) out = self.layer4(out) out = F.avg_pool2d(out, 4) out = out.view(out.size(0), -1) out = self.linear(out) return out def CIFARResNet18(num_classes: int) -> CIFARResNet: return CIFARResNet(ResNetBasicBlock, [2, 2, 2, 2], num_classes) def CIFARResNet34(num_classes: int) -> CIFARResNet: return CIFARResNet(ResNetBasicBlock, [3, 4, 6, 3], num_classes) def CIFARResNet50(num_classes: int) -> CIFARResNet: return CIFARResNet(ResNetBottleneckBlock, [3, 4, 6, 3], num_classes) def CIFARResNet101(num_classes: int) -> CIFARResNet: return CIFARResNet(ResNetBottleneckBlock, [3, 4, 23, 3], num_classes) def CIFARResNet152(num_classes: int) -> CIFARResNet: return CIFARResNet(ResNetBottleneckBlock, [3, 8, 36, 3], num_classes)
import json as _json import logging as _logging import os as _os import os.path as _path import sys as _sys import rsa as _rsa import fooster.web as _web # address to listen on addr = ('', 8000) # directory to store information dir = '/var/lib/mimameid' # log locations log = '/var/log/mimameid/mimameid.log' http_log = '/var/log/mimameid/http.log' # template directory to use template = _path.dirname(__file__) + '/html' # where texture service is located service = 'http://textures.minecraft.net' # whether to forward unknown requests to Mojang's Yggdrasil forward = False # runtime values based on config _key_pub = None _key_priv = None # store config in env var def _store(): config = {key: val for key, val in globals().items() if not key.startswith('_')} _os.environ['MIMAMEID_CONFIG'] = _json.dumps(config) # load config from env var def _load(): config = _json.loads(_os.environ['MIMAMEID_CONFIG']) globals().update(config) # automatically apply _apply() # apply special config-specific logic after changes def _apply(): global _key_pub, _key_priv # setup logging if log: _logging.getLogger('mimameid').addHandler(_logging.FileHandler(log)) else: _logging.getLogger('mimameid').addHandler(_logging.StreamHandler(_sys.stdout)) _logging.getLogger('mimameid').setLevel(_logging.INFO) if http_log: http_log_handler = _logging.FileHandler(http_log) http_log_handler.setFormatter(_web.HTTPLogFormatter()) _logging.getLogger('http').addHandler(http_log_handler) # setup rsa key if _path.exists(dir + '/pub.key'): _logging.getLogger('mimameid').info('Loading RSA key...') with open(dir + '/pub.key', 'rb') as key_file: _key_pub = _rsa.PublicKey.load_pkcs1(key_file.read()) with open(dir + '/priv.key', 'rb') as key_file: _key_priv = _rsa.PrivateKey.load_pkcs1(key_file.read()) else: _logging.getLogger('mimameid').info('Generating RSA key...') _key_pub, _key_priv = _rsa.newkeys(2048) _os.makedirs(dir, exist_ok=True) with open(dir + '/pub.key', 'wb') as key_file: key_file.write(_key_pub.save_pkcs1()) with open(dir + '/priv.key', 'wb') as key_file: key_file.write(_key_priv.save_pkcs1()) # automatically store if not already serialized if 'MIMAMEID_CONFIG' not in _os.environ: _store() # load if config already serialized in env var if 'MIMAMEID_CONFIG' in _os.environ: _load()
var React = require('react'); var ConfirmBattle = require('../components/ConfirmBattle'); var githubHelpers = require('../utils/githubHelpers'); var ConfirmBattleContainer = React.createClass({ contextTypes:{ router: React.PropTypes.object.isRequired }, getInitialState: function () { return { isLoading: true, playersInfo: [] } }, componentWillMount: function () { }, componentDidMount: function () { var query = this.props.location.query; githubHelpers.getPlayersInfo([query.playerOne, query.playerTwo]).then(function (players) { this.setState({ isLoading: false, playersInfo: [players[0], players[1]] }) }.bind(this)); }, componentWillReceiveProps: function () { }, componentWillUnmount: function () { }, handleInitiateBattle: function () { this.context.router.push({ pathname: '/results', state: { playersInfo: this.state.playersInfo } }) }, render: function () { return ( <ConfirmBattle isLoading={this.state.isLoading} playersInfo={this.state.playersInfo} onInitiateBattle={this.handleInitiateBattle} /> ); } }); module.exports = ConfirmBattleContainer;
require('../modules/web.immediate'); module.exports = require('../modules/$').core;
const runTask = require('../gulpfile'); const program = require('commander'); program.on('--help', () => { console.log(' Usage:'.to.bold.blue.color); console.log(); }); program.parse(process.argv); const taskType = program.args[0]; console.log(`FeiUI begin ${taskType}!`); runTask(taskType);
'use strict'; var bcrypt = require('bcrypt-nodejs'), Server = require('socket.io'), express = require('express'), http = require('http'), path = require('path'), mongo = require('mongojs'); var util = require('util'); var session = require('./session'); var _ = require('lodash'); var cors = require('cors'); var shortid = require('shortid'); function getDateForLog() { return new Date(); } function throwErr(func) { return function (err, data) { if (err) { throw err; } else { func.call(null, data); } }; } function validateScene(sceneData) { // convert _id so mongo recognizes it if (sceneData.hasOwnProperty('_id')) { sceneData._id = mongo.ObjectId(sceneData._id); } // add _ids to all mediaObjects if (sceneData.hasOwnProperty('scene')) { if (!Array.isArray(sceneData.scene)) { throw new Error('"scene" property must be an array of objects'); } else { sceneData.scene.forEach(function (mediaObject) { if (!mediaObject.hasOwnProperty('_id')) { mediaObject._id = mongo.ObjectId(); } }); } } return sceneData; } function validateSceneGraph(sceneGraphData) { //convert _id so mongo recognizes it if (sceneGraphData.hasOwnProperty('_id')) { sceneGraphData._id = mongo.ObjectId(sceneGraphData._id); } //TODO most likely more detailed validation can occur return sceneGraphData; } function isCredsForUsernameAndPasswordCheck(creds) { var passwordField = (creds.hasOwnProperty('password') && creds.password) && creds.password !== ''; var usernameField = (creds.hasOwnProperty('username') && creds.username) && creds.username !== ''; return passwordField && usernameField; } function isCredsForPasswordOnlyCheck(creds) { var passwordField = creds.hasOwnProperty('password') && creds.password && creds.password !== ''; var usernameField = (creds.hasOwnProperty('username') && creds.username === '') || !creds.hasOwnProperty('username'); return passwordField && usernameField; } function isCredsForTokenCheck(creds) { return creds.hasOwnProperty('token') && creds.token && creds.token !== ''; } function checkUsersCredsAgainstUsersTable(db, username, password, cb) { try { var collection = db.collection('usersWithGroup'); collection.findOne({username: username}, function (err, user) { if(user !== null && bcrypt.compareSync(password, user.password)) { cb(user.groupID); } else { cb(-1); } }); } catch (e) { cb(-1); } } function checkPasswordKeyAndGetGroup(password, config) { try { //AJF: Compares the passwords and determines what group the user logging into belongs to if (bcrypt.compareSync(password, config.secret)) { return 0; } else if (bcrypt.compareSync(password, config.secret_1)) { return 1; } else if (bcrypt.compareSync(password, config.secret_2)) { return 2; } else if (bcrypt.compareSync(password, config.secret_101)) { return 101; } else if (bcrypt.compareSync(password, config.secret_102)) { return 102; } else if (bcrypt.compareSync(password, config.secret_103)) { return 103; } else if (bcrypt.compareSync(password, config.secret_104)) { return 104; } else if (bcrypt.compareSync(password, config.secret_105)) { return 105; } else if (bcrypt.compareSync(password, config.secret_106)) { return 106; } else if (bcrypt.compareSync(password, config.secret_107)) { return 107; } else if (bcrypt.compareSync(password, config.secret_108)) { return 108; } else if (bcrypt.compareSync(password, config.secret_109)) { return 109; } else if (bcrypt.compareSync(password, config.secret_110)) { return 110; } else if (bcrypt.compareSync(password, config.secret_111)) { return 111; } else if (bcrypt.compareSync(password, config.secret_112)) { return 112; } else if (bcrypt.compareSync(password, config.secret_113)) { return 113; } else if (bcrypt.compareSync(password, config.secret_114)) { return 114; } else if (bcrypt.compareSync(password, config.secret_115)) { return 115; } else if (bcrypt.compareSync(password, config.secret_116)) { return 116; } else if (bcrypt.compareSync(password, config.secret_117)) { return 117; } else if (bcrypt.compareSync(password, config.secret_118)) { return 118; } else if (bcrypt.compareSync(password, config.secret_119)) { return 119; } // APEP if we haven't found a group, we must return nothing found return -1; } catch (e) { console.log("Error trying to find group and password lookup"); return -1; } } function adminApiCalls(hub, io, socket, session) { socket.on('authProvider', function (creds, callback) { console.log("AuthProvider - received creds: ", creds); //APEP: param record - session object from db function succeed(record) { var roomId = shortid.generate(); // APEP: generate a user friendly shortid for roomID for graph and player to communicate return callback(null, record._id.toString(), roomId, record._groupID.toString()); } if (isCredsForUsernameAndPasswordCheck(creds)) { //AJF: Compares the passwords and determines what group the user logging into belongs to checkUsersCredsAgainstUsersTable(hub.db, creds.username, creds.password, function(userGroup) { if (userGroup !== -1) { session.create(userGroup, function (err, data) { if (data) { succeed(data); } else { return callback(err); } }); } else { console.log("AuthProvider - calling back invalid password - not found"); return callback('Invalid Username or Password', null, null, null); } }); } else if (isCredsForPasswordOnlyCheck(creds)) { //AJF: Compares the passwords and determines what group the user logging into belongs to var userGroup = checkPasswordKeyAndGetGroup(creds.password, hub.config); if (userGroup !== -1) { session.create(userGroup, throwErr(succeed)); } else { console.log("AuthProvider - calling back invalid password - not found"); return callback('Invalid Password', null, null, null); } } else if (isCredsForTokenCheck(creds)) { console.log("AuthProvider - Finding session via token"); session.find(creds.token, function (err, data) { if (data) { succeed(data); } else { return callback('Invalid Token', null, null, null); } }); } else { return callback('Password must be provided', null, null, null); } }); } function addApiCalls(hub, io, socket) { function idSearch(id) { return {_id: mongo.ObjectId(id)}; } function _findScene(sceneId, cb) { console.log(getDateForLog() + " - hub.js - _findScene"); return hub.db.mediaScenes.findOne(idSearch(sceneId), cb); } function _findSceneGraph(sceneGraphId, cb) { console.log(getDateForLog() + " - hub.js - _findSceneGraph"); return hub.db.mediaSceneGraphs.findOne(idSearch(sceneGraphId), cb); } function _findSceneList(cb) { _findSceneListWithGroupId(socket.groupID, cb); } function _findSceneListWithGroupId(groupId, cb) { console.log(getDateForLog() + " - hub.js - listScenes groupId: " + groupId); try { groupId = parseInt(groupId); } catch (e) { return cb(true, null); } //AJF: if the groupID is 0 (admin) then list all scenes if (groupId === 0) { hub.db.mediaScenes.find({'$query': {}, '$orderby': {name: 1}}, {name: 1, _groupID: 2}, cb); } else { hub.db.mediaScenes.find({'$query': {_groupID: groupId}, '$orderby': {name: 1}}, {name: 1, _groupID: 2}, cb); } } // APEP Support listing scenes given a groupID, this is for controllers who use this API as an admin socket. // This is the reason for the additional call, an admin socket must be able to give the groupID for its client socket. socket.on('listScenesForGroup', _findSceneListWithGroupId); socket.on('listScenes', _findSceneList); socket.on('listSceneGraphs', function (callback) { console.log(getDateForLog() + " - hub.js - listSceneGraphs"); hub.db.mediaSceneGraphs.find({'$query': {}}, callback); }); socket.on('saveScene', function (sceneData, callback) { console.log(getDateForLog() + " - hub.js - listSceneGraphs"); try { var data = validateScene(sceneData); console.log(getDateForLog() + " - hub.js - saveScene after validation: ", data); //AJF: sanity check to stop client side CTRL+Z bug blank scene reaching the db if (data.hasOwnProperty('themes') || data.hasOwnProperty('style') || data.hasOwnProperty('scene')) { console.log("Valid"); //AJF: save the groupID acquired from the socket if the groupID isn't already set console.log(getDateForLog() + " - hub.js - saveScene data._groupID: " + data._groupID); if (!data._groupID) { console.log(getDateForLog() + " - hub.js - saveScene data._groupID not set so setting to: " + socket.groupID); data._groupID = socket.groupID; } hub.db.mediaScenes.save(data, function (err, scene) { io.to(scene._id.toString()).emit('sceneUpdate', scene); if (callback) { callback(err, scene); } }); } } catch (err) { if (callback) { callback(err.message); } } }); socket.on('saveSceneGraph', function (sceneGraphData, callback) { try { console.log(getDateForLog() + " - hub.js - saveSceneGraph"); var data = validateSceneGraph(sceneGraphData); hub.db.mediaSceneGraphs.save(data, function (err, sceneGraph) { io.to(sceneGraph._id.toString()).emit('sceneGraphUpdate', sceneGraph); if (callback) { callback(err, sceneGraph); } }); } catch (err) { if (callback) { callback(err.message); } } }); socket.on('loadScene', _findScene); socket.on('loadSceneGraph', _findSceneGraph); socket.on('loadSceneByName', function (name, callback) { console.log(getDateForLog() + " - hub.js - loadSceneByName"); hub.db.mediaScenes.findOne({name: name}, callback); }); socket.on('deleteScene', function (sceneId, callback) { console.log(getDateForLog() + " - hub.js - deleteScene"); hub.db.mediaScenes.remove(idSearch(sceneId), function (err) { if (callback) { callback(err); } }); }); socket.on('deleteSceneGraph', function (sceneGraphId, callback) { console.log(getDateForLog() + " - hub.js - deleteSceneGraph"); hub.db.mediaSceneGraphs.remove(idSearch(sceneGraphId), function (err) { if (callback) { callback(err); } }); }); socket.on('subScene', function (sceneId, callback) { console.log(getDateForLog() + " - hub.js - subScene"); _findScene(sceneId, function (err, scene) { socket.join(sceneId); if (callback) { callback(err, scene); } }); }); socket.on('unsubScene', function (sceneId, callback) { console.log(getDateForLog() + " - hub.js - unsubScene"); _findScene(sceneId, function (err, scene) { socket.leave(sceneId); if (callback) { callback(err); } }); }); socket.on('sendCommand', function (roomId, commandName, commandValue) { console.log(getDateForLog() + " - hub.js - sendCommand: ", { roomId: roomId, commandName: commandName, commandValue: commandValue }); io.to(roomId).emit('command', {name: commandName, value: commandValue}); }); socket.on('register', function (roomId) { roomId = roomId.replace("/#", ""); console.log(getDateForLog() + " - hub.js - REGISTER TO ROOM: ", roomId); socket.join(roomId); }); } var Hub = function (config) { this.config = config; this.db = mongo.connect(config.mongo, ['mediaScenes', 'sessions', 'mediaSceneGraphs']); session.setClient(this.db); }; Hub.prototype.listen = function (callback) { var self = this, app = express(), server = http.Server(app), io = new Server(server); this.server = server; app.use(cors()); // allow cross origin requests io.set('origins', '*:*'); io.sockets.on('connection', function (socket) { var disconnectTimer = setTimeout(function () { socket.disconnect(); }, 10000); socket.on('auth', function (creds, callback) { //APEP: param record - session object from db function succeed(record) { socket.groupID = record._groupID; //AJF: set the groupID on the socket to be used in further local calls addApiCalls(self, io, socket); //APEP: attach all the socket listeners //APEP: for admin sockets, we can provide some additional socket listeners if (record._groupID === 0) { adminApiCalls(self, io, socket, session); } clearTimeout(disconnectTimer); //APEP: ensure we stop the fail safe of closing an unauthenticated socket var roomId = shortid.generate(); // APEP: generate a user friendly shortid for roomID for graph and player to communicate console.log("auth - suceed - calling back:"); // APEP logging and test if callback exists - used due to error in android platform if (callback) callback(null, record._id.toString(), roomId, record._groupID.toString());//AJF: try to return the groupID... } function fail(msg) { callback(msg); socket.disconnect(); } if (isCredsForUsernameAndPasswordCheck(creds)) { //AJF: Compares the passwords and determines what group the user logging into belongs to checkUsersCredsAgainstUsersTable(self.db, creds.username, creds.password, function(userGroup) { if (userGroup !== -1) { session.create(userGroup, throwErr(succeed)); } else { fail('Invalid Username or Password'); } }); } else if (isCredsForPasswordOnlyCheck(creds)) { //AJF: Compares the passwords and determines what group the user logging into belongs to var userGroup = checkPasswordKeyAndGetGroup(creds.password, self.config); if (userGroup !== -1) { session.create(userGroup, throwErr(succeed)); } else { fail('Invalid Password'); } } else if (isCredsForTokenCheck(creds)) { console.log("Finding session via token"); session.find(creds.token, function (err, data) { if (data) { succeed(data); } else { fail('Invalid Token'); } }); } else { fail('Password must be provided'); } }); }); server.listen(self.config.port, callback); }; Hub.prototype.close = function (cb) { this.server.close(cb); }; module.exports = { createHub: function (mongoUrl) { return new Hub(mongoUrl); } };
// Copyright 2019 Intel Corporation and Smart-Edge.com, Inc. 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. import React from 'react'; import ReactDOM from 'react-dom'; import renderer from 'react-test-renderer'; import App from './App'; describe('App', () => { it('renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render( <App />, div ); ReactDOM.unmountComponentAtNode(div); }); test('has a valid snapshot', () => { const component = renderer.create( <App /> ); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); });
import * as tf from '@tensorflow/tfjs'; import { makeStorage } from '../util'; import { kInputPlanes } from '../neural/network'; import NetworkFactory from '../neural/factory'; import { TrainingDataWriter } from '../neural/writer'; import { saveWeights } from '../neural/loader'; import BitIterator from '../neural/bititer'; export function Training(options) { const network = NetworkFactory.LoadNetwork(options); this.run = () => { return new TrainingDataWriter().get() .then(_ => { function step(values, history) { if (values.length) { const chunk = values.splice(0, 10000); console.log('training ', chunk.length + '/' + values.length); return train(chunk).then(_ => step(values, _)); } else { return Promise.resolve(history); } }; return step(_); }); }; const train = data => { console.log(data); const { value, policy } = network.model; value.compile({ optimizer: 'sgd', loss: 'meanSquaredError', metrics: ['accuracy'] }); policy.compile({ optimizer: 'sgd', loss: 'categoricalCrossentropy', metrics: ['accuracy'] }); let xsBuffer = tf.buffer([data.length, kInputPlanes, 8, 8]); var flat = xsBuffer.values; let iterIdx = 0; for (const inputIdx in data) { var sample = data[inputIdx].planes; for (const mask of sample) { for (var bit of BitIterator(mask)) { flat[iterIdx + bit] = 1; } iterIdx += 64; } } xsBuffer = xsBuffer.toTensor(); let xs, vYs = data.map(_ => _.bestQ), pYs = data.map(_ => _.probabilities); xs = xsBuffer.reshape([-1, kInputPlanes, 8, 8]); vYs = tf.tensor1d(vYs); pYs = tf.tensor2d(pYs, [pYs.length, 4]); const dispose = () => [xsBuffer, xs, vYs, pYs] .forEach(_ => _.dispose); return Promise .all([value.fit(xs, vYs), policy.fit(xs, pYs)]) .then(hs => { saveWeights(network.model); dispose(); console.log(tf.memory().numTensors); return hs[0].history; }); }; }
'use strict'; const artists = ['Adrian Belew', 'Baba Lou', 'Bachman-Turner Overdrive', 'Banarama'] const artistAlbums = { 'Adrian Belew': ['Lone Rhino'], 'Baba Lou': ['Baba Lou at Bob\'s'], 'Bachman-Turner Overdrive': ['Bachman-Turner Overdrive II'], 'Bananarama': ['Deep Sea Skiving'] }; const albumTracks = { 'Adrian Belew/Lone Rhino': ['Big Electric Cat', 'The Momur'] }; const trackDetails = { 'Adrian Belew/Lone Rhino/Big Electric Cat': {path: 'mp3wave/Adrian Belew/Lone Rhino/01 - Big Electric Cat.mp3'}, 'Adrian Belew/Lone Rhino/The Momur': {path: 'mp3wave/Adrian Belew/Lone Rhino/02 - The Momur.mp3'} }; module.exports = {artists: artists, artistAlbums: artistAlbums, albumTracks: albumTracks, trackDetails: trackDetails};
/** * History.js Core * @author Benjamin Arthur Lupton <contact@balupton.com> * @copyright 2010-2011 Benjamin Arthur Lupton <contact@balupton.com> * @license New BSD License <http://creativecommons.org/licenses/BSD/> */ (function(window,undefined){ "use strict"; // -------------------------------------------------------------------------- // Initialise // Localise Globals var console = window.console||undefined, // Prevent a JSLint complain document = window.document, // Make sure we are using the correct document navigator = window.navigator, // Make sure we are using the correct navigator amplify = window.amplify||false, // Amplify.js setTimeout = window.setTimeout, clearTimeout = window.clearTimeout, setInterval = window.setInterval, JSON = window.JSON, History = window.History = window.History||{}, // Public History Object history = window.history; // Old History Object // MooTools Compatibility JSON.stringify = JSON.stringify||JSON.encode; JSON.parse = JSON.parse||JSON.decode; // Check Existence if ( typeof History.init !== 'undefined' ) { throw new Error('History.js Core has already been loaded...'); } // Initialise History History.init = function(){ // Check Load Status of Adapter if ( typeof History.Adapter === 'undefined' ) { return false; } // Check Load Status of Core if ( typeof History.initCore !== 'undefined' ) { History.initCore(); } // Check Load Status of HTML4 Support if ( typeof History.initHtml4 !== 'undefined' ) { History.initHtml4(); } // Return true return true; }; // -------------------------------------------------------------------------- // Initialise Core // Initialise Core History.initCore = function(){ // Initialise if ( typeof History.initCore.initialized !== 'undefined' ) { // Already Loaded return false; } else { History.initCore.initialized = true; } // ---------------------------------------------------------------------- // Options /** * History.options * Configurable options */ History.options = History.options||{}; /** * History.options.hashChangeInterval * How long should the interval be before hashchange checks */ History.options.hashChangeInterval = History.options.hashChangeInterval || 100; /** * History.options.safariPollInterval * How long should the interval be before safari poll checks */ History.options.safariPollInterval = History.options.safariPollInterval || 500; /** * History.options.doubleCheckInterval * How long should the interval be before we perform a double check */ History.options.doubleCheckInterval = History.options.doubleCheckInterval || 500; /** * History.options.storeInterval * How long should we wait between store calls */ History.options.storeInterval = History.options.storeInterval || 1000; /** * History.options.busyDelay * How long should we wait between busy events */ History.options.busyDelay = History.options.busyDelay || 250; /** * History.options.debug * If true will enable debug messages to be logged */ History.options.debug = History.options.debug || false; /** * History.options.initialTitle * What is the title of the initial state */ History.options.initialTitle = History.options.initialTitle || document.title; // ---------------------------------------------------------------------- // Debug /** * History.debug(message,...) * Logs the passed arguments if debug enabled */ History.debug = function(){ if ( (History.options.debug||false) ) { History.log.apply(History,arguments); } }; /** * History.log(message,...) * Logs the passed arguments */ History.log = function(){ // Prepare var consoleExists = !(typeof console === 'undefined' || typeof console.log === 'undefined' || typeof console.log.apply === 'undefined'), textarea = document.getElementById('log'), message, i,n ; // Write to Console if ( consoleExists ) { var args = Array.prototype.slice.call(arguments); message = args.shift(); if ( typeof console.debug !== 'undefined' ) { console.debug.apply(console,[message,args]); } else { console.log.apply(console,[message,args]); } } else { message = ("\n"+arguments[0]+"\n"); } // Write to log for ( i=1,n=arguments.length; i<n; ++i ) { var arg = arguments[i]; if ( typeof arg === 'object' && typeof JSON !== 'undefined' ) { try { arg = JSON.stringify(arg); } catch ( Exception ) { // Recursive Object } } message += "\n"+arg+"\n"; } // Textarea if ( textarea ) { textarea.value += message+"\n-----\n"; textarea.scrollTop = textarea.scrollHeight - textarea.clientHeight; } // No Textarea, No Console else if ( !consoleExists ) { alert(message); } // Return true return true; }; // ---------------------------------------------------------------------- // Emulated Status /** * History.getInternetExplorerMajorVersion() * Get's the major version of Internet Explorer * @return {integer} * @license Public Domain * @author Benjamin Arthur Lupton <contact@balupton.com> * @author James Padolsey <https://gist.github.com/527683> */ History.getInternetExplorerMajorVersion = function(){ var result = History.getInternetExplorerMajorVersion.cached = (typeof History.getInternetExplorerMajorVersion.cached !== 'undefined') ? History.getInternetExplorerMajorVersion.cached : (function(){ var v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i'); while ( (div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->') && all[0] ) {} return (v > 4) ? v : false; })() ; return result; }; /** * History.isInternetExplorer() * Are we using Internet Explorer? * @return {boolean} * @license Public Domain * @author Benjamin Arthur Lupton <contact@balupton.com> */ History.isInternetExplorer = function(){ var result = History.isInternetExplorer.cached = (typeof History.isInternetExplorer.cached !== 'undefined') ? History.isInternetExplorer.cached : Boolean(History.getInternetExplorerMajorVersion()) ; return result; }; /** * History.emulated * Which features require emulating? */ History.emulated = { pushState: !Boolean( window.history && window.history.pushState && window.history.replaceState && !( (/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(navigator.userAgent) /* disable for versions of iOS before version 4.3 (8F190) */ || (/AppleWebKit\/5([0-2]|3[0-2])/i).test(navigator.userAgent) /* disable for the mercury iOS browser, or at least older versions of the webkit engine */ ) ), hashChange: Boolean( !(('onhashchange' in window) || ('onhashchange' in document)) || (History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8) ) }; /** * History.enabled * Is History enabled? */ History.enabled = !History.emulated.pushState; /** * History.bugs * Which bugs are present */ History.bugs = { /** * Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call * https://bugs.webkit.org/show_bug.cgi?id=56249 */ setHash: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)), /** * Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions * https://bugs.webkit.org/show_bug.cgi?id=42940 */ safariPoll: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)), /** * MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function) */ ieDoubleCheck: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8), /** * MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event */ hashEscape: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 7) }; /** * History.isEmptyObject(obj) * Checks to see if the Object is Empty * @param {Object} obj * @return {boolean} */ History.isEmptyObject = function(obj) { for ( var name in obj ) { return false; } return true; }; /** * History.cloneObject(obj) * Clones a object * @param {Object} obj * @return {Object} */ History.cloneObject = function(obj) { var hash,newObj; if ( obj ) { hash = JSON.stringify(obj); newObj = JSON.parse(hash); } else { newObj = {}; } return newObj; }; // ---------------------------------------------------------------------- // URL Helpers /** * History.getRootUrl() * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com" * @return {String} rootUrl */ History.getRootUrl = function(){ // Create var rootUrl = document.location.protocol+'//'+(document.location.hostname||document.location.host); if ( document.location.port||false ) { rootUrl += ':'+document.location.port; } rootUrl += '/'; // Return return rootUrl; }; /** * History.getBaseHref() * Fetches the `href` attribute of the `<base href="...">` element if it exists * @return {String} baseHref */ History.getBaseHref = function(){ // Create var baseElements = document.getElementsByTagName('base'), baseElement = null, baseHref = ''; // Test for Base Element if ( baseElements.length === 1 ) { // Prepare for Base Element baseElement = baseElements[0]; baseHref = baseElement.href.replace(/[^\/]+$/,''); } // Adjust trailing slash baseHref = baseHref.replace(/\/+$/,''); if ( baseHref ) baseHref += '/'; // Return return baseHref; }; /** * History.getBaseUrl() * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first) * @return {String} baseUrl */ History.getBaseUrl = function(){ // Create var baseUrl = History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl(); // Return return baseUrl; }; /** * History.getPageUrl() * Fetches the URL of the current page * @return {String} pageUrl */ History.getPageUrl = function(){ // Fetch var State = History.getState(false,false), stateUrl = (State||{}).url||document.location.href; // Create var pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){ return (/\./).test(part) ? part : part+'/'; }); // Return return pageUrl; }; /** * History.getBasePageUrl() * Fetches the Url of the directory of the current page * @return {String} basePageUrl */ History.getBasePageUrl = function(){ // Create var basePageUrl = document.location.href.replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){ return (/[^\/]$/).test(part) ? '' : part; }).replace(/\/+$/,'')+'/'; // Return return basePageUrl; }; /** * History.getFullUrl(url) * Ensures that we have an absolute URL and not a relative URL * @param {string} url * @param {Boolean} allowBaseHref * @return {string} fullUrl */ History.getFullUrl = function(url,allowBaseHref){ // Prepare var fullUrl = url, firstChar = url.substring(0,1); allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref; // Check if ( /[a-z]+\:\/\//.test(url) ) { // Full URL } else if ( firstChar === '/' ) { // Root URL fullUrl = History.getRootUrl()+url.replace(/^\/+/,''); } else if ( firstChar === '#' ) { // Anchor URL fullUrl = History.getPageUrl().replace(/#.*/,'')+url; } else if ( firstChar === '?' ) { // Query URL fullUrl = History.getPageUrl().replace(/[\?#].*/,'')+url; } else { // Relative URL if ( allowBaseHref ) { fullUrl = History.getBaseUrl()+url.replace(/^(\.\/)+/,''); } else { fullUrl = History.getBasePageUrl()+url.replace(/^(\.\/)+/,''); } // We have an if condition above as we do not want hashes // which are relative to the baseHref in our URLs // as if the baseHref changes, then all our bookmarks // would now point to different locations // whereas the basePageUrl will always stay the same } // Return return fullUrl.replace(/\#$/,''); }; /** * History.getShortUrl(url) * Ensures that we have a relative URL and not a absolute URL * @param {string} url * @return {string} url */ History.getShortUrl = function(url){ // Prepare var shortUrl = url, baseUrl = History.getBaseUrl(), rootUrl = History.getRootUrl(); // Trim baseUrl if ( History.emulated.pushState ) { // We are in a if statement as when pushState is not emulated // The actual url these short urls are relative to can change // So within the same session, we the url may end up somewhere different shortUrl = shortUrl.replace(baseUrl,''); } // Trim rootUrl shortUrl = shortUrl.replace(rootUrl,'/'); // Ensure we can still detect it as a state if ( History.isTraditionalAnchor(shortUrl) ) { shortUrl = './'+shortUrl; } // Clean It shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,''); // Return return shortUrl; }; // ---------------------------------------------------------------------- // State Storage /** * History.store * The store for all session specific data */ History.store = amplify ? (amplify.store('History.store')||{}) : {}; History.store.idToState = History.store.idToState||{}; History.store.urlToId = History.store.urlToId||{}; History.store.stateToId = History.store.stateToId||{}; /** * History.idToState * 1-1: State ID to State Object */ History.idToState = History.idToState||{}; /** * History.stateToId * 1-1: State String to State ID */ History.stateToId = History.stateToId||{}; /** * History.urlToId * 1-1: State URL to State ID */ History.urlToId = History.urlToId||{}; /** * History.storedStates * Store the states in an array */ History.storedStates = History.storedStates||[]; /** * History.savedStates * Saved the states in an array */ History.savedStates = History.savedStates||[]; /** * History.getState() * Get an object containing the data, title and url of the current state * @param {Boolean} friendly * @param {Boolean} create * @return {Object} State */ History.getState = function(friendly,create){ // Prepare if ( typeof friendly === 'undefined' ) { friendly = true; } if ( typeof create === 'undefined' ) { create = true; } // Fetch var State = History.getLastSavedState(); // Create if ( !State && create ) { State = History.createStateObject(); } // Adjust if ( friendly ) { State = History.cloneObject(State); State.url = State.cleanUrl||State.url; } // Return return State; }; /** * History.getIdByState(State) * Gets a ID for a State * @param {State} newState * @return {String} id */ History.getIdByState = function(newState){ // Fetch ID var id = History.extractId(newState.url); if ( !id ) { // Find ID via State String var str = History.getStateString(newState); if ( typeof History.stateToId[str] !== 'undefined' ) { id = History.stateToId[str]; } else if ( typeof History.store.stateToId[str] !== 'undefined' ) { id = History.store.stateToId[str]; } else { // Generate a new ID while ( true ) { id = String(Math.floor(Math.random()*1000)); if ( typeof History.idToState[id] === 'undefined' && typeof History.store.idToState[id] === 'undefined' ) { break; } } // Apply the new State to the ID History.stateToId[str] = id; History.idToState[id] = newState; } } // Return ID return id; }; /** * History.normalizeState(State) * Expands a State Object * @param {object} State * @return {object} */ History.normalizeState = function(oldState){ // Prepare if ( !oldState || (typeof oldState !== 'object') ) { oldState = {}; } // Check if ( typeof oldState.normalized !== 'undefined' ) { return oldState; } // Adjust if ( !oldState.data || (typeof oldState.data !== 'object') ) { oldState.data = {}; } // ---------------------------------------------------------------------- // Create var newState = {}; newState.normalized = true; newState.title = oldState.title||''; newState.url = History.getFullUrl(History.unescapeString(oldState.url||document.location.href)); newState.hash = History.getShortUrl(newState.url); newState.data = History.cloneObject(oldState.data); // Fetch ID newState.id = History.getIdByState(newState); // ---------------------------------------------------------------------- // Clean the URL newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,''); newState.url = newState.cleanUrl; // Check to see if we have more than just a url var dataNotEmpty = !History.isEmptyObject(newState.data); // Apply if ( newState.title || dataNotEmpty ) { // Add ID to Hash newState.hash = History.getShortUrl(newState.url).replace(/\??\&_suid.*/,''); if ( !/\?/.test(newState.hash) ) { newState.hash += '?'; } newState.hash += '&_suid='+newState.id; } // Create the Hashed URL newState.hashedUrl = History.getFullUrl(newState.hash); // ---------------------------------------------------------------------- // Update the URL if we have a duplicate if ( (History.emulated.pushState || History.bugs.safariPoll) && History.hasUrlDuplicate(newState) ) { newState.url = newState.hashedUrl; } // ---------------------------------------------------------------------- // Return return newState; }; /** * History.createStateObject(data,title,url) * Creates a object based on the data, title and url state params * @param {object} data * @param {string} title * @param {string} url * @return {object} */ History.createStateObject = function(data,title,url){ // Hashify var State = { 'data': data, 'title': title, 'url': url }; // Expand the State State = History.normalizeState(State); // Return object return State; }; /** * History.getStateById(id) * Get a state by it's UID * @param {String} id */ History.getStateById = function(id){ // Prepare id = String(id); // Retrieve var State = History.idToState[id] || History.store.idToState[id] || undefined; // Return State return State; }; /** * Get a State's String * @param {State} passedState */ History.getStateString = function(passedState){ // Prepare var State = History.normalizeState(passedState); // Clean var cleanedState = { data: State.data, title: passedState.title, url: passedState.url }; // Fetch var str = JSON.stringify(cleanedState); // Return return str; }; /** * Get a State's ID * @param {State} passedState * @return {String} id */ History.getStateId = function(passedState){ // Prepare var State = History.normalizeState(passedState); // Fetch var id = State.id; // Return return id; }; /** * History.getHashByState(State) * Creates a Hash for the State Object * @param {State} passedState * @return {String} hash */ History.getHashByState = function(passedState){ // Prepare var hash, State = History.normalizeState(passedState); // Fetch hash = State.hash; // Return return hash; }; /** * History.extractId(url_or_hash) * Get a State ID by it's URL or Hash * @param {string} url_or_hash * @return {string} id */ History.extractId = function ( url_or_hash ) { // Prepare var id; // Extract var parts,url; parts = /(.*)\&_suid=([0-9]+)$/.exec(url_or_hash); url = parts ? (parts[1]||url_or_hash) : url_or_hash; id = parts ? String(parts[2]||'') : ''; // Return return id||false; }; /** * History.isTraditionalAnchor * Checks to see if the url is a traditional anchor or not * @param {String} url_or_hash * @return {Boolean} */ History.isTraditionalAnchor = function(url_or_hash){ // Check var isTraditional = !(/[\/\?\.]/.test(url_or_hash)); // Return return isTraditional; }; /** * History.extractState * Get a State by it's URL or Hash * @param {String} url_or_hash * @return {State|null} */ History.extractState = function(url_or_hash,create){ // Prepare var State = null; create = create||false; // Fetch SUID var id = History.extractId(url_or_hash); if ( id ) { State = History.getStateById(id); } // Fetch SUID returned no State if ( !State ) { // Fetch URL var url = History.getFullUrl(url_or_hash); // Check URL id = History.getIdByUrl(url)||false; if ( id ) { State = History.getStateById(id); } // Create State if ( !State && create && !History.isTraditionalAnchor(url_or_hash) ) { State = History.createStateObject(null,null,url); } } // Return return State; }; /** * History.getIdByUrl() * Get a State ID by a State URL */ History.getIdByUrl = function(url){ // Fetch var id = History.urlToId[url] || History.store.urlToId[url] || undefined; // Return return id; }; /** * History.getLastSavedState() * Get an object containing the data, title and url of the current state * @return {Object} State */ History.getLastSavedState = function(){ return History.savedStates[History.savedStates.length-1]||undefined; }; /** * History.getLastStoredState() * Get an object containing the data, title and url of the current state * @return {Object} State */ History.getLastStoredState = function(){ return History.storedStates[History.storedStates.length-1]||undefined; }; /** * History.hasUrlDuplicate * Checks if a Url will have a url conflict * @param {Object} newState * @return {Boolean} hasDuplicate */ History.hasUrlDuplicate = function(newState) { // Prepare var hasDuplicate = false; // Fetch var oldState = History.extractState(newState.url); // Check hasDuplicate = oldState && oldState.id !== newState.id; // Return return hasDuplicate; }; /** * History.storeState * Store a State * @param {Object} newState * @return {Object} newState */ History.storeState = function(newState){ // Store the State History.urlToId[newState.url] = newState.id; // Push the State History.storedStates.push(History.cloneObject(newState)); // Return newState return newState; }; /** * History.isLastSavedState(newState) * Tests to see if the state is the last state * @param {Object} newState * @return {boolean} isLast */ History.isLastSavedState = function(newState){ // Prepare var isLast = false; // Check if ( History.savedStates.length ) { var newId = newState.id, oldState = History.getLastSavedState(), oldId = oldState.id; // Check isLast = (newId === oldId); } // Return return isLast; }; /** * History.saveState * Push a State * @param {Object} newState * @return {boolean} changed */ History.saveState = function(newState){ // Check Hash if ( History.isLastSavedState(newState) ) { return false; } // Push the State History.savedStates.push(History.cloneObject(newState)); // Return true return true; }; /** * History.getStateByIndex() * Gets a state by the index * @param {integer} index * @return {Object} */ History.getStateByIndex = function(index){ // Prepare var State = null; // Handle if ( typeof index === 'undefined' ) { // Get the last inserted State = History.savedStates[History.savedStates.length-1]; } else if ( index < 0 ) { // Get from the end State = History.savedStates[History.savedStates.length+index]; } else { // Get from the beginning State = History.savedStates[index]; } // Return State return State; }; // ---------------------------------------------------------------------- // Hash Helpers /** * History.getHash() * Gets the current document hash * @return {string} */ History.getHash = function(){ var hash = History.unescapeHash(document.location.hash); return hash; }; /** * History.unescapeString() * Unescape a string * @param {String} str * @return {string} */ History.unescapeString = function(str){ // Prepare var result = str; // Unescape hash var tmp; while ( true ) { tmp = window.unescape(result); if ( tmp === result ) { break; } result = tmp; } // Return result return result; }; /** * History.unescapeHash() * normalize and Unescape a Hash * @param {String} hash * @return {string} */ History.unescapeHash = function(hash){ // Prepare var result = History.normalizeHash(hash); // Unescape hash result = History.unescapeString(result); // Return result return result; }; /** * History.normalizeHash() * normalize a hash across browsers * @return {string} */ History.normalizeHash = function(hash){ var result = hash.replace(/[^#]*#/,'').replace(/#.*/, ''); // Return result return result; }; /** * History.setHash(hash) * Sets the document hash * @param {string} hash * @return {History} */ History.setHash = function(hash,queue){ // Handle Queueing if ( queue !== false && History.busy() ) { // Wait + Push to Queue //History.debug('History.setHash: we must wait', arguments); History.pushQueue({ scope: History, callback: History.setHash, args: arguments, queue: queue }); return false; } // Log //History.debug('History.setHash: called',hash); // Prepare var adjustedHash = History.escapeHash(hash); // Make Busy + Continue History.busy(true); // Check if hash is a state var State = History.extractState(hash,true); if ( State && !History.emulated.pushState ) { // Hash is a state so skip the setHash //History.debug('History.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments); // PushState History.pushState(State.data,State.title,State.url,false); } else if ( document.location.hash !== adjustedHash ) { // Hash is a proper hash, so apply it // Handle browser bugs if ( History.bugs.setHash ) { // Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249 // Fetch the base page var pageUrl = History.getPageUrl(); // Safari hash apply History.pushState(null,null,pageUrl+'#'+adjustedHash,false); } else { // Normal hash apply document.location.hash = adjustedHash; } } // Chain return History; }; /** * History.escape() * normalize and Escape a Hash * @return {string} */ History.escapeHash = function(hash){ var result = History.normalizeHash(hash); // Escape hash result = window.escape(result); // IE6 Escape Bug if ( !History.bugs.hashEscape ) { // Restore common parts result = result .replace(/\%21/g,'!') .replace(/\%26/g,'&') .replace(/\%3D/g,'=') .replace(/\%3F/g,'?'); } // Return result return result; }; /** * History.getHashByUrl(url) * Extracts the Hash from a URL * @param {string} url * @return {string} url */ History.getHashByUrl = function(url){ // Extract the hash var hash = String(url) .replace(/([^#]*)#?([^#]*)#?(.*)/, '$2') ; // Unescape hash hash = History.unescapeHash(hash); // Return hash return hash; }; /** * History.setTitle(title) * Applies the title to the document * @param {State} newState * @return {Boolean} */ History.setTitle = function(newState){ // Prepare var title = newState.title; // Initial if ( !title ) { var firstState = History.getStateByIndex(0); if ( firstState && firstState.url === newState.url ) { title = firstState.title||History.options.initialTitle; } } // Apply try { document.getElementsByTagName('title')[0].innerHTML = title.replace('<','&lt;').replace('>','&gt;').replace(' & ',' &amp; '); } catch ( Exception ) { } document.title = title; // Chain return History; }; // ---------------------------------------------------------------------- // Queueing /** * History.queues * The list of queues to use * First In, First Out */ History.queues = []; /** * History.busy(value) * @param {boolean} value [optional] * @return {boolean} busy */ History.busy = function(value){ // Apply if ( typeof value !== 'undefined' ) { //History.debug('History.busy: changing ['+(History.busy.flag||false)+'] to ['+(value||false)+']', History.queues.length); History.busy.flag = value; } // Default else if ( typeof History.busy.flag === 'undefined' ) { History.busy.flag = false; } // Queue if ( !History.busy.flag ) { // Execute the next item in the queue clearTimeout(History.busy.timeout); var fireNext = function(){ if ( History.busy.flag ) return; for ( var i=History.queues.length-1; i >= 0; --i ) { var queue = History.queues[i]; if ( queue.length === 0 ) continue; var item = queue.shift(); History.fireQueueItem(item); History.busy.timeout = setTimeout(fireNext,History.options.busyDelay); } }; History.busy.timeout = setTimeout(fireNext,History.options.busyDelay); } // Return return History.busy.flag; }; /** * History.fireQueueItem(item) * Fire a Queue Item * @param {Object} item * @return {Mixed} result */ History.fireQueueItem = function(item){ return item.callback.apply(item.scope||History,item.args||[]); }; /** * History.pushQueue(callback,args) * Add an item to the queue * @param {Object} item [scope,callback,args,queue] */ History.pushQueue = function(item){ // Prepare the queue History.queues[item.queue||0] = History.queues[item.queue||0]||[]; // Add to the queue History.queues[item.queue||0].push(item); // Chain return History; }; /** * History.queue (item,queue), (func,queue), (func), (item) * Either firs the item now if not busy, or adds it to the queue */ History.queue = function(item,queue){ // Prepare if ( typeof item === 'function' ) { item = { callback: item }; } if ( typeof queue !== 'undefined' ) { item.queue = queue; } // Handle if ( History.busy() ) { History.pushQueue(item); } else { History.fireQueueItem(item); } // Chain return History; }; /** * History.clearQueue() * Clears the Queue */ History.clearQueue = function(){ History.busy.flag = false; History.queues = []; return History; }; // ---------------------------------------------------------------------- // IE Bug Fix /** * History.stateChanged * States whether or not the state has changed since the last double check was initialised */ History.stateChanged = false; /** * History.doubleChecker * Contains the timeout used for the double checks */ History.doubleChecker = false; /** * History.doubleCheckComplete() * Complete a double check * @return {History} */ History.doubleCheckComplete = function(){ // Update History.stateChanged = true; // Clear History.doubleCheckClear(); // Chain return History; }; /** * History.doubleCheckClear() * Clear a double check * @return {History} */ History.doubleCheckClear = function(){ // Clear if ( History.doubleChecker ) { clearTimeout(History.doubleChecker); History.doubleChecker = false; } // Chain return History; }; /** * History.doubleCheck() * Create a double check * @return {History} */ History.doubleCheck = function(tryAgain){ // Reset History.stateChanged = false; History.doubleCheckClear(); // Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does) // Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940 if ( History.bugs.ieDoubleCheck ) { // Apply Check History.doubleChecker = setTimeout( function(){ History.doubleCheckClear(); if ( !History.stateChanged ) { //History.debug('History.doubleCheck: State has not yet changed, trying again', arguments); // Re-Attempt tryAgain(); } return true; }, History.options.doubleCheckInterval ); } // Chain return History; }; // ---------------------------------------------------------------------- // Safari Bug Fix /** * History.safariStatePoll() * Poll the current state * @return {History} */ History.safariStatePoll = function(){ // Poll the URL // Get the Last State which has the new URL var urlState = History.extractState(document.location.href), newState; // Check for a difference if ( !History.isLastSavedState(urlState) ) { newState = urlState; } else { return; } // Check if we have a state with that url // If not create it if ( !newState ) { //History.debug('History.safariStatePoll: new'); newState = History.createStateObject(); } // Apply the New State //History.debug('History.safariStatePoll: trigger'); History.Adapter.trigger(window,'popstate'); // Chain return History; }; // ---------------------------------------------------------------------- // State Aliases /** * History.back(queue) * Send the browser history back one item * @param {Integer} queue [optional] */ History.back = function(queue){ //History.debug('History.back: called', arguments); // Handle Queueing if ( queue !== false && History.busy() ) { // Wait + Push to Queue //History.debug('History.back: we must wait', arguments); History.pushQueue({ scope: History, callback: History.back, args: arguments, queue: queue }); return false; } // Make Busy + Continue History.busy(true); // Fix certain browser bugs that prevent the state from changing History.doubleCheck(function(){ History.back(false); }); // Go back history.go(-1); // End back closure return true; }; /** * History.forward(queue) * Send the browser history forward one item * @param {Integer} queue [optional] */ History.forward = function(queue){ //History.debug('History.forward: called', arguments); // Handle Queueing if ( queue !== false && History.busy() ) { // Wait + Push to Queue //History.debug('History.forward: we must wait', arguments); History.pushQueue({ scope: History, callback: History.forward, args: arguments, queue: queue }); return false; } // Make Busy + Continue History.busy(true); // Fix certain browser bugs that prevent the state from changing History.doubleCheck(function(){ History.forward(false); }); // Go forward history.go(1); // End forward closure return true; }; /** * History.go(index,queue) * Send the browser history back or forward index times * @param {Integer} queue [optional] */ History.go = function(index,queue){ //History.debug('History.go: called', arguments); // Prepare var i; // Handle if ( index > 0 ) { // Forward for ( i=1; i<=index; ++i ) { History.forward(queue); } } else if ( index < 0 ) { // Backward for ( i=-1; i>=index; --i ) { History.back(queue); } } else { throw new Error('History.go: History.go requires a positive or negative integer passed.'); } // Chain return History; }; // ---------------------------------------------------------------------- // Initialise /** * Create the initial State */ History.saveState(History.storeState(History.extractState(document.location.href,true))); /** * Bind for Saving Store */ if ( amplify ) { History.onUnload = function(){ // Prepare var currentStore = amplify.store('History.store')||{}, item; // Ensure currentStore.idToState = currentStore.idToState || {}; currentStore.urlToId = currentStore.urlToId || {}; currentStore.stateToId = currentStore.stateToId || {}; // Sync for ( item in History.idToState ) { if ( !History.idToState.hasOwnProperty(item) ) { continue; } currentStore.idToState[item] = History.idToState[item]; } for ( item in History.urlToId ) { if ( !History.urlToId.hasOwnProperty(item) ) { continue; } currentStore.urlToId[item] = History.urlToId[item]; } for ( item in History.stateToId ) { if ( !History.stateToId.hasOwnProperty(item) ) { continue; } currentStore.stateToId[item] = History.stateToId[item]; } // Update History.store = currentStore; // Store amplify.store('History.store',currentStore); }; // For Internet Explorer setInterval(History.onUnload,History.options.storeInterval); // For Other Browsers History.Adapter.bind(window,'beforeunload',History.onUnload); History.Adapter.bind(window,'unload',History.onUnload); // Both are enabled for consistency } // ---------------------------------------------------------------------- // HTML5 State Support if ( History.emulated.pushState ) { /* * Provide Skeleton for HTML4 Browsers */ // Prepare var emptyFunction = function(){}; History.pushState = History.pushState||emptyFunction; History.replaceState = History.replaceState||emptyFunction; } else { /* * Use native HTML5 History API Implementation */ /** * History.onPopState(event,extra) * Refresh the Current State */ History.onPopState = function(event){ // Reset the double check History.doubleCheckComplete(); // Check for a Hash, and handle apporiatly var currentHash = History.getHash(); if ( currentHash ) { // Expand Hash var currentState = History.extractState(currentHash||document.location.href,true); if ( currentState ) { // We were able to parse it, it must be a State! // Let's forward to replaceState //History.debug('History.onPopState: state anchor', currentHash, currentState); History.replaceState(currentState.data, currentState.title, currentState.url, false); } else { // Traditional Anchor //History.debug('History.onPopState: traditional anchor', currentHash); History.Adapter.trigger(window,'anchorchange'); History.busy(false); } // We don't care for hashes History.expectedStateId = false; return false; } // Prepare var newState = false; // Prepare event = event||{}; if ( typeof event.state === 'undefined' ) { // jQuery if ( typeof event.originalEvent !== 'undefined' && typeof event.originalEvent.state !== 'undefined' ) { event.state = event.originalEvent.state||false; } // MooTools else if ( typeof event.event !== 'undefined' && typeof event.event.state !== 'undefined' ) { event.state = event.event.state||false; } } // Ensure event.state = (event.state||false); // Fetch State if ( event.state ) { // Vanilla: Back/forward button was used newState = History.getStateById(event.state); } else if ( History.expectedStateId ) { // Vanilla: A new state was pushed, and popstate was called manually newState = History.getStateById(History.expectedStateId); } else { // Initial State newState = History.extractState(document.location.href); } // The State did not exist in our store if ( !newState ) { // Regenerate the State newState = History.createStateObject(null,null,document.location.href); } // Clean History.expectedStateId = false; // Check if we are the same state if ( History.isLastSavedState(newState) ) { // There has been no change (just the page's hash has finally propagated) //History.debug('History.onPopState: no change', newState, History.savedStates); History.busy(false); return false; } // Store the State History.storeState(newState); History.saveState(newState); // Force update of the title History.setTitle(newState); // Fire Our Event History.Adapter.trigger(window,'statechange'); History.busy(false); // Return true return true; }; History.Adapter.bind(window,'popstate',History.onPopState); /** * History.pushState(data,title,url) * Add a new State to the history object, become it, and trigger onpopstate * We have to trigger for HTML4 compatibility * @param {object} data * @param {string} title * @param {string} url * @return {true} */ History.pushState = function(data,title,url,queue){ //History.debug('History.pushState: called', arguments); // Check the State if ( History.getHashByUrl(url) && History.emulated.pushState ) { throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).'); } // Handle Queueing if ( queue !== false && History.busy() ) { // Wait + Push to Queue //History.debug('History.pushState: we must wait', arguments); History.pushQueue({ scope: History, callback: History.pushState, args: arguments, queue: queue }); return false; } // Make Busy + Continue History.busy(true); // Create the newState var newState = History.createStateObject(data,title,url); // Check it if ( History.isLastSavedState(newState) ) { // Won't be a change History.busy(false); } else { // Store the newState History.storeState(newState); History.expectedStateId = newState.id; // Push the newState history.pushState(newState.id,newState.title,newState.url); // Fire HTML5 Event History.Adapter.trigger(window,'popstate'); } // End pushState closure return true; }; /** * History.replaceState(data,title,url) * Replace the State and trigger onpopstate * We have to trigger for HTML4 compatibility * @param {object} data * @param {string} title * @param {string} url * @return {true} */ History.replaceState = function(data,title,url,queue){ //History.debug('History.replaceState: called', arguments); // Check the State if ( History.getHashByUrl(url) && History.emulated.pushState ) { throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).'); } // Handle Queueing if ( queue !== false && History.busy() ) { // Wait + Push to Queue //History.debug('History.replaceState: we must wait', arguments); History.pushQueue({ scope: History, callback: History.replaceState, args: arguments, queue: queue }); return false; } // Make Busy + Continue History.busy(true); // Create the newState var newState = History.createStateObject(data,title,url); // Check it if ( History.isLastSavedState(newState) ) { // Won't be a change History.busy(false); } else { // Store the newState History.storeState(newState); History.expectedStateId = newState.id; // Push the newState history.replaceState(newState.id,newState.title,newState.url); // Fire HTML5 Event History.Adapter.trigger(window,'popstate'); } // End replaceState closure return true; }; // Be aware, the following is only for native pushState implementations // If you are wanting to include something for all browsers // Then include it above this if block /** * Setup Safari Fix */ if ( History.bugs.safariPoll ) { setInterval(History.safariStatePoll, History.options.safariPollInterval); } /** * Ensure Cross Browser Compatibility */ if ( navigator.vendor === 'Apple Computer, Inc.' || (navigator.appCodeName||'') === 'Mozilla' ) { /** * Fix Safari HashChange Issue */ // Setup Alias History.Adapter.bind(window,'hashchange',function(){ History.Adapter.trigger(window,'popstate'); }); // Initialise Alias if ( History.getHash() ) { History.Adapter.onDomLoad(function(){ History.Adapter.trigger(window,'hashchange'); }); } } } // !History.emulated.pushState }; // History.initCore // Try and Initialise History History.init(); })(window);
require('dotenv').config(); const express = require('express'); const router = express.Router(); const { check } = require('express-validator'); const { validate } = require('../middleware/validate'); const { checkAuth } = require('../middleware/auth'); const { authenticateUser, getMe } = require('../controllers/auth'); /** * Authenticate user and send token */ router.post( '/', [ check('email', 'Укажите корректный адрес электронной почты').isEmail(), check('password', 'Укажите верный пароль').not().isEmpty().exists(), ], validate, authenticateUser ); /** * Send user data from database */ router.get('/', checkAuth, getMe); module.exports = router;
module.exports={D:{"4":0.007057,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0.035285,"23":0.021171,"24":0.007057,"25":0.007057,"26":0,"27":0.021171,"28":0,"29":0.007057,"30":0.014114,"31":0.007057,"32":0.007057,"33":0.014114,"34":0.014114,"35":0,"36":0.007057,"37":0.007057,"38":0.021171,"39":0.007057,"40":0.007057,"41":0.007057,"42":0.007057,"43":0.014114,"44":0.021171,"45":0.007057,"46":0.042342,"47":0.028228,"48":0.007057,"49":0.176425,"50":0.028228,"51":0.014114,"52":0.028228,"53":0.056456,"54":0.084684,"55":0.014114,"56":0.042342,"57":0.042342,"58":0.049399,"59":0.035285,"60":0.077627,"61":0.035285,"62":0.21171,"63":0.197596,"64":0.14114,"65":0.218767,"66":2.102986,"67":3.17565,"68":0.007057,"69":0,"70":0},C:{"2":0.007057,"3":0,"4":0.007057,"5":0,"6":0.007057,"7":0.014114,"8":0,"9":0,"10":0.007057,"11":0.007057,"12":0.007057,"13":0.007057,"14":0,"15":0.014114,"16":0.007057,"17":0.035285,"18":0.007057,"19":0.014114,"20":0.028228,"21":0.035285,"22":0.007057,"23":0.098798,"24":0.042342,"25":0.134083,"26":0.324622,"27":0.797441,"28":0.028228,"29":0.07057,"30":0.049399,"31":0.049399,"32":0.049399,"33":0.331679,"34":0.529275,"35":0.148197,"36":0.077627,"37":0.359907,"38":0.56456,"39":0.183482,"40":0.451648,"41":0.232881,"42":0.225824,"43":0.733928,"44":0.155254,"45":1.90539,"46":0.536332,"47":1.242032,"48":0.543389,"49":0.684529,"50":1.192633,"51":0.832726,"52":1.714851,"53":0.451648,"54":1.877162,"55":0.416363,"56":1.213804,"57":2.18767,"58":1.213804,"59":2.491121,"60":14.290425,"61":0.98798,"62":0.07057,"3.5":0.007057,"3.6":0.063513},F:{"9":0,"11":0,"12":0,"15":0,"16":0,"17":0.007057,"18":0,"19":0,"20":0,"21":0,"22":0.007057,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0.028228,"30":0,"31":0,"32":0,"33":0.014114,"34":0.007057,"35":0,"36":0.014114,"37":0.014114,"38":0,"39":0,"40":0,"41":0,"42":0.021171,"43":0,"44":0,"45":0.007057,"46":0.007057,"47":0.007057,"48":0.021171,"49":0.007057,"50":0.007057,"51":0.014114,"52":0.021171,"53":0.557503,"9.5-9.6":0,"10.0-10.1":0.007057,"10.5":0,"10.6":0,"11.1":0,"11.5":0,"11.6":0.007057,"12.1":0.014114},E:{"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0.014114,"11":0.091741,"12":0,_:"0","3.1":0,"3.2":0,"5.1":0.007057,"6.1":0,"7.1":0,"9.1":0.084684,"10.1":0.056456,"11.1":0.105855},G:{"8":0.00328459973977,"12":0.00821149934941,"3.2":0.00027371664498,"4.0-4.1":0,"4.2-4.3":0.000547433289961,"5.0-5.1":0.00410574967471,"6.0-6.1":0.00218973315984,"7.0-7.1":0.0114960990892,"8.1-8.4":0.0172441486338,"9.0-9.2":0.0131383989591,"9.3":0.0785566771094,"10.0-10.2":0.0862207431689,"10.3":0.197623417676,"11.0-11.2":0.443694681513,"11.3-11.4":1.86811610199},I:{"3":0,"4":0,_:"67","2.1":0,"2.2":0,"2.3":0,"4.1":0.182215858647,"4.2-4.3":0.415825933835,"4.4":1.54182649624,"4.4.3-4.4.4":0.967145711278},A:{"6":0,"7":0,"8":0.098798,"9":0.021171,"10":0.035285,"11":0.7057,"5.5":0},K:{_:"0 10 11 12 11.1 11.5 12.1"},B:{"12":0.049399,"13":0.091741,"14":0.119969,"15":0.07057,"16":0.14114,"17":0.077627,_:"18"},P:{"4":0.418206988636,"5":0.0714011931818,"6.2":0.285604772727,_:"7.2"},J:{"7":0.026487,"10":0.105948},N:{"10":0.0435564,"11":0.0653346},M:{"0":1.268433},Q:{_:"1.2"},O:{"0":0.526797},H:{"0":0.392860159794},L:{"0":39.374759},R:{_:"0"}};
# # Instant Python # $Id: tkColorChooser.py,v 1.2 2002/04/12 09:44:07 sof34 Exp $ # # tk common colour chooser dialogue # # this module provides an interface to the native color dialogue # available in Tk 4.2 and newer. # # written by Fredrik Lundh, May 1997 # # fixed initialcolor handling in August 1998 # # # options (all have default values): # # - initialcolor: colour to mark as selected when dialog is displayed # (given as an RGB triplet or a Tk color string) # # - parent: which window to place the dialog on top of # # - title: dialog title # from tkCommonDialog import Dialog # # color chooser class class Chooser(Dialog): "Ask for a color" command = "tk_chooseColor" def _fixoptions(self): try: # make sure initialcolor is a tk color string color = self.options["initialcolor"] if type(color) == type(()): # assume an RGB triplet self.options["initialcolor"] = "#%02x%02x%02x" % color except KeyError: pass def _fixresult(self, widget, result): # to simplify application code, the color chooser returns # an RGB tuple together with the Tk color string if not result: return None, None # canceled r, g, b = widget.winfo_rgb(result) return (r/256, g/256, b/256), result # # convenience stuff def askcolor(color = None, **options): "Ask for a color" if color: options = options.copy() options["initialcolor"] = color return apply(Chooser, (), options).show() # -------------------------------------------------------------------- # test stuff if __name__ == "__main__": print "color", askcolor()
define("0d910c1c-13b9-4e1c-9aa4-b008c5e42d7d_16.8.5", [], function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "mwqp"); /******/ }) /************************************************************************/ /******/ ({ /***/ "04mm": /*!*************************************************************************************************************************************************!*\ !*** C:/agent/1/_work/5/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/prop-types/15.6.0/node_modules/prop-types/checkPropTypes.js ***! \*************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ if (true) { var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "ypis"); var warning = __webpack_require__(/*! fbjs/lib/warning */ "Q+bF"); var ReactPropTypesSecret = __webpack_require__(/*! ./lib/ReactPropTypesSecret */ "DVb/"); var loggedTypeFailures = {}; } /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?Function} getStack Returns the component stack. * @private */ function checkPropTypes(typeSpecs, values, location, componentName, getStack) { if (true) { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. invariant(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'the `prop-types` package, but received `%s`.', componentName || 'React class', location, typeSpecName, typeof typeSpecs[typeSpecName]); error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); } catch (ex) { error = ex; } warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error); if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var stack = getStack ? getStack() : ''; warning(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : ''); } } } } } module.exports = checkPropTypes; /***/ }), /***/ "1FaY": /*!********************************************************************************************************************************************************!*\ !*** C:/agent/1/_work/5/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/create-react-class/15.6.3/node_modules/create-react-class/index.js ***! \********************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ var React = __webpack_require__(/*! react */ "3wdl"); var factory = __webpack_require__(/*! ./factory */ "U8ve"); if (typeof React === 'undefined') { throw Error( 'create-react-class could not find the React object. If you are using script tags, ' + 'make sure that React is being loaded before create-react-class.' ); } // Hack to grab NoopUpdateQueue from isomorphic React var ReactNoopUpdateQueue = new React.Component().updater; module.exports = factory( React.Component, React.isValidElement, ReactNoopUpdateQueue ); /***/ }), /***/ "2Jnp": /*!**********************************************************************************************************************************************************!*\ !*** C:/agent/1/_work/5/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/prop-types/15.6.0/node_modules/prop-types/factoryWithTypeCheckers.js ***! \**********************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var emptyFunction = __webpack_require__(/*! fbjs/lib/emptyFunction */ "xvdx"); var invariant = __webpack_require__(/*! fbjs/lib/invariant */ "ypis"); var warning = __webpack_require__(/*! fbjs/lib/warning */ "Q+bF"); var assign = __webpack_require__(/*! object-assign */ "sjay"); var ReactPropTypesSecret = __webpack_require__(/*! ./lib/ReactPropTypesSecret */ "DVb/"); var checkPropTypes = __webpack_require__(/*! ./checkPropTypes */ "04mm"); module.exports = function(isValidElement, throwOnDirectAccess) { /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; // Important! // Keep this list in sync with production version in `./factoryWithThrowingShims.js`. var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), symbol: createPrimitiveTypeChecker('symbol'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker, exact: createStrictShapeTypeChecker, }; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ /*eslint-disable no-self-compare*/ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /*eslint-enable no-self-compare*/ /** * We use an Error-like object for backward compatibility as people may call * PropTypes directly and inspect their output. However, we don't use real * Errors anymore. We don't inspect their stack anyway, and creating them * is prohibitively expensive if they are created too often, such as what * happens in oneOfType() for any type before the one that matched. */ function PropTypeError(message) { this.message = message; this.stack = ''; } // Make `instanceof Error` still work for returned errors. PropTypeError.prototype = Error.prototype; function createChainableTypeChecker(validate) { if (true) { var manualPropTypeCallCache = {}; var manualPropTypeWarningCount = 0; } function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (secret !== ReactPropTypesSecret) { if (throwOnDirectAccess) { // New behavior only for users of `prop-types` package invariant( false, 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use `PropTypes.checkPropTypes()` to call them. ' + 'Read more at http://fb.me/use-check-prop-types' ); } else if ( true && typeof console !== 'undefined') { // Old behavior for people using React.PropTypes var cacheKey = componentName + ':' + propName; if ( !manualPropTypeCallCache[cacheKey] && // Avoid spamming the console because they are often not actionable except for lib authors manualPropTypeWarningCount < 3 ) { warning( false, 'You are manually calling a React.PropTypes validation ' + 'function for the `%s` prop on `%s`. This is deprecated ' + 'and will throw in the standalone `prop-types` package. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.', propFullName, componentName ); manualPropTypeCallCache[cacheKey] = true; manualPropTypeWarningCount++; } } } if (props[propName] == null) { if (isRequired) { if (props[propName] === null) { return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.')); } return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName, secret) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunction.thatReturnsNull); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!isValidElement(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.')); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { true ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : undefined; return emptyFunction.thatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (is(propValue, expectedValues[i])) { return null; } } var valuesString = JSON.stringify(expectedValues); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { if (propValue.hasOwnProperty(key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { true ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : undefined; return emptyFunction.thatReturnsNull; } for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (typeof checker !== 'function') { warning( false, 'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' + 'received %s at index %s.', getPostfixForTypeWarning(checker), i ); return emptyFunction.thatReturnsNull; } } function validate(props, propName, componentName, location, propFullName) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) { return null; } } return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createStrictShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } // We need to check all keys in case some are required but missing from // props. var allKeys = assign({}, props[propName], shapeTypes); for (var key in allKeys) { var checker = shapeTypes[key]; if (!checker) { return new PropTypeError( 'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' + '\nBad object: ' + JSON.stringify(props[propName], null, ' ') + '\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ') ); } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } function isSymbol(propType, propValue) { // Native Symbol. if (propType === 'symbol') { return true; } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' if (propValue['@@toStringTag'] === 'Symbol') { return true; } // Fallback for non-spec compliant Symbols which are polyfilled. if (typeof Symbol === 'function' && propValue instanceof Symbol) { return true; } return false; } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } if (isSymbol(propType, propValue)) { return 'symbol'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { if (typeof propValue === 'undefined' || propValue === null) { return '' + propValue; } var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns a string that is postfixed to a warning about an invalid type. // For example, "undefined" or "of type array" function getPostfixForTypeWarning(value) { var type = getPreciseType(value); switch (type) { case 'array': case 'object': return 'an ' + type; case 'boolean': case 'date': case 'regexp': return 'a ' + type; default: return type; } } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } ReactPropTypes.checkPropTypes = checkPropTypes; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; /***/ }), /***/ "3wdl": /*!******************************************************************************************************************************!*\ !*** C:/agent/1/_work/5/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/react/16.8.5/node_modules/react/index.js ***! \******************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; if (false) {} else { module.exports = __webpack_require__(/*! ./cjs/react.development.js */ "8En3"); } /***/ }), /***/ "8En3": /*!**********************************************************************************************************************************************!*\ !*** C:/agent/1/_work/5/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/react/16.8.5/node_modules/react/cjs/react.development.js ***! \**********************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** @license React v16.8.5 * react.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ if (true) { (function() { 'use strict'; var _assign = __webpack_require__(/*! object-assign */ "sjay"); var checkPropTypes = __webpack_require__(/*! prop-types/checkPropTypes */ "jvHV"); // TODO: this is special because it gets imported during build. var ReactVersion = '16.8.5'; // The Symbol used to tag the ReactElement-like types. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var hasSymbol = typeof Symbol === 'function' && Symbol.for; var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7; var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca; var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb; var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc; var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2; var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd; var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf; var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0; var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1; var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3; var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4; var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== 'object') { return null; } var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; if (typeof maybeIterator === 'function') { return maybeIterator; } return null; } /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var validateFormat = function () {}; { validateFormat = function (format) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } }; } function invariant(condition, format, a, b, c, d, e, f) { validateFormat(format); if (!condition) { var error = void 0; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } // Relying on the `invariant()` implementation lets us // preserve the format and params in the www builds. /** * Forked from fbjs/warning: * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js * * Only change is we use console.warn instead of console.error, * and do nothing when 'console' is not supported. * This really simplifies the code. * --- * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var lowPriorityWarning = function () {}; { var printWarning = function (format) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.warn(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; lowPriorityWarning = function (condition, format) { if (format === undefined) { throw new Error('`lowPriorityWarning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (!condition) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } printWarning.apply(undefined, [format].concat(args)); } }; } var lowPriorityWarning$1 = lowPriorityWarning; /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warningWithoutStack = function () {}; { warningWithoutStack = function (condition, format) { for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } if (format === undefined) { throw new Error('`warningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument'); } if (args.length > 8) { // Check before the condition to catch violations early. throw new Error('warningWithoutStack() currently supports at most 8 arguments.'); } if (condition) { return; } if (typeof console !== 'undefined') { var argsWithFormat = args.map(function (item) { return '' + item; }); argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it // breaks IE9: https://github.com/facebook/react/issues/13610 Function.prototype.apply.call(console.error, console, argsWithFormat); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); throw new Error(message); } catch (x) {} }; } var warningWithoutStack$1 = warningWithoutStack; var didWarnStateUpdateForUnmountedComponent = {}; function warnNoop(publicInstance, callerName) { { var _constructor = publicInstance.constructor; var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass'; var warningKey = componentName + '.' + callerName; if (didWarnStateUpdateForUnmountedComponent[warningKey]) { return; } warningWithoutStack$1(false, "Can't call %s on a component that is not yet mounted. " + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName); didWarnStateUpdateForUnmountedComponent[warningKey] = true; } } /** * This is the abstract API for an update queue. */ var ReactNoopUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { return false; }, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {?function} callback Called after component is updated. * @param {?string} callerName name of the calling function in the public API. * @internal */ enqueueForceUpdate: function (publicInstance, callback, callerName) { warnNoop(publicInstance, 'forceUpdate'); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @param {?function} callback Called after component is updated. * @param {?string} callerName name of the calling function in the public API. * @internal */ enqueueReplaceState: function (publicInstance, completeState, callback, callerName) { warnNoop(publicInstance, 'replaceState'); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @param {?function} callback Called after component is updated. * @param {?string} Name of the calling function in the public API. * @internal */ enqueueSetState: function (publicInstance, partialState, callback, callerName) { warnNoop(publicInstance, 'setState'); } }; var emptyObject = {}; { Object.freeze(emptyObject); } /** * Base class helpers for the updating state of a component. */ function Component(props, context, updater) { this.props = props; this.context = context; // If a component has string refs, we will assign a different object later. this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } Component.prototype.isReactComponent = {}; /** * Sets a subset of the state. Always use this to mutate * state. You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * There is no guarantee that calls to `setState` will run synchronously, * as they may eventually be batched together. You can provide an optional * callback that will be executed when the call to setState is actually * completed. * * When a function is provided to setState, it will be called at some point in * the future (not synchronously). It will be called with the up to date * component arguments (state, props, context). These values can be different * from this.* because your function may be called after receiveProps but before * shouldComponentUpdate, and this new state, props, and context will not yet be * assigned to this. * * @param {object|function} partialState Next partial state or function to * produce next partial state to be merged with current state. * @param {?function} callback Called after state is updated. * @final * @protected */ Component.prototype.setState = function (partialState, callback) { !(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? invariant(false, 'setState(...): takes an object of state variables to update or a function which returns an object of state variables.') : void 0; this.updater.enqueueSetState(this, partialState, callback, 'setState'); }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {?function} callback Called after update is complete. * @final * @protected */ Component.prototype.forceUpdate = function (callback) { this.updater.enqueueForceUpdate(this, callback, 'forceUpdate'); }; /** * Deprecated APIs. These APIs used to exist on classic React classes but since * we would like to deprecate them, we're not going to move them over to this * modern base class. Instead, we define a getter that warns if it's accessed. */ { var deprecatedAPIs = { isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'], replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).'] }; var defineDeprecationWarning = function (methodName, info) { Object.defineProperty(Component.prototype, methodName, { get: function () { lowPriorityWarning$1(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]); return undefined; } }); }; for (var fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } function ComponentDummy() {} ComponentDummy.prototype = Component.prototype; /** * Convenience component with default shallow equality check for sCU. */ function PureComponent(props, context, updater) { this.props = props; this.context = context; // If a component has string refs, we will assign a different object later. this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; } var pureComponentPrototype = PureComponent.prototype = new ComponentDummy(); pureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods. _assign(pureComponentPrototype, Component.prototype); pureComponentPrototype.isPureReactComponent = true; // an immutable object with a single mutable value function createRef() { var refObject = { current: null }; { Object.seal(refObject); } return refObject; } /** * Keeps track of the current dispatcher. */ var ReactCurrentDispatcher = { /** * @internal * @type {ReactComponent} */ current: null }; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; var BEFORE_SLASH_RE = /^(.*)[\\\/]/; var describeComponentFrame = function (name, source, ownerName) { var sourceInfo = ''; if (source) { var path = source.fileName; var fileName = path.replace(BEFORE_SLASH_RE, ''); { // In DEV, include code for a common special case: // prefer "folder/index.js" instead of just "index.js". if (/^index\./.test(fileName)) { var match = path.match(BEFORE_SLASH_RE); if (match) { var pathBeforeSlash = match[1]; if (pathBeforeSlash) { var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, ''); fileName = folderName + '/' + fileName; } } } } sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')'; } else if (ownerName) { sourceInfo = ' (created by ' + ownerName + ')'; } return '\n in ' + (name || 'Unknown') + sourceInfo; }; var Resolved = 1; function refineResolvedLazyComponent(lazyComponent) { return lazyComponent._status === Resolved ? lazyComponent._result : null; } function getWrappedName(outerType, innerType, wrapperName) { var functionName = innerType.displayName || innerType.name || ''; return outerType.displayName || (functionName !== '' ? wrapperName + '(' + functionName + ')' : wrapperName); } function getComponentName(type) { if (type == null) { // Host root, text node or just invalid type. return null; } { if (typeof type.tag === 'number') { warningWithoutStack$1(false, 'Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.'); } } if (typeof type === 'function') { return type.displayName || type.name || null; } if (typeof type === 'string') { return type; } switch (type) { case REACT_CONCURRENT_MODE_TYPE: return 'ConcurrentMode'; case REACT_FRAGMENT_TYPE: return 'Fragment'; case REACT_PORTAL_TYPE: return 'Portal'; case REACT_PROFILER_TYPE: return 'Profiler'; case REACT_STRICT_MODE_TYPE: return 'StrictMode'; case REACT_SUSPENSE_TYPE: return 'Suspense'; } if (typeof type === 'object') { switch (type.$$typeof) { case REACT_CONTEXT_TYPE: return 'Context.Consumer'; case REACT_PROVIDER_TYPE: return 'Context.Provider'; case REACT_FORWARD_REF_TYPE: return getWrappedName(type, type.render, 'ForwardRef'); case REACT_MEMO_TYPE: return getComponentName(type.type); case REACT_LAZY_TYPE: { var thenable = type; var resolvedThenable = refineResolvedLazyComponent(thenable); if (resolvedThenable) { return getComponentName(resolvedThenable); } } } } return null; } var ReactDebugCurrentFrame = {}; var currentlyValidatingElement = null; function setCurrentlyValidatingElement(element) { { currentlyValidatingElement = element; } } { // Stack implementation injected by the current renderer. ReactDebugCurrentFrame.getCurrentStack = null; ReactDebugCurrentFrame.getStackAddendum = function () { var stack = ''; // Add an extra top frame while an element is being validated if (currentlyValidatingElement) { var name = getComponentName(currentlyValidatingElement.type); var owner = currentlyValidatingElement._owner; stack += describeComponentFrame(name, currentlyValidatingElement._source, owner && getComponentName(owner.type)); } // Delegate to the injected renderer-specific implementation var impl = ReactDebugCurrentFrame.getCurrentStack; if (impl) { stack += impl() || ''; } return stack; }; } var ReactSharedInternals = { ReactCurrentDispatcher: ReactCurrentDispatcher, ReactCurrentOwner: ReactCurrentOwner, // Used by renderers to avoid bundling object-assign twice in UMD bundles: assign: _assign }; { _assign(ReactSharedInternals, { // These should not be included in production. ReactDebugCurrentFrame: ReactDebugCurrentFrame, // Shim for React DOM 16.0.0 which still destructured (but not used) this. // TODO: remove in React 17.0. ReactComponentTreeHook: {} }); } /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = warningWithoutStack$1; { warning = function (condition, format) { if (condition) { return; } var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; var stack = ReactDebugCurrentFrame.getStackAddendum(); // eslint-disable-next-line react-internal/warning-and-invariant-args for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } warningWithoutStack$1.apply(undefined, [false, format + '%s'].concat(args, [stack])); }; } var warning$1 = warning; var hasOwnProperty = Object.prototype.hasOwnProperty; var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown = void 0; var specialPropRefWarningShown = void 0; function hasValidRef(config) { { if (hasOwnProperty.call(config, 'ref')) { var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; if (getter && getter.isReactWarning) { return false; } } } return config.ref !== undefined; } function hasValidKey(config) { { if (hasOwnProperty.call(config, 'key')) { var getter = Object.getOwnPropertyDescriptor(config, 'key').get; if (getter && getter.isReactWarning) { return false; } } } return config.key !== undefined; } function defineKeyPropWarningGetter(props, displayName) { var warnAboutAccessingKey = function () { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; warningWithoutStack$1(false, '%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName); } }; warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, 'key', { get: warnAboutAccessingKey, configurable: true }); } function defineRefPropWarningGetter(props, displayName) { var warnAboutAccessingRef = function () { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; warningWithoutStack$1(false, '%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName); } }; warnAboutAccessingRef.isReactWarning = true; Object.defineProperty(props, 'ref', { get: warnAboutAccessingRef, configurable: true }); } /** * Factory method to create a new React element. This no longer adheres to * the class pattern, so do not use new to call it. Also, no instanceof check * will work. Instead test $$typeof field against Symbol.for('react.element') to check * if something is a React Element. * * @param {*} type * @param {*} key * @param {string|object} ref * @param {*} self A *temporary* helper to detect places where `this` is * different from the `owner` when React.createElement is called, so that we * can warn. We want to get rid of owner and replace string `ref`s with arrow * functions, and as long as `this` and owner are the same, there will be no * change in behavior. * @param {*} source An annotation object (added by a transpiler or otherwise) * indicating filename, line number, and/or other information. * @param {*} owner * @param {*} props * @internal */ var ReactElement = function (type, key, ref, self, source, owner, props) { var element = { // This tag allows us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type, key: key, ref: ref, props: props, // Record the component responsible for creating this element. _owner: owner }; { // The validation flag is currently mutative. We put it on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. element._store = {}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, writable: true, value: false }); // self and source are DEV only properties. Object.defineProperty(element, '_self', { configurable: false, enumerable: false, writable: false, value: self }); // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source }); if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; }; /** * Create and return a new ReactElement of the given type. * See https://reactjs.org/docs/react-api.html#createelement */ function createElement(type, config, children) { var propName = void 0; // Reserved names are extracted var props = {}; var key = null; var ref = null; var self = null; var source = null; if (config != null) { if (hasValidRef(config)) { ref = config.ref; } if (hasValidKey(config)) { key = '' + config.key; } self = config.__self === undefined ? null : config.__self; source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } { if (Object.freeze) { Object.freeze(childArray); } } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } { if (key || ref) { var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; if (key) { defineKeyPropWarningGetter(props, displayName); } if (ref) { defineRefPropWarningGetter(props, displayName); } } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); } /** * Return a function that produces ReactElements of a given type. * See https://reactjs.org/docs/react-api.html#createfactory */ function cloneAndReplaceKey(oldElement, newKey) { var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); return newElement; } /** * Clone and return a new ReactElement using element as the starting point. * See https://reactjs.org/docs/react-api.html#cloneelement */ function cloneElement(element, config, children) { !!(element === null || element === undefined) ? invariant(false, 'React.cloneElement(...): The argument must be a React element, but you passed %s.', element) : void 0; var propName = void 0; // Original props are copied var props = _assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Self is preserved since the owner is preserved. var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a // transpiler, and the original source is probably a better indicator of the // true owner. var source = element._source; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if (hasValidRef(config)) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (hasValidKey(config)) { key = '' + config.key; } // Remaining properties override existing props var defaultProps = void 0; if (element.type && element.type.defaultProps) { defaultProps = element.type.defaultProps; } for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { if (config[propName] === undefined && defaultProps !== undefined) { // Resolve default props props[propName] = defaultProps[propName]; } else { props[propName] = config[propName]; } } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return ReactElement(element.type, key, ref, self, source, owner, props); } /** * Verifies the object is a ReactElement. * See https://reactjs.org/docs/react-api.html#isvalidelement * @param {?object} object * @return {boolean} True if `object` is a ReactElement. * @final */ function isValidElement(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } var SEPARATOR = '.'; var SUBSEPARATOR = ':'; /** * Escape and wrap key so it is safe to use as a reactid * * @param {string} key to be escaped. * @return {string} the escaped key. */ function escape(key) { var escapeRegex = /[=:]/g; var escaperLookup = { '=': '=0', ':': '=2' }; var escapedString = ('' + key).replace(escapeRegex, function (match) { return escaperLookup[match]; }); return '$' + escapedString; } /** * TODO: Test that a single child and an array with one item have the same key * pattern. */ var didWarnAboutMaps = false; var userProvidedKeyEscapeRegex = /\/+/g; function escapeUserProvidedKey(text) { return ('' + text).replace(userProvidedKeyEscapeRegex, '$&/'); } var POOL_SIZE = 10; var traverseContextPool = []; function getPooledTraverseContext(mapResult, keyPrefix, mapFunction, mapContext) { if (traverseContextPool.length) { var traverseContext = traverseContextPool.pop(); traverseContext.result = mapResult; traverseContext.keyPrefix = keyPrefix; traverseContext.func = mapFunction; traverseContext.context = mapContext; traverseContext.count = 0; return traverseContext; } else { return { result: mapResult, keyPrefix: keyPrefix, func: mapFunction, context: mapContext, count: 0 }; } } function releaseTraverseContext(traverseContext) { traverseContext.result = null; traverseContext.keyPrefix = null; traverseContext.func = null; traverseContext.context = null; traverseContext.count = 0; if (traverseContextPool.length < POOL_SIZE) { traverseContextPool.push(traverseContext); } } /** * @param {?*} children Children tree container. * @param {!string} nameSoFar Name of the key path so far. * @param {!function} callback Callback to invoke with each child found. * @param {?*} traverseContext Used to pass information throughout the traversal * process. * @return {!number} The number of children in this subtree. */ function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) { var type = typeof children; if (type === 'undefined' || type === 'boolean') { // All of the above are perceived as null. children = null; } var invokeCallback = false; if (children === null) { invokeCallback = true; } else { switch (type) { case 'string': case 'number': invokeCallback = true; break; case 'object': switch (children.$$typeof) { case REACT_ELEMENT_TYPE: case REACT_PORTAL_TYPE: invokeCallback = true; } } } if (invokeCallback) { callback(traverseContext, children, // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows. nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar); return 1; } var child = void 0; var nextName = void 0; var subtreeCount = 0; // Count of children found in the current subtree. var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getComponentKey(child, i); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { var iteratorFn = getIteratorFn(children); if (typeof iteratorFn === 'function') { { // Warn about using Maps as children if (iteratorFn === children.entries) { !didWarnAboutMaps ? warning$1(false, 'Using Maps as children is unsupported and will likely yield ' + 'unexpected results. Convert it to a sequence/iterable of keyed ' + 'ReactElements instead.') : void 0; didWarnAboutMaps = true; } } var iterator = iteratorFn.call(children); var step = void 0; var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getComponentKey(child, ii++); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else if (type === 'object') { var addendum = ''; { addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + ReactDebugCurrentFrame.getStackAddendum(); } var childrenString = '' + children; invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum); } } return subtreeCount; } /** * Traverses children that are typically specified as `props.children`, but * might also be specified through attributes: * * - `traverseAllChildren(this.props.children, ...)` * - `traverseAllChildren(this.props.leftPanelChildren, ...)` * * The `traverseContext` is an optional argument that is passed through the * entire traversal. It can be used to store accumulations or anything else that * the callback might find relevant. * * @param {?*} children Children tree object. * @param {!function} callback To invoke upon traversing each child. * @param {?*} traverseContext Context for traversal. * @return {!number} The number of children in this subtree. */ function traverseAllChildren(children, callback, traverseContext) { if (children == null) { return 0; } return traverseAllChildrenImpl(children, '', callback, traverseContext); } /** * Generate a key string that identifies a component within a set. * * @param {*} component A component that could contain a manual key. * @param {number} index Index that is used if a manual key is not provided. * @return {string} */ function getComponentKey(component, index) { // Do some typechecking here since we call this blindly. We want to ensure // that we don't block potential future ES APIs. if (typeof component === 'object' && component !== null && component.key != null) { // Explicit key return escape(component.key); } // Implicit key determined by the index in the set return index.toString(36); } function forEachSingleChild(bookKeeping, child, name) { var func = bookKeeping.func, context = bookKeeping.context; func.call(context, child, bookKeeping.count++); } /** * Iterates through children that are typically specified as `props.children`. * * See https://reactjs.org/docs/react-api.html#reactchildrenforeach * * The provided forEachFunc(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc * @param {*} forEachContext Context for forEachContext. */ function forEachChildren(children, forEachFunc, forEachContext) { if (children == null) { return children; } var traverseContext = getPooledTraverseContext(null, null, forEachFunc, forEachContext); traverseAllChildren(children, forEachSingleChild, traverseContext); releaseTraverseContext(traverseContext); } function mapSingleChildIntoContext(bookKeeping, child, childKey) { var result = bookKeeping.result, keyPrefix = bookKeeping.keyPrefix, func = bookKeeping.func, context = bookKeeping.context; var mappedChild = func.call(context, child, bookKeeping.count++); if (Array.isArray(mappedChild)) { mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, function (c) { return c; }); } else if (mappedChild != null) { if (isValidElement(mappedChild)) { mappedChild = cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as // traverseAllChildren used to do for objects as children keyPrefix + (mappedChild.key && (!child || child.key !== mappedChild.key) ? escapeUserProvidedKey(mappedChild.key) + '/' : '') + childKey); } result.push(mappedChild); } } function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) { var escapedPrefix = ''; if (prefix != null) { escapedPrefix = escapeUserProvidedKey(prefix) + '/'; } var traverseContext = getPooledTraverseContext(array, escapedPrefix, func, context); traverseAllChildren(children, mapSingleChildIntoContext, traverseContext); releaseTraverseContext(traverseContext); } /** * Maps children that are typically specified as `props.children`. * * See https://reactjs.org/docs/react-api.html#reactchildrenmap * * The provided mapFunction(child, key, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} func The map function. * @param {*} context Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapChildren(children, func, context) { if (children == null) { return children; } var result = []; mapIntoWithKeyPrefixInternal(children, result, null, func, context); return result; } /** * Count the number of children that are typically specified as * `props.children`. * * See https://reactjs.org/docs/react-api.html#reactchildrencount * * @param {?*} children Children tree container. * @return {number} The number of children. */ function countChildren(children) { return traverseAllChildren(children, function () { return null; }, null); } /** * Flatten a children object (typically specified as `props.children`) and * return an array with appropriately re-keyed children. * * See https://reactjs.org/docs/react-api.html#reactchildrentoarray */ function toArray(children) { var result = []; mapIntoWithKeyPrefixInternal(children, result, null, function (child) { return child; }); return result; } /** * Returns the first child in a collection of children and verifies that there * is only one child in the collection. * * See https://reactjs.org/docs/react-api.html#reactchildrenonly * * The current implementation of this function assumes that a single child gets * passed without a wrapper, but the purpose of this helper function is to * abstract away the particular structure of children. * * @param {?object} children Child collection structure. * @return {ReactElement} The first and only `ReactElement` contained in the * structure. */ function onlyChild(children) { !isValidElement(children) ? invariant(false, 'React.Children.only expected to receive a single React element child.') : void 0; return children; } function createContext(defaultValue, calculateChangedBits) { if (calculateChangedBits === undefined) { calculateChangedBits = null; } else { { !(calculateChangedBits === null || typeof calculateChangedBits === 'function') ? warningWithoutStack$1(false, 'createContext: Expected the optional second argument to be a ' + 'function. Instead received: %s', calculateChangedBits) : void 0; } } var context = { $$typeof: REACT_CONTEXT_TYPE, _calculateChangedBits: calculateChangedBits, // As a workaround to support multiple concurrent renderers, we categorize // some renderers as primary and others as secondary. We only expect // there to be two concurrent renderers at most: React Native (primary) and // Fabric (secondary); React DOM (primary) and React ART (secondary). // Secondary renderers store their context values on separate fields. _currentValue: defaultValue, _currentValue2: defaultValue, // Used to track how many concurrent renderers this context currently // supports within in a single renderer. Such as parallel server rendering. _threadCount: 0, // These are circular Provider: null, Consumer: null }; context.Provider = { $$typeof: REACT_PROVIDER_TYPE, _context: context }; var hasWarnedAboutUsingNestedContextConsumers = false; var hasWarnedAboutUsingConsumerProvider = false; { // A separate object, but proxies back to the original context object for // backwards compatibility. It has a different $$typeof, so we can properly // warn for the incorrect usage of Context as a Consumer. var Consumer = { $$typeof: REACT_CONTEXT_TYPE, _context: context, _calculateChangedBits: context._calculateChangedBits }; // $FlowFixMe: Flow complains about not setting a value, which is intentional here Object.defineProperties(Consumer, { Provider: { get: function () { if (!hasWarnedAboutUsingConsumerProvider) { hasWarnedAboutUsingConsumerProvider = true; warning$1(false, 'Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?'); } return context.Provider; }, set: function (_Provider) { context.Provider = _Provider; } }, _currentValue: { get: function () { return context._currentValue; }, set: function (_currentValue) { context._currentValue = _currentValue; } }, _currentValue2: { get: function () { return context._currentValue2; }, set: function (_currentValue2) { context._currentValue2 = _currentValue2; } }, _threadCount: { get: function () { return context._threadCount; }, set: function (_threadCount) { context._threadCount = _threadCount; } }, Consumer: { get: function () { if (!hasWarnedAboutUsingNestedContextConsumers) { hasWarnedAboutUsingNestedContextConsumers = true; warning$1(false, 'Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?'); } return context.Consumer; } } }); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty context.Consumer = Consumer; } { context._currentRenderer = null; context._currentRenderer2 = null; } return context; } function lazy(ctor) { var lazyType = { $$typeof: REACT_LAZY_TYPE, _ctor: ctor, // React uses these fields to store the result. _status: -1, _result: null }; { // In production, this would just set it on the object. var defaultProps = void 0; var propTypes = void 0; Object.defineProperties(lazyType, { defaultProps: { configurable: true, get: function () { return defaultProps; }, set: function (newDefaultProps) { warning$1(false, 'React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.'); defaultProps = newDefaultProps; // Match production behavior more closely: Object.defineProperty(lazyType, 'defaultProps', { enumerable: true }); } }, propTypes: { configurable: true, get: function () { return propTypes; }, set: function (newPropTypes) { warning$1(false, 'React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.'); propTypes = newPropTypes; // Match production behavior more closely: Object.defineProperty(lazyType, 'propTypes', { enumerable: true }); } } }); } return lazyType; } function forwardRef(render) { { if (render != null && render.$$typeof === REACT_MEMO_TYPE) { warningWithoutStack$1(false, 'forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).'); } else if (typeof render !== 'function') { warningWithoutStack$1(false, 'forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render); } else { !( // Do not warn for 0 arguments because it could be due to usage of the 'arguments' object render.length === 0 || render.length === 2) ? warningWithoutStack$1(false, 'forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.') : void 0; } if (render != null) { !(render.defaultProps == null && render.propTypes == null) ? warningWithoutStack$1(false, 'forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?') : void 0; } } return { $$typeof: REACT_FORWARD_REF_TYPE, render: render }; } function isValidElementType(type) { return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill. type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE); } function memo(type, compare) { { if (!isValidElementType(type)) { warningWithoutStack$1(false, 'memo: The first argument must be a component. Instead ' + 'received: %s', type === null ? 'null' : typeof type); } } return { $$typeof: REACT_MEMO_TYPE, type: type, compare: compare === undefined ? null : compare }; } function resolveDispatcher() { var dispatcher = ReactCurrentDispatcher.current; !(dispatcher !== null) ? invariant(false, 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.') : void 0; return dispatcher; } function useContext(Context, unstable_observedBits) { var dispatcher = resolveDispatcher(); { !(unstable_observedBits === undefined) ? warning$1(false, 'useContext() second argument is reserved for future ' + 'use in React. Passing it is not supported. ' + 'You passed: %s.%s', unstable_observedBits, typeof unstable_observedBits === 'number' && Array.isArray(arguments[2]) ? '\n\nDid you call array.map(useContext)? ' + 'Calling Hooks inside a loop is not supported. ' + 'Learn more at https://fb.me/rules-of-hooks' : '') : void 0; // TODO: add a more generic warning for invalid values. if (Context._context !== undefined) { var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs // and nobody should be using this in existing code. if (realContext.Consumer === Context) { warning$1(false, 'Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' + 'removed in a future major release. Did you mean to call useContext(Context) instead?'); } else if (realContext.Provider === Context) { warning$1(false, 'Calling useContext(Context.Provider) is not supported. ' + 'Did you mean to call useContext(Context) instead?'); } } } return dispatcher.useContext(Context, unstable_observedBits); } function useState(initialState) { var dispatcher = resolveDispatcher(); return dispatcher.useState(initialState); } function useReducer(reducer, initialArg, init) { var dispatcher = resolveDispatcher(); return dispatcher.useReducer(reducer, initialArg, init); } function useRef(initialValue) { var dispatcher = resolveDispatcher(); return dispatcher.useRef(initialValue); } function useEffect(create, inputs) { var dispatcher = resolveDispatcher(); return dispatcher.useEffect(create, inputs); } function useLayoutEffect(create, inputs) { var dispatcher = resolveDispatcher(); return dispatcher.useLayoutEffect(create, inputs); } function useCallback(callback, inputs) { var dispatcher = resolveDispatcher(); return dispatcher.useCallback(callback, inputs); } function useMemo(create, inputs) { var dispatcher = resolveDispatcher(); return dispatcher.useMemo(create, inputs); } function useImperativeHandle(ref, create, inputs) { var dispatcher = resolveDispatcher(); return dispatcher.useImperativeHandle(ref, create, inputs); } function useDebugValue(value, formatterFn) { { var dispatcher = resolveDispatcher(); return dispatcher.useDebugValue(value, formatterFn); } } /** * ReactElementValidator provides a wrapper around a element factory * which validates the props passed to the element. This is intended to be * used only in DEV and could be replaced by a static type checker for languages * that support it. */ var propTypesMisspellWarningShown = void 0; { propTypesMisspellWarningShown = false; } function getDeclarationErrorAddendum() { if (ReactCurrentOwner.current) { var name = getComponentName(ReactCurrentOwner.current.type); if (name) { return '\n\nCheck the render method of `' + name + '`.'; } } return ''; } function getSourceInfoErrorAddendum(elementProps) { if (elementProps !== null && elementProps !== undefined && elementProps.__source !== undefined) { var source = elementProps.__source; var fileName = source.fileName.replace(/^.*[\\\/]/, ''); var lineNumber = source.lineNumber; return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.'; } return ''; } /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasKeyUseWarning = {}; function getCurrentComponentErrorInfo(parentType) { var info = getDeclarationErrorAddendum(); if (!info) { var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; if (parentName) { info = '\n\nCheck the top-level render call using <' + parentName + '>.'; } } return info; } /** * Warn if the element doesn't have an explicit key assigned to it. * This element is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. Error statuses are cached so a warning * will only be shown once. * * @internal * @param {ReactElement} element Element that requires a key. * @param {*} parentType element's parent's type. */ function validateExplicitKey(element, parentType) { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { return; } ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a // property, it may be the creator of the child that's responsible for // assigning it a key. var childOwner = ''; if (element && element._owner && element._owner !== ReactCurrentOwner.current) { // Give the component that originally created this child. childOwner = ' It was passed a child from ' + getComponentName(element._owner.type) + '.'; } setCurrentlyValidatingElement(element); { warning$1(false, 'Each child in a list should have a unique "key" prop.' + '%s%s See https://fb.me/react-warning-keys for more information.', currentComponentErrorInfo, childOwner); } setCurrentlyValidatingElement(null); } /** * Ensure that every element either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {ReactNode} node Statically passed child of any type. * @param {*} parentType node's parent's type. */ function validateChildKeys(node, parentType) { if (typeof node !== 'object') { return; } if (Array.isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (isValidElement(node)) { // This element was passed in a valid location. if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); if (typeof iteratorFn === 'function') { // Entry iterators used to provide implicit keys, // but now we print a separate warning for them later. if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step = void 0; while (!(step = iterator.next()).done) { if (isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } /** * Given an element, validate that its props follow the propTypes definition, * provided by the type. * * @param {ReactElement} element */ function validatePropTypes(element) { var type = element.type; if (type === null || type === undefined || typeof type === 'string') { return; } var name = getComponentName(type); var propTypes = void 0; if (typeof type === 'function') { propTypes = type.propTypes; } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. // Inner props are checked in the reconciler. type.$$typeof === REACT_MEMO_TYPE)) { propTypes = type.propTypes; } else { return; } if (propTypes) { setCurrentlyValidatingElement(element); checkPropTypes(propTypes, element.props, 'prop', name, ReactDebugCurrentFrame.getStackAddendum); setCurrentlyValidatingElement(null); } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) { propTypesMisspellWarningShown = true; warningWithoutStack$1(false, 'Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', name || 'Unknown'); } if (typeof type.getDefaultProps === 'function') { !type.getDefaultProps.isReactClassApproved ? warningWithoutStack$1(false, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : void 0; } } /** * Given a fragment, validate that it can only be provided with fragment props * @param {ReactElement} fragment */ function validateFragmentProps(fragment) { setCurrentlyValidatingElement(fragment); var keys = Object.keys(fragment.props); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (key !== 'children' && key !== 'key') { warning$1(false, 'Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key); break; } } if (fragment.ref !== null) { warning$1(false, 'Invalid attribute `ref` supplied to `React.Fragment`.'); } setCurrentlyValidatingElement(null); } function createElementWithValidation(type, props, children) { var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. if (!validType) { var info = ''; if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports."; } var sourceInfo = getSourceInfoErrorAddendum(props); if (sourceInfo) { info += sourceInfo; } else { info += getDeclarationErrorAddendum(); } var typeString = void 0; if (type === null) { typeString = 'null'; } else if (Array.isArray(type)) { typeString = 'array'; } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) { typeString = '<' + (getComponentName(type.type) || 'Unknown') + ' />'; info = ' Did you accidentally export a JSX literal instead of a component?'; } else { typeString = typeof type; } warning$1(false, 'React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info); } var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used. // TODO: Drop this when these are no longer allowed as the type argument. if (element == null) { return element; } // Skip key warning if the type isn't valid since our key validation logic // doesn't expect a non-string/function type and can throw confusing errors. // We don't want exception behavior to differ between dev and prod. // (Rendering will throw with a helpful message and as soon as the type is // fixed, the key warnings will appear.) if (validType) { for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], type); } } if (type === REACT_FRAGMENT_TYPE) { validateFragmentProps(element); } else { validatePropTypes(element); } return element; } function createFactoryWithValidation(type) { var validatedFactory = createElementWithValidation.bind(null, type); validatedFactory.type = type; // Legacy hook: remove it { Object.defineProperty(validatedFactory, 'type', { enumerable: false, get: function () { lowPriorityWarning$1(false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.'); Object.defineProperty(this, 'type', { value: type }); return type; } }); } return validatedFactory; } function cloneElementWithValidation(element, props, children) { var newElement = cloneElement.apply(this, arguments); for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], newElement.type); } validatePropTypes(newElement); return newElement; } // Helps identify side effects in begin-phase lifecycle hooks and setState reducers: // In some cases, StrictMode should also double-render lifecycles. // This can be confusing for tests though, // And it can be bad for performance in production. // This feature flag can be used to control the behavior: // To preserve the "Pause on caught exceptions" behavior of the debugger, we // replay the begin phase of a failed component inside invokeGuardedCallback. // Warn about deprecated, async-unsafe lifecycles; relates to RFC #6: // Gather advanced timing metrics for Profiler subtrees. // Trace which interactions trigger each commit. // Only used in www builds. // TODO: true? Here it might just be false. // Only used in www builds. // Only used in www builds. // React Fire: prevent the value and checked attributes from syncing // with their related DOM properties // These APIs will no longer be "unstable" in the upcoming 16.7 release, // Control this behavior with a flag to support 16.6 minor releases in the meanwhile. var enableStableConcurrentModeAPIs = false; var React = { Children: { map: mapChildren, forEach: forEachChildren, count: countChildren, toArray: toArray, only: onlyChild }, createRef: createRef, Component: Component, PureComponent: PureComponent, createContext: createContext, forwardRef: forwardRef, lazy: lazy, memo: memo, useCallback: useCallback, useContext: useContext, useEffect: useEffect, useImperativeHandle: useImperativeHandle, useDebugValue: useDebugValue, useLayoutEffect: useLayoutEffect, useMemo: useMemo, useReducer: useReducer, useRef: useRef, useState: useState, Fragment: REACT_FRAGMENT_TYPE, StrictMode: REACT_STRICT_MODE_TYPE, Suspense: REACT_SUSPENSE_TYPE, createElement: createElementWithValidation, cloneElement: cloneElementWithValidation, createFactory: createFactoryWithValidation, isValidElement: isValidElement, version: ReactVersion, unstable_ConcurrentMode: REACT_CONCURRENT_MODE_TYPE, unstable_Profiler: REACT_PROFILER_TYPE, __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: ReactSharedInternals }; // Note: some APIs are added with feature flags. // Make sure that stable builds for open source // don't modify the React object to avoid deopts. // Also let's not expose their names in stable builds. if (enableStableConcurrentModeAPIs) { React.ConcurrentMode = REACT_CONCURRENT_MODE_TYPE; React.Profiler = REACT_PROFILER_TYPE; React.unstable_ConcurrentMode = undefined; React.unstable_Profiler = undefined; } var React$2 = Object.freeze({ default: React }); var React$3 = ( React$2 && React ) || React$2; // TODO: decide on the top-level export form. // This is hacky but makes it work with both Rollup and Jest. var react = React$3.default || React$3; module.exports = react; })(); } /***/ }), /***/ "BMHr": /*!***********************************************************************************************************************************************************!*\ !*** C:/agent/1/_work/5/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/prop-types/15.7.2/node_modules/prop-types/lib/ReactPropTypesSecret.js ***! \***********************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret; /***/ }), /***/ "DVb/": /*!***********************************************************************************************************************************************************!*\ !*** C:/agent/1/_work/5/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/prop-types/15.6.0/node_modules/prop-types/lib/ReactPropTypesSecret.js ***! \***********************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret; /***/ }), /***/ "FJDr": /*!**************************************************************************************************************************************!*\ !*** C:/agent/1/_work/5/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/fbjs/0.8.17/node_modules/fbjs/lib/emptyObject.js ***! \**************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ var emptyObject = {}; if (true) { Object.freeze(emptyObject); } module.exports = emptyObject; /***/ }), /***/ "Q+bF": /*!**********************************************************************************************************************************!*\ !*** C:/agent/1/_work/5/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/fbjs/0.8.17/node_modules/fbjs/lib/warning.js ***! \**********************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ var emptyFunction = __webpack_require__(/*! ./emptyFunction */ "xvdx"); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if (true) { var printWarning = function printWarning(format) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; warning = function warning(condition, format) { if (format === undefined) { throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } printWarning.apply(undefined, [format].concat(args)); } }; } module.exports = warning; /***/ }), /***/ "R3cu": /*!****************************************************************************************************************************************!*\ !*** C:/agent/1/_work/5/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/prop-types/15.6.0/node_modules/prop-types/index.js ***! \****************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ if (true) { var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' && Symbol.for && Symbol.for('react.element')) || 0xeac7; var isValidElement = function(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; // By explicitly using `prop-types` you are opting into new development behavior. // http://fb.me/prop-types-in-prod var throwOnDirectAccess = true; module.exports = __webpack_require__(/*! ./factoryWithTypeCheckers */ "2Jnp")(isValidElement, throwOnDirectAccess); } else {} /***/ }), /***/ "U8ve": /*!**********************************************************************************************************************************************************!*\ !*** C:/agent/1/_work/5/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/create-react-class/15.6.3/node_modules/create-react-class/factory.js ***! \**********************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ var _assign = __webpack_require__(/*! object-assign */ "sjay"); var emptyObject = __webpack_require__(/*! fbjs/lib/emptyObject */ "FJDr"); var _invariant = __webpack_require__(/*! fbjs/lib/invariant */ "ypis"); if (true) { var warning = __webpack_require__(/*! fbjs/lib/warning */ "Q+bF"); } var MIXINS_KEY = 'mixins'; // Helper function to allow the creation of anonymous functions which do not // have .name set to the name of the variable being assigned to. function identity(fn) { return fn; } var ReactPropTypeLocationNames; if (true) { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } else {} function factory(ReactComponent, isValidElement, ReactNoopUpdateQueue) { /** * Policies that describe methods in `ReactClassInterface`. */ var injectedMixins = []; /** * Composite components are higher-level components that compose other composite * or host components. * * To create a new type of `ReactClass`, pass a specification of * your new class to `React.createClass`. The only requirement of your class * specification is that you implement a `render` method. * * var MyComponent = React.createClass({ * render: function() { * return <div>Hello World</div>; * } * }); * * The class specification supports a specific protocol of methods that have * special meaning (e.g. `render`). See `ReactClassInterface` for * more the comprehensive protocol. Any other properties and methods in the * class specification will be available on the prototype. * * @interface ReactClassInterface * @internal */ var ReactClassInterface = { /** * An array of Mixin objects to include when defining your component. * * @type {array} * @optional */ mixins: 'DEFINE_MANY', /** * An object containing properties and methods that should be defined on * the component's constructor instead of its prototype (static methods). * * @type {object} * @optional */ statics: 'DEFINE_MANY', /** * Definition of prop types for this component. * * @type {object} * @optional */ propTypes: 'DEFINE_MANY', /** * Definition of context types for this component. * * @type {object} * @optional */ contextTypes: 'DEFINE_MANY', /** * Definition of context types this component sets for its children. * * @type {object} * @optional */ childContextTypes: 'DEFINE_MANY', // ==== Definition methods ==== /** * Invoked when the component is mounted. Values in the mapping will be set on * `this.props` if that prop is not specified (i.e. using an `in` check). * * This method is invoked before `getInitialState` and therefore cannot rely * on `this.state` or use `this.setState`. * * @return {object} * @optional */ getDefaultProps: 'DEFINE_MANY_MERGED', /** * Invoked once before the component is mounted. The return value will be used * as the initial value of `this.state`. * * getInitialState: function() { * return { * isOn: false, * fooBaz: new BazFoo() * } * } * * @return {object} * @optional */ getInitialState: 'DEFINE_MANY_MERGED', /** * @return {object} * @optional */ getChildContext: 'DEFINE_MANY_MERGED', /** * Uses props from `this.props` and state from `this.state` to render the * structure of the component. * * No guarantees are made about when or how often this method is invoked, so * it must not have side effects. * * render: function() { * var name = this.props.name; * return <div>Hello, {name}!</div>; * } * * @return {ReactComponent} * @required */ render: 'DEFINE_ONCE', // ==== Delegate methods ==== /** * Invoked when the component is initially created and about to be mounted. * This may have side effects, but any external subscriptions or data created * by this method must be cleaned up in `componentWillUnmount`. * * @optional */ componentWillMount: 'DEFINE_MANY', /** * Invoked when the component has been mounted and has a DOM representation. * However, there is no guarantee that the DOM node is in the document. * * Use this as an opportunity to operate on the DOM when the component has * been mounted (initialized and rendered) for the first time. * * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidMount: 'DEFINE_MANY', /** * Invoked before the component receives new props. * * Use this as an opportunity to react to a prop transition by updating the * state using `this.setState`. Current props are accessed via `this.props`. * * componentWillReceiveProps: function(nextProps, nextContext) { * this.setState({ * likesIncreasing: nextProps.likeCount > this.props.likeCount * }); * } * * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop * transition may cause a state change, but the opposite is not true. If you * need it, you are probably looking for `componentWillUpdate`. * * @param {object} nextProps * @optional */ componentWillReceiveProps: 'DEFINE_MANY', /** * Invoked while deciding if the component should be updated as a result of * receiving new props, state and/or context. * * Use this as an opportunity to `return false` when you're certain that the * transition to the new props/state/context will not require a component * update. * * shouldComponentUpdate: function(nextProps, nextState, nextContext) { * return !equal(nextProps, this.props) || * !equal(nextState, this.state) || * !equal(nextContext, this.context); * } * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @return {boolean} True if the component should update. * @optional */ shouldComponentUpdate: 'DEFINE_ONCE', /** * Invoked when the component is about to update due to a transition from * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState` * and `nextContext`. * * Use this as an opportunity to perform preparation before an update occurs. * * NOTE: You **cannot** use `this.setState()` in this method. * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @param {ReactReconcileTransaction} transaction * @optional */ componentWillUpdate: 'DEFINE_MANY', /** * Invoked when the component's DOM representation has been updated. * * Use this as an opportunity to operate on the DOM when the component has * been updated. * * @param {object} prevProps * @param {?object} prevState * @param {?object} prevContext * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidUpdate: 'DEFINE_MANY', /** * Invoked when the component is about to be removed from its parent and have * its DOM representation destroyed. * * Use this as an opportunity to deallocate any external resources. * * NOTE: There is no `componentDidUnmount` since your component will have been * destroyed by that point. * * @optional */ componentWillUnmount: 'DEFINE_MANY', /** * Replacement for (deprecated) `componentWillMount`. * * @optional */ UNSAFE_componentWillMount: 'DEFINE_MANY', /** * Replacement for (deprecated) `componentWillReceiveProps`. * * @optional */ UNSAFE_componentWillReceiveProps: 'DEFINE_MANY', /** * Replacement for (deprecated) `componentWillUpdate`. * * @optional */ UNSAFE_componentWillUpdate: 'DEFINE_MANY', // ==== Advanced methods ==== /** * Updates the component's currently mounted DOM representation. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @internal * @overridable */ updateComponent: 'OVERRIDE_BASE' }; /** * Similar to ReactClassInterface but for static methods. */ var ReactClassStaticInterface = { /** * This method is invoked after a component is instantiated and when it * receives new props. Return an object to update state in response to * prop changes. Return null to indicate no change to state. * * If an object is returned, its keys will be merged into the existing state. * * @return {object || null} * @optional */ getDerivedStateFromProps: 'DEFINE_MANY_MERGED' }; /** * Mapping from class specification keys to special processing functions. * * Although these are declared like instance properties in the specification * when defining classes using `React.createClass`, they are actually static * and are accessible on the constructor instead of the prototype. Despite * being static, they must be defined outside of the "statics" key under * which all other static methods are defined. */ var RESERVED_SPEC_KEYS = { displayName: function(Constructor, displayName) { Constructor.displayName = displayName; }, mixins: function(Constructor, mixins) { if (mixins) { for (var i = 0; i < mixins.length; i++) { mixSpecIntoComponent(Constructor, mixins[i]); } } }, childContextTypes: function(Constructor, childContextTypes) { if (true) { validateTypeDef(Constructor, childContextTypes, 'childContext'); } Constructor.childContextTypes = _assign( {}, Constructor.childContextTypes, childContextTypes ); }, contextTypes: function(Constructor, contextTypes) { if (true) { validateTypeDef(Constructor, contextTypes, 'context'); } Constructor.contextTypes = _assign( {}, Constructor.contextTypes, contextTypes ); }, /** * Special case getDefaultProps which should move into statics but requires * automatic merging. */ getDefaultProps: function(Constructor, getDefaultProps) { if (Constructor.getDefaultProps) { Constructor.getDefaultProps = createMergedResultFunction( Constructor.getDefaultProps, getDefaultProps ); } else { Constructor.getDefaultProps = getDefaultProps; } }, propTypes: function(Constructor, propTypes) { if (true) { validateTypeDef(Constructor, propTypes, 'prop'); } Constructor.propTypes = _assign({}, Constructor.propTypes, propTypes); }, statics: function(Constructor, statics) { mixStaticSpecIntoComponent(Constructor, statics); }, autobind: function() {} }; function validateTypeDef(Constructor, typeDef, location) { for (var propName in typeDef) { if (typeDef.hasOwnProperty(propName)) { // use a warning instead of an _invariant so components // don't show up in prod but only in __DEV__ if (true) { warning( typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName ); } } } } function validateMethodOverride(isAlreadyDefined, name) { var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null; // Disallow overriding of base class methods unless explicitly allowed. if (ReactClassMixin.hasOwnProperty(name)) { _invariant( specPolicy === 'OVERRIDE_BASE', 'ReactClassInterface: You are attempting to override ' + '`%s` from your class specification. Ensure that your method names ' + 'do not overlap with React methods.', name ); } // Disallow defining methods more than once unless explicitly allowed. if (isAlreadyDefined) { _invariant( specPolicy === 'DEFINE_MANY' || specPolicy === 'DEFINE_MANY_MERGED', 'ReactClassInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name ); } } /** * Mixin helper which handles policy validation and reserved * specification keys when building React classes. */ function mixSpecIntoComponent(Constructor, spec) { if (!spec) { if (true) { var typeofSpec = typeof spec; var isMixinValid = typeofSpec === 'object' && spec !== null; if (true) { warning( isMixinValid, "%s: You're attempting to include a mixin that is either null " + 'or not an object. Check the mixins included by the component, ' + 'as well as any mixins they include themselves. ' + 'Expected object but got %s.', Constructor.displayName || 'ReactClass', spec === null ? null : typeofSpec ); } } return; } _invariant( typeof spec !== 'function', "ReactClass: You're attempting to " + 'use a component class or function as a mixin. Instead, just use a ' + 'regular object.' ); _invariant( !isValidElement(spec), "ReactClass: You're attempting to " + 'use a component as a mixin. Instead, just use a regular object.' ); var proto = Constructor.prototype; var autoBindPairs = proto.__reactAutoBindPairs; // By handling mixins before any other properties, we ensure the same // chaining order is applied to methods with DEFINE_MANY policy, whether // mixins are listed before or after these methods in the spec. if (spec.hasOwnProperty(MIXINS_KEY)) { RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins); } for (var name in spec) { if (!spec.hasOwnProperty(name)) { continue; } if (name === MIXINS_KEY) { // We have already handled mixins in a special case above. continue; } var property = spec[name]; var isAlreadyDefined = proto.hasOwnProperty(name); validateMethodOverride(isAlreadyDefined, name); if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { RESERVED_SPEC_KEYS[name](Constructor, property); } else { // Setup methods on prototype: // The following member methods should not be automatically bound: // 1. Expected ReactClass methods (in the "interface"). // 2. Overridden methods (that were mixed in). var isReactClassMethod = ReactClassInterface.hasOwnProperty(name); var isFunction = typeof property === 'function'; var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false; if (shouldAutoBind) { autoBindPairs.push(name, property); proto[name] = property; } else { if (isAlreadyDefined) { var specPolicy = ReactClassInterface[name]; // These cases should already be caught by validateMethodOverride. _invariant( isReactClassMethod && (specPolicy === 'DEFINE_MANY_MERGED' || specPolicy === 'DEFINE_MANY'), 'ReactClass: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name ); // For methods which are defined more than once, call the existing // methods before calling the new property, merging if appropriate. if (specPolicy === 'DEFINE_MANY_MERGED') { proto[name] = createMergedResultFunction(proto[name], property); } else if (specPolicy === 'DEFINE_MANY') { proto[name] = createChainedFunction(proto[name], property); } } else { proto[name] = property; if (true) { // Add verbose displayName to the function, which helps when looking // at profiling tools. if (typeof property === 'function' && spec.displayName) { proto[name].displayName = spec.displayName + '_' + name; } } } } } } } function mixStaticSpecIntoComponent(Constructor, statics) { if (!statics) { return; } for (var name in statics) { var property = statics[name]; if (!statics.hasOwnProperty(name)) { continue; } var isReserved = name in RESERVED_SPEC_KEYS; _invariant( !isReserved, 'ReactClass: You are attempting to define a reserved ' + 'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' + 'as an instance property instead; it will still be accessible on the ' + 'constructor.', name ); var isAlreadyDefined = name in Constructor; if (isAlreadyDefined) { var specPolicy = ReactClassStaticInterface.hasOwnProperty(name) ? ReactClassStaticInterface[name] : null; _invariant( specPolicy === 'DEFINE_MANY_MERGED', 'ReactClass: You are attempting to define ' + '`%s` on your component more than once. This conflict may be ' + 'due to a mixin.', name ); Constructor[name] = createMergedResultFunction(Constructor[name], property); return; } Constructor[name] = property; } } /** * Merge two objects, but throw if both contain the same key. * * @param {object} one The first object, which is mutated. * @param {object} two The second object * @return {object} one after it has been mutated to contain everything in two. */ function mergeIntoWithNoDuplicateKeys(one, two) { _invariant( one && two && typeof one === 'object' && typeof two === 'object', 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.' ); for (var key in two) { if (two.hasOwnProperty(key)) { _invariant( one[key] === undefined, 'mergeIntoWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: `%s`. This conflict ' + 'may be due to a mixin; in particular, this may be caused by two ' + 'getInitialState() or getDefaultProps() methods returning objects ' + 'with clashing keys.', key ); one[key] = two[key]; } } return one; } /** * Creates a function that invokes two functions and merges their return values. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createMergedResultFunction(one, two) { return function mergedResult() { var a = one.apply(this, arguments); var b = two.apply(this, arguments); if (a == null) { return b; } else if (b == null) { return a; } var c = {}; mergeIntoWithNoDuplicateKeys(c, a); mergeIntoWithNoDuplicateKeys(c, b); return c; }; } /** * Creates a function that invokes two functions and ignores their return vales. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createChainedFunction(one, two) { return function chainedFunction() { one.apply(this, arguments); two.apply(this, arguments); }; } /** * Binds a method to the component. * * @param {object} component Component whose method is going to be bound. * @param {function} method Method to be bound. * @return {function} The bound method. */ function bindAutoBindMethod(component, method) { var boundMethod = method.bind(component); if (true) { boundMethod.__reactBoundContext = component; boundMethod.__reactBoundMethod = method; boundMethod.__reactBoundArguments = null; var componentName = component.constructor.displayName; var _bind = boundMethod.bind; boundMethod.bind = function(newThis) { for ( var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++ ) { args[_key - 1] = arguments[_key]; } // User is trying to bind() an autobound method; we effectively will // ignore the value of "this" that the user is trying to use, so // let's warn. if (newThis !== component && newThis !== null) { if (true) { warning( false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName ); } } else if (!args.length) { if (true) { warning( false, 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See %s', componentName ); } return boundMethod; } var reboundMethod = _bind.apply(boundMethod, arguments); reboundMethod.__reactBoundContext = component; reboundMethod.__reactBoundMethod = method; reboundMethod.__reactBoundArguments = args; return reboundMethod; }; } return boundMethod; } /** * Binds all auto-bound methods in a component. * * @param {object} component Component whose method is going to be bound. */ function bindAutoBindMethods(component) { var pairs = component.__reactAutoBindPairs; for (var i = 0; i < pairs.length; i += 2) { var autoBindKey = pairs[i]; var method = pairs[i + 1]; component[autoBindKey] = bindAutoBindMethod(component, method); } } var IsMountedPreMixin = { componentDidMount: function() { this.__isMounted = true; } }; var IsMountedPostMixin = { componentWillUnmount: function() { this.__isMounted = false; } }; /** * Add more to the ReactClass base class. These are all legacy features and * therefore not already part of the modern ReactComponent. */ var ReactClassMixin = { /** * TODO: This will be deprecated because state should always keep a consistent * type signature and the only use case for this, is to avoid that. */ replaceState: function(newState, callback) { this.updater.enqueueReplaceState(this, newState, callback); }, /** * Checks whether or not this composite component is mounted. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function() { if (true) { warning( this.__didWarnIsMounted, '%s: isMounted is deprecated. Instead, make sure to clean up ' + 'subscriptions and pending requests in componentWillUnmount to ' + 'prevent memory leaks.', (this.constructor && this.constructor.displayName) || this.name || 'Component' ); this.__didWarnIsMounted = true; } return !!this.__isMounted; } }; var ReactClassComponent = function() {}; _assign( ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin ); /** * Creates a composite component class given a class specification. * See https://facebook.github.io/react/docs/top-level-api.html#react.createclass * * @param {object} spec Class specification (which must define `render`). * @return {function} Component constructor function. * @public */ function createClass(spec) { // To keep our warnings more understandable, we'll use a little hack here to // ensure that Constructor.name !== 'Constructor'. This makes sure we don't // unnecessarily identify a class without displayName as 'Constructor'. var Constructor = identity(function(props, context, updater) { // This constructor gets overridden by mocks. The argument is used // by mocks to assert on what gets mounted. if (true) { warning( this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory' ); } // Wire up auto-binding if (this.__reactAutoBindPairs.length) { bindAutoBindMethods(this); } this.props = props; this.context = context; this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; this.state = null; // ReactClasses doesn't have constructors. Instead, they use the // getInitialState and componentWillMount methods for initialization. var initialState = this.getInitialState ? this.getInitialState() : null; if (true) { // We allow auto-mocks to proceed as if they're returning null. if ( initialState === undefined && this.getInitialState._isMockFunction ) { // This is probably bad practice. Consider warning here and // deprecating this convenience. initialState = null; } } _invariant( typeof initialState === 'object' && !Array.isArray(initialState), '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent' ); this.state = initialState; }); Constructor.prototype = new ReactClassComponent(); Constructor.prototype.constructor = Constructor; Constructor.prototype.__reactAutoBindPairs = []; injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor)); mixSpecIntoComponent(Constructor, IsMountedPreMixin); mixSpecIntoComponent(Constructor, spec); mixSpecIntoComponent(Constructor, IsMountedPostMixin); // Initialize the defaultProps property after all mixins have been merged. if (Constructor.getDefaultProps) { Constructor.defaultProps = Constructor.getDefaultProps(); } if (true) { // This is a tag to indicate that the use of these method names is ok, // since it's used with createClass. If it's not, then it's likely a // mistake so we'll warn you to use the static property, property // initializer or constructor respectively. if (Constructor.getDefaultProps) { Constructor.getDefaultProps.isReactClassApproved = {}; } if (Constructor.prototype.getInitialState) { Constructor.prototype.getInitialState.isReactClassApproved = {}; } } _invariant( Constructor.prototype.render, 'createClass(...): Class specification must implement a `render` method.' ); if (true) { warning( !Constructor.prototype.componentShouldUpdate, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', spec.displayName || 'A component' ); warning( !Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component' ); warning( !Constructor.prototype.UNSAFE_componentWillRecieveProps, '%s has a method called UNSAFE_componentWillRecieveProps(). ' + 'Did you mean UNSAFE_componentWillReceiveProps()?', spec.displayName || 'A component' ); } // Reduce time spent doing lookups by setting these on the prototype. for (var methodName in ReactClassInterface) { if (!Constructor.prototype[methodName]) { Constructor.prototype[methodName] = null; } } return Constructor; } return createClass; } module.exports = factory; /***/ }), /***/ "jvHV": /*!*************************************************************************************************************************************************!*\ !*** C:/agent/1/_work/5/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/prop-types/15.7.2/node_modules/prop-types/checkPropTypes.js ***! \*************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var printWarning = function() {}; if (true) { var ReactPropTypesSecret = __webpack_require__(/*! ./lib/ReactPropTypesSecret */ "BMHr"); var loggedTypeFailures = {}; var has = Function.call.bind(Object.prototype.hasOwnProperty); printWarning = function(text) { var message = 'Warning: ' + text; if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; } /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?Function} getStack Returns the component stack. * @private */ function checkPropTypes(typeSpecs, values, location, componentName, getStack) { if (true) { for (var typeSpecName in typeSpecs) { if (has(typeSpecs, typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. if (typeof typeSpecs[typeSpecName] !== 'function') { var err = Error( (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' ); err.name = 'Invariant Violation'; throw err; } error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); } catch (ex) { error = ex; } if (error && !(error instanceof Error)) { printWarning( (componentName || 'React class') + ': type specification of ' + location + ' `' + typeSpecName + '` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).' ); } if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var stack = getStack ? getStack() : ''; printWarning( 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '') ); } } } } } /** * Resets warning cache when testing. * * @private */ checkPropTypes.resetWarningCache = function() { if (true) { loggedTypeFailures = {}; } } module.exports = checkPropTypes; /***/ }), /***/ "mwqp": /*!**********************!*\ !*** ./lib/index.js ***! \**********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var React = __webpack_require__(/*! react */ "3wdl"); var createClass = __webpack_require__(/*! create-react-class */ "1FaY"); var PropTypes = __webpack_require__(/*! prop-types */ "R3cu"); React.React = React; // tslint:disable-line:no-any React.React.createClass = createClass; // tslint:disable-line:no-any React.React.PropTypes = PropTypes; // tslint:disable-line:no-any module.exports = React; /***/ }), /***/ "sjay": /*!*********************************************************************************************************************************************!*\ !*** C:/agent/1/_work/5/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/object-assign/4.1.1/node_modules/object-assign/index.js ***! \*********************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* object-assign (c) Sindre Sorhus @license MIT */ /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } module.exports = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /***/ }), /***/ "xvdx": /*!****************************************************************************************************************************************!*\ !*** C:/agent/1/_work/5/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/fbjs/0.8.17/node_modules/fbjs/lib/emptyFunction.js ***! \****************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ var emptyFunction = function emptyFunction() {}; emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; module.exports = emptyFunction; /***/ }), /***/ "ypis": /*!************************************************************************************************************************************!*\ !*** C:/agent/1/_work/5/s/common/temp/node_modules/.onedrive.pkgs.visualstudio.com/fbjs/0.8.17/node_modules/fbjs/lib/invariant.js ***! \************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var validateFormat = function validateFormat(format) {}; if (true) { validateFormat = function validateFormat(format) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } }; } function invariant(condition, format, a, b, c, d, e, f) { validateFormat(format); if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } module.exports = invariant; /***/ }) /******/ })});; //# sourceMappingURL=react-16-bundle.js.map
/** * A simple slot extension, built upon the components service. * * @type {Object} */ const ComponentWithSlots = { slotFill(slotProps, DefaultFill) { const { type, context, ...props } = slotProps; const Fill = this.components.getComponent(type, context) || DefaultFill; if (Fill) { return <Fill { ...context } { ...props } />; } return null; }, slotFills(slotProps) { const { type, context, ...props } = slotProps; const fills = this.components.getComponents(type, context); return fills.map( Fill => <Fill { ...context } { ...props } /> ); } }; export default ComponentWithSlots; ComponentWithSlots.$inject = [ 'components' ];
const interpreter = require("../interpreter") module.exports = async (client, channel, user) => { for (const command of client.typing_commands.array()) { const data = { author: user, member: channel.type === "dm" ? undefined : await channel.guild.members.fetch(user.id).catch(err => undefined), guild: channel.guild, channel } const id = command.channel ? command.channel.includes("$") ? await interpreter(client, data, [], { channel: command.channel, code: command.channel }, undefined, true) : command.channel : channel.id const ch = channel.guild.channels.cache.get(id) data.channel = command.channel ? ch ? ch : channel : channel await interpreter(client, data, [], command, undefined) } }
import React from 'react'; import './DashboardHome.css'; const DashboardHome = () => { return ( <div className="dashboardHome"> <img src="https://i.ibb.co/vvpCk62/site-stats-concept-illustration-114360-1509.jpg" alt="" /> </div> ); }; export default DashboardHome;
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = require('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = require('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _libs = require('../../../libs'); var _draggable = require('../draggable'); var _draggable2 = _interopRequireDefault(_draggable); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { var enterModule = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.enterModule : undefined; enterModule && enterModule(module); })(); var __signature__ = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.default.signature : function (a) { return a; }; var AlphaSlider = function (_Component) { (0, _inherits3.default)(AlphaSlider, _Component); function AlphaSlider(props) { (0, _classCallCheck3.default)(this, AlphaSlider); var _this = (0, _possibleConstructorReturn3.default)(this, (AlphaSlider.__proto__ || Object.getPrototypeOf(AlphaSlider)).call(this, props)); _this.state = { thumbLeft: 0, thumbTop: 0, background: null }; return _this; } (0, _createClass3.default)(AlphaSlider, [{ key: 'componentDidMount', value: function componentDidMount() { var _this2 = this; var _refs = this.refs, bar = _refs.bar, thumb = _refs.thumb; var dragConfig = { drag: function drag(event) { _this2.handleDrag(event); }, end: function end(event) { _this2.handleDrag(event); } }; (0, _draggable2.default)(bar, dragConfig); (0, _draggable2.default)(thumb, dragConfig); this.update(); } }, { key: 'handleClick', value: function handleClick(event) { var thumb = this.refs.thumb; var target = event.target; if (target !== thumb) { this.handleDrag(event); } } }, { key: 'handleDrag', value: function handleDrag(event) { var _props = this.props, vertical = _props.vertical, color = _props.color; var onChange = this.context.onChange; var rect = this.$el.getBoundingClientRect(); var thumb = this.refs.thumb; if (!vertical) { var left = event.clientX - rect.left; left = Math.max(thumb.offsetWidth / 2, left); left = Math.min(left, rect.width - thumb.offsetWidth / 2); color.set('alpha', Math.round((left - thumb.offsetWidth / 2) / (rect.width - thumb.offsetWidth) * 100)); } else { var top = event.clientY - rect.top; top = Math.max(thumb.offsetHeight / 2, top); top = Math.min(top, rect.height - thumb.offsetHeight / 2); color.set('alpha', Math.round((top - thumb.offsetHeight / 2) / (rect.height - thumb.offsetHeight) * 100)); } this.update(); onChange(color); } }, { key: 'getThumbLeft', value: function getThumbLeft() { var _props2 = this.props, vertical = _props2.vertical, color = _props2.color; if (vertical) return 0; var el = this.$el; var alpha = color._alpha; if (!el) return 0; var thumb = this.refs.thumb; return Math.round(alpha * (el.offsetWidth - thumb.offsetWidth / 2) / 100); } }, { key: 'getThumbTop', value: function getThumbTop() { var _props3 = this.props, vertical = _props3.vertical, color = _props3.color; if (!vertical) return 0; var el = this.$el; var alpha = color._alpha; if (!el) return 0; var thumb = this.refs.thumb; return Math.round(alpha * (el.offsetHeight - thumb.offsetHeight / 2) / 100); } }, { key: 'getBackground', value: function getBackground() { var color = this.props.color; if (color && color.value) { var _color$toRgb = color.toRgb(), r = _color$toRgb.r, g = _color$toRgb.g, b = _color$toRgb.b; return 'linear-gradient(to right, rgba(' + r + ', ' + g + ', ' + b + ', 0) 0%, rgba(' + r + ', ' + g + ', ' + b + ', 1) 100%)'; } return null; } }, { key: 'update', value: function update() { this.setState({ thumbLeft: this.getThumbLeft(), thumbTop: this.getThumbTop(), background: this.getBackground() }); } }, { key: 'render', value: function render() { var _this3 = this; var vertical = this.props.vertical; var _state = this.state, thumbLeft = _state.thumbLeft, thumbTop = _state.thumbTop, background = _state.background; return _react2.default.createElement( 'div', { ref: function ref(el) { return _this3.$el = el; }, className: this.classNames({ 'el-color-alpha-slider': true, 'is-vertical': vertical }) }, _react2.default.createElement('div', { className: 'el-color-alpha-slider__bar', onClick: function onClick(e) { return _this3.handleClick(e); }, ref: 'bar', style: { background: background } }), _react2.default.createElement('div', { className: 'el-color-alpha-slider__thumb', ref: 'thumb', style: { left: thumbLeft + 'px', top: thumbTop + 'px' } }) ); } }, { key: '__reactstandin__regenerateByEval', // @ts-ignore value: function __reactstandin__regenerateByEval(key, code) { // @ts-ignore this[key] = eval(code); } }]); return AlphaSlider; }(_libs.Component); var _default = AlphaSlider; exports.default = _default; AlphaSlider.contextTypes = { onChange: _libs.PropTypes.func }; AlphaSlider.propTypes = { color: _libs.PropTypes.object.isRequired, vertical: _libs.PropTypes.bool }; ; (function () { var reactHotLoader = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.default : undefined; if (!reactHotLoader) { return; } reactHotLoader.register(AlphaSlider, 'AlphaSlider', 'src/color-picker/components/AlphaSlider.jsx'); reactHotLoader.register(_default, 'default', 'src/color-picker/components/AlphaSlider.jsx'); })(); ; (function () { var leaveModule = typeof reactHotLoaderGlobal !== 'undefined' ? reactHotLoaderGlobal.leaveModule : undefined; leaveModule && leaveModule(module); })();
import 'regenerator-runtime/runtime' import { getTransactions } from "../../../../app/actions/ClientActions"; import { getTransactions as walletGetTransactions } from "../../../../app/wallet/service"; import { mockedTransactions, unminedMockedTransactions } from "../get-transactions.data"; jest.mock("../../../../app/wallet/service"); jest.mock("../../../../app/middleware/walletrpc/api_pb"); jest.mock("../../../../app/selectors"); function getMockedTransactions(height) { return [...mockedTransactions].map(tx => ({ ...tx, height })); } function range(numberOfElements) { return [...Array(numberOfElements).keys()]; } function getMockedGrpcState(overrideProps = {}) { const defaultState = { currentBlockHeight: 2, getTransactionsRequestAttempt: false, transactionsFilter: { listDirection: "desc", types: [0], direction: null }, walletService: jest.fn(), maximumTransactionCount: 10, recentTransactionCount: 8, noMoreTransactions: false, lastTransaction: null, minedTransactions: [], recentRegularTransactions: [], recentStakeTransactions: [] }; return { grpc: { ...defaultState, ...overrideProps } }; } function getMockedWalletGetTransactionResponse(options = {}) { if (options.empty) { return { mined: [], unmined: [] }; } const { height = 1 } = options; return { unmined: [], mined: [ { amount: 30000000000, creditAddresses: [ "22tv7nd31sMmD8BpcVRJAWQLqYCjaCuqpWpz", "22u4VtFDzXDT517DFfCLRM8i5t814pZXePBK" ], creditAmounts: 30000000000, txHash: "933bb306b3e71ac0d7c89f8dd2884f9190a1b7049e0632ae5201e1fb59377849", txType: "Coinbase", type: 4, index: 0, height } ] }; } describe("ClientActions > getTransactions", () => { test("it shouldn't dispatch any action when 'getTransactionsRequestAttempt' or 'noMoreTransactions' is true", async () => { walletGetTransactions.mockResolvedValue(getMockedWalletGetTransactionResponse({ empty: true })); const _getState = jest.fn(); const _dispatch = jest.fn(); const [firstCase, secondCase, thirdCase] = [[true, false], [false, true], [true, true]] .map(([getTransactionsRequestAttempt, noMoreTransactions]) => ({ getTransactionsRequestAttempt, noMoreTransactions })) .map(getMockedGrpcState); _getState // each call of getTransactions calls getState twice .mockReturnValueOnce(firstCase) .mockReturnValueOnce(firstCase) .mockReturnValueOnce(secondCase) .mockReturnValueOnce(secondCase) .mockReturnValueOnce(thirdCase) .mockReturnValueOnce(thirdCase); const invoked = getTransactions(); await Promise.all([ invoked(_dispatch, _getState), invoked(_dispatch, _getState), invoked(_dispatch, _getState) ]); expect(_dispatch.mock.calls.length).toBe(0); walletGetTransactions.mockReset(); }); test("it should call dispatch twice in case when noMoreTransactions condition is fulfilled", async () => { walletGetTransactions .mockResolvedValueOnce(getMockedWalletGetTransactionResponse()) .mockResolvedValueOnce(getMockedWalletGetTransactionResponse({ empty: true })); const _getState = jest.fn(); const _dispatch = jest.fn(); _getState.mockReturnValue(getMockedGrpcState()); await getTransactions()(_dispatch, _getState); expect(_dispatch.mock.calls.length).toBe(2); expect(_dispatch.mock.calls[0][0]).toEqual({ type: "GETTRANSACTIONS_ATTEMPT" }); expect(_dispatch.mock.calls[1][0]).toHaveProperty("type", "GETTRANSACTIONS_COMPLETE"); expect(walletGetTransactions.mock.calls.length).toBe(2); walletGetTransactions.mockReset(); }); test("it should correctly dispatch actions in infinite loop case", async () => { walletGetTransactions.mockResolvedValue(getMockedWalletGetTransactionResponse()); const _getState = jest.fn(); const _dispatch = jest.fn(); _getState.mockReturnValue(getMockedGrpcState()); await getTransactions()(_dispatch, _getState); expect(_dispatch.mock.calls.length).toBe(2); expect(walletGetTransactions.mock.calls.length).toBe(3); expect(_dispatch.mock.calls[0][0]).toEqual({ type: "GETTRANSACTIONS_ATTEMPT" }); expect(_dispatch.mock.calls[1][0]).toHaveProperty("type", "GETTRANSACTIONS_COMPLETE"); walletGetTransactions.mockReset(); }); test("it should correctly dispatch actions in case of 'walletGetTransactions' error & break request flow immediately in infinite loop case", async () => { walletGetTransactions .mockResolvedValueOnce(getMockedWalletGetTransactionResponse({ empty: true })) .mockRejectedValueOnce("GENERIC ERROR") .mockResolvedValue(getMockedWalletGetTransactionResponse()); const _getState = jest.fn(); const _dispatch = jest.fn(); _getState.mockReturnValue(getMockedGrpcState()); await getTransactions()(_dispatch, _getState); expect(_dispatch.mock.calls.length).toBe(2); expect(_dispatch.mock.calls[0][0]).toEqual({ type: "GETTRANSACTIONS_ATTEMPT" }); expect(_dispatch.mock.calls[1][0]).toHaveProperty("type", "GETTRANSACTIONS_FAILED"); walletGetTransactions.mockReset(); }); test("it should call walletGetTransactions with correct arguments in infinite loop case", async () => { walletGetTransactions .mockResolvedValueOnce(getMockedWalletGetTransactionResponse({ empty: true })) .mockResolvedValueOnce(getMockedWalletGetTransactionResponse({ height: 2 })) .mockResolvedValue(getMockedWalletGetTransactionResponse()); const _getState = jest.fn(); const _dispatch = jest.fn(); _getState.mockReturnValue(getMockedGrpcState()); await getTransactions()(_dispatch, _getState); expect(walletGetTransactions.mock.calls.length).toBe(3); const [firstCall, secondCall, thirdCall] = walletGetTransactions.mock.calls; // unmined transactions expect(firstCall[1]).toBe(-1); expect(firstCall[2]).toBe(-1); expect(firstCall[3]).toBe(0); expect(secondCall[1]).toBe(2); expect(secondCall[2]).toBe(1); expect(secondCall[3]).toBe(10); expect(thirdCall[1]).toBe(1); expect(thirdCall[2]).toBe(1); expect(thirdCall[3]).toBe(10); walletGetTransactions.mockReset(); }); test("should call walletGetTransactions 3 times when filtered transactions length condition is fulfilled", async () => { walletGetTransactions.mockResolvedValueOnce( getMockedWalletGetTransactionResponse({ empty: true }) ); // 12 subsequent calls for (const num of range(12)) { walletGetTransactions.mockReturnValueOnce({ unmined: [], mined: getMockedTransactions(641 - num + 1) }); } const _getState = jest.fn(); const _dispatch = jest.fn(); _getState.mockReturnValue( getMockedGrpcState({ currentBlockHeight: 641, transactionsFilter: { listDirection: "desc", types: [2], direction: null } }) ); const result = await getTransactions()(_dispatch, _getState); expect(_dispatch.mock.calls.length).toBe(2); expect(walletGetTransactions.mock.calls.length).toBe(3); const [firstCall, secondCall, thirdCall] = walletGetTransactions.mock.calls; expect(firstCall[1]).toBe(-1); expect(firstCall[2]).toBe(-1); expect(firstCall[3]).toBe(0); expect(secondCall[1]).toBe(641); expect(secondCall[2]).toBe(1); expect(secondCall[3]).toBe(10); expect(thirdCall[1]).toBe(640); expect(thirdCall[2]).toBe(1); expect(thirdCall[3]).toBe(10); expect(result.unminedTransactions.length).toBe(0); expect(result.minedTransactions.length).toBe(5); expect(result.recentRegularTransactions.length).toBe(0); expect(result.recentStakeTransactions.length).toBe(5); walletGetTransactions.mockReset(); }); test("should return correct state change shape with 'REGULAR' type transaction filter", async () => { walletGetTransactions .mockResolvedValueOnce({ unmined: unminedMockedTransactions, mined: [] }) .mockResolvedValueOnce(getMockedWalletGetTransactionResponse()) .mockResolvedValueOnce(getMockedWalletGetTransactionResponse({ empty: true })); const _getState = jest.fn(); const _dispatch = jest.fn(); _getState.mockReturnValue(getMockedGrpcState()); const result = await getTransactions()(_dispatch, _getState); expect(walletGetTransactions.mock.calls.length).toBe(3); expect(_dispatch.mock.calls.length).toBe(2); expect(result.unminedTransactions.length).toBe(1); expect(result.minedTransactions.length).toBe(0); expect(result.recentRegularTransactions.length).toBe(1); expect(result.lastTransaction).toEqual({ amount: 30000000000, creditAddresses: [ "22tv7nd31sMmD8BpcVRJAWQLqYCjaCuqpWpz", "22u4VtFDzXDT517DFfCLRM8i5t814pZXePBK" ], creditAmounts: 30000000000, txHash: "933bb306b3e71ac0d7c89f8dd2884f9190a1b7049e0632ae5201e1fb59377849", txType: "Coinbase", type: 4, index: 0, height: 1 }); walletGetTransactions.mockReset(); }); test("should return correct state change shape with 'VOTE' type transaction filter", async () => { walletGetTransactions .mockResolvedValueOnce({ unmined: unminedMockedTransactions, mined: [] }) .mockResolvedValueOnce({ unmined: [], mined: mockedTransactions }) .mockResolvedValueOnce(getMockedWalletGetTransactionResponse({ empty: true })); const _getState = jest.fn(); const _dispatch = jest.fn(); _getState.mockReturnValue( getMockedGrpcState({ currentBlockHeight: 641, transactionsFilter: { listDirection: "desc", types: [2], direction: null } }) ); const result = await getTransactions()(_dispatch, _getState); expect(_dispatch.mock.calls.length).toBe(2); expect(walletGetTransactions.mock.calls.length).toBe(3); const [firstCall, secondCall, thirdCall] = walletGetTransactions.mock.calls; expect(firstCall[1]).toBe(-1); expect(firstCall[2]).toBe(-1); expect(firstCall[3]).toBe(0); expect(secondCall[1]).toBe(641); expect(secondCall[2]).toBe(1); expect(secondCall[3]).toBe(10); expect(thirdCall[1]).toBe(640); expect(thirdCall[2]).toBe(1); expect(thirdCall[3]).toBe(10); expect(result.unminedTransactions.length).toBe(1); expect(result.minedTransactions.length).toBe(5); expect(result.recentRegularTransactions.length).toBe(0); expect(result.recentStakeTransactions.length).toBe(6); expect(result.lastTransaction).toEqual(mockedTransactions[mockedTransactions.length - 1]); walletGetTransactions.mockReset(); }); });
from pathlib import Path import click import logging import pandas as pd import SimpleITK as sitk from src.evaluation.scores import dice @click.command() @click.argument('ground_truth_folder', type=click.Path(exists=True), default='data/gt') @click.argument('prediction_folder', type=click.Path(exists=True), default='data/results/') @click.argument('output_filepath', type=click.Path(), default='data/results/results.csv') def main(prediction_folder, ground_truth_folder, output_filepath): logger = logging.getLogger(__name__) logger.info('Computing Dice scores') results_df = pd.DataFrame(columns=['PatientID', 'Dice score']) groundtruth_files_list = [ f for f in Path(ground_truth_folder).rglob('*GTVt.nii') ] for path in groundtruth_files_list: np_image_gt = sitk.GetArrayFromImage( sitk.ReadImage(str(path.resolve()))) patient_name = path.name[0:10] prediction_files = [ f for f in Path(prediction_folder).rglob(patient_name + '*GTVt.nii') ] if len(prediction_files) > 1: raise RuntimeError( 'There is too many prediction files for patient {}'.format( patient_name)) # check_segmentation(sitk_pred) np_image_pred = sitk.GetArrayFromImage( sitk.ReadImage(str(prediction_files[0].resolve()))) score = dice(np_image_gt, np_image_pred) results_df = results_df.append( { 'PatientID': patient_name, 'Dice score': score }, ignore_index=True) results_df.to_csv(output_filepath) if __name__ == '__main__': log_fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' logging.basicConfig(level=logging.INFO, format=log_fmt) logging.captureWarnings(True) main()
// MENU SHOW const navMenu = document.getElementById('nav-menu'), navToggle = document.getElementById('nav-toggle'), navClose = document.getElementById('nav-close') if(navToggle){ navToggle.addEventListener('click',() => { navMenu.classList.add('show-menu') }) } if(navClose){ navClose.addEventListener('click', () =>{ navMenu.classList.remove('show-menu') }) } /* Remove menu mobile */ const navLink = document.querySelectorAll('.nav__link') function linkAction(){ const navMenu = document.getElementById('nav-menu') // When we click on each nav__link, we remove the show-menu class navMenu.classList.remove('show-menu') } navLink.forEach(n => n.addEventListener('click', linkAction)) /* Acordion Skills */ const skillsContent = document.getElementsByClassName('skills__content'), skillsHeader = document.querySelectorAll('.skills__header') function toggleSkills(){ let itemClass = this.parentNode.className for(i = 0; i < skillsContent.length; i++){ skillsContent[i].className = 'skills__content skills__close' } if(itemClass === 'skills__content skills__close'){ this.parentNode.className = 'skills__content skills__open' } } skillsHeader.forEach((el) => { el.addEventListener('click', toggleSkills) }) /* Portfolio swiper */ let swiperPortfolio = new Swiper(".portfolio__container", { pagination: { el: ".swiper-pagination", }, mousewheel: true, keyboard: true, loop: true, grabCursor: true }); // Testimonials swiper let swiperTestimonials = new Swiper(".testimonial__container", { loop: true, grabCursor: true, spaceBetween:48, pagination: { el: ".swiper-pagination", clickable: true, dinamicBullets: true, }, mousewheel: true, keyboard: true, }); //Scroll Reveal const scrollReveal = ScrollReveal({ origin: 'top', distance: '30px', duration: 700, reset: true }) scrollReveal.reveal( `#home, #about, #skills, #portfolio, #contact`, {interval: 300}) /* Scrolls section ative */ const sections = document.querySelectorAll('section[id]') function scrollActive(){ const scrollY = window.pageYOffset sections.forEach(current =>{ const sectionHeight = current.offsetHeight const sectionTop = current.offsetTop - 50; sectionId = current.getAttribute('id') if(scrollY > sectionTop && scrollY <= sectionTop + sectionHeight){ document.querySelector('.nav__menu a[href*=' + sectionId + ']').classList.add('active-link') }else{ document.querySelector('.nav__menu a[href*=' + sectionId + ']').classList.remove('active-link') } }) } window.addEventListener('scroll', scrollActive) /* Shadow Header */ function scrollHeader(){ const nav = document.getElementById('header') if(this.scrollY >= 80) nav.classList.add('scroll-header'); else nav.classList.remove('scroll-header') } window.addEventListener('scroll', scrollHeader) /* Show scroll top */ function scrollUp(){ const scrollUp = document.getElementById('scroll-up'); if(this.scrollY >= 500) scrollUp.classList.add('show-scroll'); else scrollUp.classList.remove('show-scroll') } window.addEventListener('scroll', scrollUp)
import React, {Component} from 'react' import styled from 'styled-components' import Button from 'react-bootstrap/Button' import InputGroup from 'react-bootstrap/InputGroup' import FormControl from 'react-bootstrap/FormControl' import ButtonToolbar from 'react-bootstrap/ButtonToolbar' import ToggleButton from 'react-bootstrap/ToggleButton' import ToggleButtonGroup from 'react-bootstrap/ToggleButtonGroup' import Alert from 'react-bootstrap/Alert' import Cache from './cache' export default class Question extends Component{ constructor(props){ super(props) this.state={ mods: [], answers: [], valid: false, show: false, } } componentDidMount(){ let temp = [] let ans = [] if(Cache.state.currentCol.Mods.length > 0){ Cache.state.currentCol.Mods.map( item => { ans.push([]) if( typeof item.modQuestions === "string"){ item.modQuestions = JSON.parse(item.modQuestions) } return temp.push(item) } ) } if(Cache.state.currentExh.exhMods.length > 0){ Cache.state.currentExh.exhMods.map( item => { ans.push([]) return temp.push(item) } ) } this.setState({mods: temp, answers: ans}) } Alert() { if (this.state.show) { return ( <Alert variant="danger" onClose={() => this.setState({show: false})} dismissible> <Alert.Heading>Error!</Alert.Heading> <p> You have not completed all the questions. Please finish any uncompleted questions and try again. </p> </Alert> ); } } validate(){ let res = true let ans = this.state.answers let mods = this.state.mods for(let i = 0; i < ans.length; i++){ if(ans[i].length !== mods[i].modQuestions.length){ res = false break } else if(ans[i].includes(null) || ans[i].includes("") ){ res = false break } } return res } saveAns(ans, key){ let temp = this.state.answers if(temp[key.mod].length !== key.ques){ while(temp[key.mod].length < key.ques){ temp[key.mod].push(null) } } temp[key.mod][key.ques] = ans this.setState({answers: temp}) } showQuestion(ques, key){ switch (ques.qType) { //Text questions //Single Line Free Text case "SLFT": return( <ModQ> <h6>{ques.qTitle}</h6> <InputGroup> <FormControl placeholder="Input Text" onChange={ (e)=>this.saveAns(e.target.value, key) } /> { ques.qExtra.other ? <FormControl placeholder="Other" onChange={ (e)=>this.saveAns(e.target.value, key) } /> : null } </InputGroup> </ModQ> ) //Multi Line Free Text case "MLFT": return( <ModQ> <h6>{ques.qTitle}</h6> <InputGroup> <FormControl as="textarea" placeholder="Input Text" onChange={ (e)=>this.saveAns(e.target.value, key) } /> { ques.qExtra.other ? <FormControl placeholder="Other" onChange={ (e)=>this.saveAns(e.target.value, key) } /> : null } </InputGroup> </ModQ> ) //Scale Questions //Scale Binary case "SCABIN": return( <ModQ> <h6>{ques.qTitle}</h6> <ButtonToolbar> <ToggleButtonGroup type="radio" name={ques.qTitle} onChange={ (e)=>this.saveAns(e, key) } > <ToggleButton variant="outline-secondary" value={true} >{ques.qExtra.yes}</ToggleButton> <ToggleButton variant="outline-secondary" value={false} >{ques.qExtra.no}</ToggleButton> </ToggleButtonGroup> { ques.qExtra.other ? <FormControl placeholder="Other" onChange={ (e)=>this.saveAns(e.target.value, key) } /> : null } </ButtonToolbar> </ModQ> ) //Scale Likert case "SCALIK": return( <ModQ> <h6>{ques.qTitle}</h6> <ButtonToolbar> <ToggleButtonGroup type="radio" name={ques.qTitle} onChange={ (e)=>this.saveAns(e, key) } > <ToggleButton variant="outline-secondary" value={0} >{ques.qExtra.min}</ToggleButton> <ToggleButton variant="outline-secondary" value={1} style={{width: '45px'}}></ToggleButton> <ToggleButton variant="outline-secondary" value={2} style={{width: '45px'}}></ToggleButton> <ToggleButton variant="outline-secondary" value={3} style={{width: '45px'}}></ToggleButton> <ToggleButton variant="outline-secondary" value={4} >{ques.qExtra.max}</ToggleButton> </ToggleButtonGroup> { ques.qExtra.other ? <FormControl placeholder="Other" onChange={ (e)=>this.saveAns(e.target.value, key) } /> : null } </ButtonToolbar> </ModQ> ) //Scale Custom case "SCACUS": let arr = [] for(let i = 0; i < parseInt(ques.qExtra.step); i++){ arr.push(i) } return( <ModQ> <h6>{ques.qTitle}</h6> <ButtonToolbar> <ToggleButtonGroup type="radio" name={ques.qTitle} onChange={ (e)=>this.saveAns(e, key) } > { arr.map( item =>{ return <ToggleButton variant="outline-secondary" value={ item === 0 ? parseInt(ques.qExtra.min) : parseInt(ques.qExtra.min) + item } >{ item === 0 ? ques.qExtra.min : item === parseInt(ques.qExtra.step) - 1 ? ques.qExtra.max : null }</ToggleButton> } ) } </ToggleButtonGroup> { ques.qExtra.other ? <FormControl placeholder="Other" onChange={ (e)=>this.saveAns(e.target.value, key) } /> : null } </ButtonToolbar> </ModQ> ) //Choice Questions //Choice Single case "CHOSIN": return( <ModQ> <h6>{ques.qTitle}</h6> <ButtonToolbar> <ToggleButtonGroup type="radio" name={ques.qTitle} vertical onChange={ (e)=>this.saveAns(e, key) } > { ques.qExtra.choiceList.map( (item, i) =>{ return <ToggleButton variant="outline-secondary" value={i} >{ item }</ToggleButton> } ) } </ToggleButtonGroup> { ques.qExtra.other ? <FormControl placeholder="Other" onChange={ (e)=>this.saveAns(e.target.value, key) } /> : null } </ButtonToolbar> </ModQ> ) //Choice Multiple case "CHOMUL": return( <ModQ> <h6>{ques.qTitle}</h6> <ButtonToolbar> <ToggleButtonGroup type="checkbox" vertical onChange={ (e)=>this.saveAns(e, key) } > { ques.qExtra.choiceList.map( (item, i) =>{ return <ToggleButton variant="outline-secondary" value={i} >{ item }</ToggleButton> } ) } </ToggleButtonGroup> { ques.qExtra.other ? <FormControl placeholder="Other" onChange={ (e)=>this.saveAns(e.target.value, key) } /> : null } </ButtonToolbar> </ModQ> ) default: console.log("Other:" + ques.qType) break; } } render(){ return ( <Body> <Button variant="secondary" onClick={this.props.return} >Back</Button><br/> <h3>{Cache.state.currentExh.exhName}</h3> { this.state.mods.length > 0 ? this.state.mods.map( (item,i) => { return <div key={i} ><h4>{item.modName}</h4> { item.modQuestions.map( (elem, d) => { let key = { mod: i, ques: d } return this.showQuestion(elem, key) } ) } </div> } ) : null } {this.Alert()} <Button variant="secondary" onClick={()=>{ if(this.validate()){ Cache.updateUser(this.state.answers, this.state.mods) Cache.state.completedExh.push("" + Cache.state.currentCol.ID + Cache.state.currentExh.exhID) this.props.return() } else{ this.setState({show: true}) console.log("Something went wrong") } }} >Finish</Button> </Body> ) } } const Body = styled.div` margin: 3rem auto; display: flex; flex-direction: column; flex-wrap: wrap; align-items: center; justify-content: center; ` const ModQ = styled.div` display: flex; flex-direction: column; flex-wrap: wrap; align-items: center; justify-content: center; `
var searchData= [ ['name',['name',['../structcxxopts_1_1_help_group_details.html#abc389252a862724a1404d3c22fda6fc2',1,'cxxopts::HelpGroupDetails']]], ['name_5f',['name_',['../classbnssassembler_1_1_symbol.html#aa4d48274d378011c7eddc09fd862878d',1,'bnssassembler::Symbol::name_()'],['../classbnssassembler_1_1_symbol_data.html#af8e28fdc3e5c25c337aa8e36b9bd30f5',1,'bnssassembler::SymbolData::name_()'],['../classbnssassembler_1_1_symbol_definition.html#abc70285f590abe24b39f59aedb032071',1,'bnssassembler::SymbolDefinition::name_()'],['../classbnssassembler_1_1_symbol_definition_token.html#acdf384ab32d20a39394362716f9b597d',1,'bnssassembler::SymbolDefinitionToken::name_()'],['../classbnssassembler_1_1_symbol_token.html#acaa15e56f8fe7b0db24e17503b10584f',1,'bnssassembler::SymbolToken::name_()'],['../classbnssemulator_1_1_symbol_data.html#a4fe2a54690a7a454f6fccf25bade9fe9',1,'bnssemulator::SymbolData::name_()']]], ['next_5f',['next_',['../classbnssassembler_1_1_line_parser.html#ac85ad0f08b92d0ce1cd039caeec71dad',1,'bnssassembler::LineParser::next_()'],['../classbnssassembler_1_1_operand_parser.html#ac5e626c49d494d1429e44fbf1fce50c8',1,'bnssassembler::OperandParser::next_()']]], ['num_5fof_5fregisters',['NUM_OF_REGISTERS',['../namespacebnssassembler.html#a9c2fa6c7b4cdd10008e56e84b67a35dd',1,'bnssassembler']]] ];
var step = '<font class="fontSize">' + '<p>Test Purpose: </p>' + '<p>Verifies the device is able to handle pageVisible event when app page hidden/display.</p>' + '<p>Expected Result: </p>' + '<p>Test passes if the visibilitystate/hidden attribute is set to hidden/true for hidden state and visible/false for display state.</p>' + '</font>'