hexsha
string
size
int64
ext
string
lang
string
max_stars_repo_path
string
max_stars_repo_name
string
max_stars_repo_head_hexsha
string
max_stars_repo_licenses
list
max_stars_count
int64
max_stars_repo_stars_event_min_datetime
string
max_stars_repo_stars_event_max_datetime
string
max_issues_repo_path
string
max_issues_repo_name
string
max_issues_repo_head_hexsha
string
max_issues_repo_licenses
list
max_issues_count
int64
max_issues_repo_issues_event_min_datetime
string
max_issues_repo_issues_event_max_datetime
string
max_forks_repo_path
string
max_forks_repo_name
string
max_forks_repo_head_hexsha
string
max_forks_repo_licenses
list
max_forks_count
int64
max_forks_repo_forks_event_min_datetime
string
max_forks_repo_forks_event_max_datetime
string
content
string
avg_line_length
float64
max_line_length
int64
alphanum_fraction
float64
67261b9c9753ae38f5d6e4a611dc2da2eee3e974
2,598
js
JavaScript
telos-create/telos-create.js
Sesacash-Weather-Project/node-red-server-processing
feb507da13169f70bcba45f12c1539a6e7b2aff7
[ "MIT" ]
null
null
null
telos-create/telos-create.js
Sesacash-Weather-Project/node-red-server-processing
feb507da13169f70bcba45f12c1539a6e7b2aff7
[ "MIT" ]
1
2020-05-27T21:08:25.000Z
2020-05-27T21:08:25.000Z
telos-create/telos-create.js
Sesacash-Weather-Project/node-red-server-processing
feb507da13169f70bcba45f12c1539a6e7b2aff7
[ "MIT" ]
null
null
null
const { Api, JsonRpc, RpcError, Serialize } = require('eosjs'); const { JsSignatureProvider } = require('eosjs/dist/eosjs-jssig'); // development only const ecc = require('eosjs-ecc'); const fetch = require('node-fetch'); // node only; not needed in browsers const { TextEncoder, TextDecoder } = require('util'); // node only; native TextEncoder/Decoder const fs = require('fs'); var _ = require('lodash'); const trans = require('./lib/transaction_modules.js'); module.exports = function(RED) { function TelosCreateNode(config) { RED.nodes.createNode(this,config); var node = this; //node.blockchain = config.blockchain; // Don't need. Chain ID should be enough node.chainid = config.chainid; if (config.endpoint === "other") { node.endpoint = config.customendpoint; } else { node.endpoint = config.endpoint; } node.privkey = fs.readFileSync(config.privkey, 'utf8').trim(); node.pubkey = ecc.privateToPublic(node.privkey); node.inputtype = config.inputtype; node.subaccount = config.name; // Initialize eojs API const signatureProvider = new JsSignatureProvider([node.privkey]); const rpc = new JsonRpc(node.endpoint, { fetch }); const api = new Api({ rpc, signatureProvider, textDecoder: new TextDecoder(), textEncoder: new TextEncoder() }); let connect = true; (async () => { // Test that chain ID is correct try { // UNCOMMENT FOLLOWING 2 LINES const info = await rpc.get_info(); //get information from http endpoint } catch (e) { if (e instanceof RpcError) // Should specify error due to 'unknown key' { console.log("Unexpected RPC error when checking account's contract."); connect = false; } } if (connect){ console.log("Node looks good. Connecting node to injection."); // Function that runs every time data is injected node.on('input', function(msg){ trans.create_new_account('noderedtelos',node.subaccount,api); node.send(msg); // continue sending message through to outputs if necessary }); } })(); // End of async } // end TelosTransactNode definition RED.nodes.registerType("telos-create",TelosCreateNode); };
35.589041
120
0.571209
6726830289fdbba393772335f33c03a477e016de
931
js
JavaScript
commands/general/ping.js
UtopicUnicorns/Artemis_v2
aa963e7eca08fa69894d317851c3688aeec09bdc
[ "MIT" ]
15
2020-05-12T05:07:29.000Z
2021-05-09T18:24:34.000Z
commands/general/ping.js
UtopicUnicorns/artemis
aa963e7eca08fa69894d317851c3688aeec09bdc
[ "MIT" ]
19
2020-05-12T01:02:24.000Z
2021-01-02T09:37:31.000Z
commands/general/ping.js
UtopicUnicorns/Artemis_v2
aa963e7eca08fa69894d317851c3688aeec09bdc
[ "MIT" ]
10
2020-06-24T18:54:43.000Z
2021-09-29T12:13:51.000Z
//Load modules const npm = require("../../modules/NPM.js"); npm.npm(); //load database dbinit = require("../../modules/dbinit.js"); dbinit.dbinit(); //start module.exports = { category: `general`, name: "ping", description: "[general] ping", explain: `This is just a ping command, checks the lag between messages... Example usage: \`!ping\``, async execute(message) { //build prefix const prefixstart = getGuild.get(message.guild.id); const prefix = prefixstart.prefix; //update usage usage = getUsage.get("ping"); usage.number++; setUsage.run(usage); //ping const m = await message.channel .send("Ping?") .catch((err) => console.log("")); if (!m) return; m.edit( `Pong! Latency is ${ m.createdTimestamp - message.createdTimestamp }ms. API Latency is ${Math.round(message.client.ws.ping)}ms` ).catch((err) => console.log("")); }, };
23.275
75
0.614393
67279f4f912112cdca26a61ab461d68aa76691f9
1,284
js
JavaScript
src/flow/mocha.js
stvvan/sdk-js
fc0f38883934f6d1e1bb06aa7a85ef847c875963
[ "Apache-2.0" ]
1
2021-06-02T14:58:49.000Z
2021-06-02T14:58:49.000Z
src/flow/mocha.js
stvvan/sdk-js
fc0f38883934f6d1e1bb06aa7a85ef847c875963
[ "Apache-2.0" ]
null
null
null
src/flow/mocha.js
stvvan/sdk-js
fc0f38883934f6d1e1bb06aa7a85ef847c875963
[ "Apache-2.0" ]
null
null
null
// @flow declare class describe { static(description: string, spec: () => void): void; static only(description: string, spec: () => void): void; static skip(description: string, spec: () => void): void; } declare class context { static(description: string, spec: () => void): void; static only(description: string, spec: () => void): void; static skip(description: string, spec: () => void): void; } declare class it { static(description: string, spec: () => void | Promise<*>): void; static only(description: string, spec: () => void | Promise<*>): void; static skip(description: string, spec: () => void | Promise<*>): void; } declare class xit { static(description: string, spec: () => void | Promise<*>): void; static only(description: string, spec: () => void | Promise<*>): void; static skip(description: string, spec: () => void | Promise<*>): void; } declare class specify { static(description: string, spec: () => void | Promise<*>): void; } declare class before { static(spec: () => void | Promise<*>): void; } declare class after { static(spec: () => void | Promise<*>): void; } declare class beforeEach { static(spec: () => void | Promise<*>): void; } declare class afterEach { static(spec: () => void | Promise<*>): void; }
25.68
72
0.626947
672823e175ba6e57c0c437bf79a917d4174ce1ba
2,902
js
JavaScript
public/js/common.js
phptangem/power.app
f40de6ea65a16c82bbd98de6105003b3876d8ae0
[ "MIT" ]
null
null
null
public/js/common.js
phptangem/power.app
f40de6ea65a16c82bbd98de6105003b3876d8ae0
[ "MIT" ]
null
null
null
public/js/common.js
phptangem/power.app
f40de6ea65a16c82bbd98de6105003b3876d8ae0
[ "MIT" ]
null
null
null
function ajaxRequest(param, requestUrl, successCallback) { param['_token'] = $('input[name="_token"]').val(); $.ajax({ type: 'POST', url: requestUrl, data: param, // headers: {'X-CSRF-TOKEN': labUser.token}, dataType: 'json', success: function(data) { if (successCallback && (successCallback instanceof Function)) { successCallback(data); } }, error: function(data){ $("#doSave").removeAttr('disabled'); var errorinfo = ''; var return_data = data.responseJSON ? data.responseJSON : eval('('+data.responseText+')'); $.each(return_data,function(i,j){ if(errorinfo == ''){ errorinfo = j[0]; alert(errorinfo); } }) } }); }; /** * 过滤首尾空格 */ function LTrim(str) { return str.replace(/^\s+/, ""); } /** * 参数说明: 根据长度截取先使用字符串,超长部分追加… str 对象字符串 len 目标字节长度 返回值: 处理结果字符串 */ function cutString(str, len) { var str_len = str.length; if (str_len <= len) { return str; } else { return str.substring(0, len) + '...'; } } // html转义 function encodeHtml(str) { var s = ""; if (str.length == 0) return ""; s = str.replace(/&/g, "&gt;"); s = s.replace(/</g, "&lt;"); s = s.replace(/>/g, "&gt;"); s = s.replace(/ /g, "&nbsp;"); s = s.replace(/\'/g, "&#39;"); s = s.replace(/\"/g, "&quot;"); s = s.replace(/\n/g, "<br>"); return s; } var openBrowse; var fileUpload; //$(function() { openBrowse = function(filename, file) { var ie = navigator.appName == "Microsoft Internet Explorer" ? true : false; if (ie) { $(file).click(); var file = $(file).val(); $(filename).val(file); } else { var a = document.createEvent("MouseEvents");// FF的处理 a.initEvent("click", true, true); document.getElementById(file).dispatchEvent(a); } }; function uploadCallBack(name, path,filetype, filesize,filename, input_name,message,error) { //var img_show = '/public/images/upload/' + path + '/' + name; //var img = '/public/images/upload/' + path + '/' + name; $("input[name='"+input_name+"']").val(path); $("input[name='"+input_name+"_name']").val(filename); $("input[name='"+input_name+"_filetype']").val(filetype); $("input[name='"+input_name+"_filesize']").val(filesize); $("img[name='"+input_name+"']").attr("src", name); if(error) { $("#img_info").html(message); }else{ $("#img_info").html(''); } //$("#photo_show").attr("src", img_show); } fileUpload = function(fileId, input_name) { $.ajaxFileUpload({ url: uploadUrl , secureuri: false, // 是否启用安全提交 dataType: 'json', // 数据类型 fileElementId: fileId, // 表示文件域ID // 提交成功后处理函数 html为返回值,status为执行的状态 success: function(html, status) { uploadCallBack(html.path, html.url, html.filetype, html.filesize, html.filename, input_name,html.message,html.error); }, // 提交失败处理函数 error: function(html, status, e) { console.log(html); } }) } //});
25.017241
121
0.589249
67297f753f31ca0f3c7bed6b30ec293695c2cb91
3,016
js
JavaScript
client/src/context/member/MemberState.js
nicolasleivab/React-Team-Builder
e0a2d58e4e56d548c8fedd3a5513fe2a605e638f
[ "MIT" ]
2
2021-03-18T06:02:15.000Z
2021-06-21T16:34:38.000Z
client/src/context/member/MemberState.js
nicolasleivab/React-Team-Builder
e0a2d58e4e56d548c8fedd3a5513fe2a605e638f
[ "MIT" ]
6
2020-05-04T12:18:43.000Z
2022-02-27T00:19:56.000Z
client/src/context/member/MemberState.js
nicolasleivab/React-Team-Builder
e0a2d58e4e56d548c8fedd3a5513fe2a605e638f
[ "MIT" ]
1
2020-12-10T11:28:03.000Z
2020-12-10T11:28:03.000Z
import React, { useReducer } from 'react'; import MemberContext from './memberContext'; import memberReducer from './memberReducer'; import axios from 'axios'; import { GET_MEMBERS, CLEAR_MEMBERS, ADD_MEMBER, MEMBER_ERROR, DELETE_MEMBER, SET_CURRENT, CLEAR_CURRENT, UPDATE_MEMBER, FILTER_MEMBERS, CLEAR_FILTER } from '../types'; const MemberState = props => { const initialState = { members: null, current: null, filtered: null, error: null, loading: true }; const [state, dispatch] = useReducer(memberReducer, initialState); // Get Members const getMembers = async () => { try { const res = await axios.get('/api/teamMembers'); dispatch({ type: GET_MEMBERS, payload: res.data }); } catch (err) { dispatch({ type: MEMBER_ERROR, payload: err.response.msg }); } }; // Add Member const addMember = async member => { const config = { headers: { 'Content-Type': 'application/json' } }; try { const res = await axios.post('/api/teamMembers', member, config); dispatch({ type: ADD_MEMBER, payload: res.data }); } catch (err) { dispatch({ type: MEMBER_ERROR, payload: err.response.msg }); } }; // Delete Member const deleteMember = async member => { try { await axios.delete(`/api/teamMembers/${member._id}`); dispatch({ type: DELETE_MEMBER, payload: member }); } catch (err) { dispatch({ type: MEMBER_ERROR, payload: err.response.msg }); } }; // Update Member const updateMember = async member => { const config = { headers: { 'Content-Type': 'application/json' } }; try { const res = await axios.put( `/api/teamMembers/${member._id}`, member, config ); dispatch({ type: UPDATE_MEMBER, payload: res.data }); } catch (err) { dispatch({ type: MEMBER_ERROR, payload: err.response.msg }); } }; // Clear Members const clearMembers = () => { dispatch({ type: CLEAR_MEMBERS }); }; // Set Current Member const setCurrent = member => { dispatch({ type: SET_CURRENT, payload: member }); }; // Clear Current Member const clearCurrent = () => { dispatch({ type: CLEAR_CURRENT }); }; // Filter Members const filterMembers = text => { dispatch({ type: FILTER_MEMBERS, payload: text }); }; // Clear Filter const clearFilter = () => { dispatch({ type: CLEAR_FILTER }); }; return ( <MemberContext.Provider value={{ members: state.members, current: state.current, filtered: state.filtered, error: state.error, loading: state.loading, getMembers, addMember, deleteMember, setCurrent, clearCurrent, updateMember, filterMembers, clearFilter, clearMembers }} > {props.children} </MemberContext.Provider> ); }; export default MemberState;
22.176471
71
0.590849
672ad906641b1b6474ba6ff320b2df91751ad17a
23,666
js
JavaScript
2018/flack/application/static/js/script.js
133794m3r/cs50-web
1f695cd7fb4ec368ec45e0d3154dd7eebc2c81e2
[ "MIT" ]
null
null
null
2018/flack/application/static/js/script.js
133794m3r/cs50-web
1f695cd7fb4ec368ec45e0d3154dd7eebc2c81e2
[ "MIT" ]
null
null
null
2018/flack/application/static/js/script.js
133794m3r/cs50-web
1f695cd7fb4ec368ec45e0d3154dd7eebc2c81e2
[ "MIT" ]
null
null
null
Array.prototype.removeItem=function(needle){ let index = this.indexOf(needle) if(index > -1){ return this.splice(index,1); } } Date.prototype.toLocalTime=function() { return this.toLocaleString('en-us', {timeZone: 'America/New_York'}) } //the globals var g_channels = []; var g_pms = {}; var g_pm_msgs = {}; var g_users = []; //sets the current channel to the one stored within the local storage. var g_current_channel = localStorage.getItem("current_channel"); var g_privates = {'names':[],'passwords':[],'full_name':[]}; //same with the username. var g_username = localStorage.getItem('username') var socket; var g_private = false; //once it's all setup I have this function wait till everything else is loaded before I start doing things. $('body').ready(()=>{ document.getElementById('msg_block').scrollTop=100000000000; //create the actual socket. socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port); //if they don't already have a username. if (!g_username){ console.log('no username'); //prompt them for one. $("#main_modal").modal('toggle'); $('#modal_input').data('type','username'); } else{ //otherwise add them to the list of users add_user(g_username) //and make them rejoin all of their channels. socket.emit('rejoin',{'username':g_username,'channel':g_current_channel}); } $('#modal_button').on('click',()=>{ let input=$("#modal_input"); let input_val=input.val().replace(/\ /g,'_'); let type=input.data('type'); input.val(''); let total_privates = (g_privates["names"] == undefined?0:g_privates["names"].length) //switch through types till I figure out which one it is to properly emit the data on the socket. switch(type){ //new username/bad username. case "username": //let username=input.val(); g_username=input_val; if(input_val in g_users){ //tell them that the username already exists and. $('#main_modal_title').text('This user already exists. Please select another.'); } else { //try to create the user on the server. socket.emit('new_user', {'username': input_val}); } break; //the case where they're joining a channel through the button. case "join_channel": if(g_channels.indexOf(input_val) !== -1){ //can't recreate a channel that already exists. $('#main_modal_title').text('This channel doesn\'t exist. Please check your spelling'); } else{ //do the join event with this channel. socket.emit("join",{'channel':input_val}); } break; case "create_channel": //let name=input.val(); //when they're creating a channel. if(g_channels.indexOf(input_val)!== -1){ //already have it existing in the general channels. $('#main_modal_title').text('This channel already exists. Please select another name.'); } else if ((total_privates > 0) && (g_private['names'].indexOf(input_val) !== -1)){ //it already existed in the private channels they're a member of. This prevents them from creating a channel //with the same name as one they're already in/aware of. $('#main_modal_title').text('This channel already exists. Please select another name.'); } else { //create teh channel. socket.emit('create_channel',{'channel':input_val}); } break; case "create_private_channel": //let name=input.val(); //see if the channel exists in the global channels. if(g_channels.indexOf(input_val) !== -1){ $('#main_modal_title').text('This channel already exists. Please select another name.'); } else if ((total_privates > 0)&& (g_privates['names'].indexOf(input_val) !== -1)){ //same here don't let them create a channel with the same name. $('#main_modal_title').text('This channel already exists. Please select another name.'); } else { //otherwise it's time to try and create it. let el=document.getElementById('channel_password'); //get the password value. let password=el.value; //reset it to blank. el.value=''; //remove that row. $('#password_row').remove(); //emit the event to create the channel with the name, their username and the password. socket.emit('create_private_channel',{'channel':input_val,'username':g_username,'password':password}) } break; case "join_private": //this is when they try to join a private channel. let password=$('#channel_password').val(); $('#channel_password').val(''); //the channel must not be a public one. if(g_channels.indexOf(input_val) !== -1){ $('#main_modal_title').text("This channel is a regular channel no password is required.") } else if(password === ''){ //the password can't be blank. $('#main_modal_title').text("The password cannot be blank."); } else{ //remove the password row. $('#password_row').remove() //emit the join event with the password and their username so that the server can add it to their list of joined //channels. socket.emit("join",{"username":g_username,"channel":input_val,"password":password}); } break; case "create_pm": //when they create a private message to a new user. let msg=$('#user_message').val(); //remove the room row. $('#pm_row').remove() //remove the message row. $('#message_row').remove() //emit the event to the server with who it was from, and who it was to. Also send the message to the server. let resp={'username':g_username,'to_user':input_val,'msg':msg}; let to_user='' let found=false for(let key in g_pms){ to_user = g_pms[key]['to']; if(to_user === input_val){ found=true; socket.emit("pm",resp); break; } } //emit the event to the server. if(!found){ socket.emit("create_pm_room", resp); } break; } }); //when the add channel button is clicked do this. $('#add_channel').on('click',()=>{ //create the modal for the add channel event. $('#main_modal_title').text('Please enter the channel name'); $('#modal_label').text('Channel Name:') $('#input_row') $('.row2').remove() if(document.getElementById('private_channel_toggle') == null){ let div='<div class="col">Private <input type="checkbox" id="private_channel_toggle" onclick=""></div>' $('#input_row').append(div); } //if they click the private room checkbox then it'll toggle the password rwo. $('#private_channel_toggle').on('click',function(){ if ($(this).prop('checked')) { $('#modal_input').data('type', 'create_private_channel'); if(document.getElementById('password_row') == null) { $('#input_row').after('<div class="row row2" id="password_row"><div class="col"><label for="channel_password">Password:</label><input type="text" id="channel_password"></div></div>') } } else { $('#modal_input').data('type', 'create_channel'); $('#password_row').remove(); } }); //set the type to create channel. $('#modal_input').data('type','create_channel'); console.log('add_channel') //toggle the modal after it's all drawn. $("#main_modal").modal('toggle'); }); //when they try to join it setup this modal. $('#join_private_channel').on('click',()=>{ $('.row2').remove(); $('#main_modal_title').text('Please enter the channel\'s name'); $('#modal_label').text('Channel Name:'); //make sure the toggle is checked. $('#private_channel_toggle').checked(true); if(document.getElementById('password_row') !== null) { $('#password_row').remove(); $('#input_row').after(`<div class="row row2" id="password_row"><div class="col"><label for="channel_password">Channel Password </label><input id="channel_password" type="text"></div></div>`); } else{ $('#input_row').after(`<div class="row row2" id="password_row"><div class="col"><label for="channel_password">Channel Password </label><input id="channel_password" type="text"></div></div>`); } $('#modal_input').data('type','join_private'); console.log('join private') $("#main_modal").modal('toggle'); }); //the first of our socket events. This one is when the user already exists event. socket.on("user_exists",data=>{ //clear their local storage as it's invalid. localStorage.clear() //create the information modal to help them realize that they have this error. $('#input_row').html(`<div class="col"><label for="modal_input" id="modal_label">Username</label> <input id="modal_input" class="form-control w-50" type="text" data-type="username" onkeypress="modal_update(event)"></div>`); $('#main_modal_title').text(data['error']); console.log('user already exists') window.setTimeout(function(){$("#main_modal").modal('toggle');},300); }); //the add user event. socket.on("add_user",data=>{ //if data['error'] is anything but empty string then it's an error. if (data['error'] !== '') { $('#input_row').html(`<div class="col"><label for="modal_input" id="modal_label">Username</label> <input id="modal_input" class="form-control w-50" type="text" data-type="username" onkeypress="modal_update(event)"></div>`); $('#main_modal_title').text(data['error']); console.log('cannot add user') window.setTimeout(function(){$("#main_modal").modal('toggle');},300); } else { //otherwise we add the user to the list/set if it's no the same as our own. console.log(g_username); console.log(data['username']); if(data['username'] != g_username){ add_user(data['username']); } else{ //add_user(data['username']); $('#current_username').text(g_username); //set the property as their username. localStorage.setItem('username',data['username']); //rejoin event is fired to rejoin all channels. socket.emit("rejoin",{"username":g_username}); } } }); //a channel was added. socket.on('add_channel',data=>{ //error means they did something wrong/something went wrong. if(data['error'] != ''){ $('#main_modal_title').text(data['error']); console.log('cannot add channel') window.setTimeout(function(){$("#main_modal").modal('show');},300); } else{ //add teh channel to the list. console.log('added channel'); g_channels.push(data['channel']); add_channel(data['channel']); } }); //the private channel socket event for when they create a private channel. socket.on('private_channel',data=>{ //error means something was broke. if(data['error']!=''){ $('#main_modal_title').text(data['error']); console.log('cannot create private channel'); window.setTimeout(function(){$("#main_modal").modal('show');},300); } else{ //add the private information to the global object. console.log("added private"); g_privates['full_name'].push(data['full_name']); g_privates['names'].push(data['channel']); g_privates['passwords'].push(data['password']); add_private_channel(data['channel'],data['full_name']) //add_channel(data['channel'],true); } }); //a user has left. For some reason this doesn't always get sent by the server. socket.on('user_left',data=>{ console.log("user left"); g_users.removeItem(data['username']) let username=data['username'] $('#'+username).remove() }); //they joined a channel event. socket.on('joined',data=>{ //it worked. I should make them all have a success property but I didn't in time. Maybe for 1.1 version. if(data['success']){ console.log('joined'); //if the current channel isn't already set. if(!g_current_channel){ //set it as the first channel in the list. g_current_channel=g_channels[0]; } //add all of the messages from the channel. add_messages(data['channel_msgs']); } else{ //otherwise we have to setup the error modal. let channel=data['channel']; let password=data['password']; $('#main_modal_title').text(data['error']); $('#modal_label').text('Channel Name:'); $('#modal_input').val(channel); $('.row2').remove(); //password is not empty means it's a private room. if(password !== ''){ $('#input_row').after(`<div class="row row2" id="password_row"><div class="col"><label for="channel_password"> Channel Password</label><input id="channel_password" type="text"></div></div>`); $('#modal_input').data('type','join_private'); } else{ $('#modal_input').data('type','join_channel'); } //we have to delay it by some amount of time to get it to reopen properly. window.setTimeout(function(){$("#main_modal").modal('show');},300); } }); //someone pmed someone. socket.on("add_pm",data=>{ //error means it didn't work. if(data['error']!=''){ console.log('cannot pm'); $('#input_row').html(`<div class="col" id="pm_row"><label for="modal_input" id="modal_label">Username</label> <input id="modal_input" class="form-control w-50" type="text" data-type="create_pm" onkeypress="modal_update(event)"></div>`) $('#main_modal_title').text(data['error']); window.setTimeout(function(){$("#main_modal").modal('show');},300); } else{ //otherwise we have to add the first PM. let shown_user=data['to']; //set msg count to 1. let msgs=1; //see if the event was sent back to the sender or other person. if(shown_user === g_username){ //if it is then we set the msg count to zero since they would've already seen it. shown_user=data['from']; msgs=0; } //the channel_id is the full name of their room during PMing. let channel_id=data['room_name']; g_pms[channel_id]={'to':shown_user,'msgs':1} //a template string that has the channel id(which is used to get the PMs), and also the counter. let html=`<li id="${channel_id}" class="list-group-item list-group-item-dark d-flex justify-content-between align-items-center" onclick="get_pms(this.id)">${shown_user}<span class="badge badge-secondary badge-pill">${msgs} </span></li>` //append the new PM room to the list of them. $('#private_messages').append(html); g_pm_msgs[channel_id]=[data['msg']]; } }); //a new PM is sent. socket.on("pm",data=>{ //error was occured. if(data['error']!=''){ //couldn't send the PM. console.log('cannot pm') $('#input_row').html(`<div class="col" id="pm_row"><label for="modal_input" id="modal_label">Username</label> <input id="modal_input" class="form-control w-50" type="text" data-type="pm" onkeypress="modal_update(event)"></div>`) $('#main_modal_title').text(data['error']); window.setTimeout(function(){$("#main_modal").modal('show');},300); } else{ //otherwise again figure out who this was to/form. let shown_user=data['to']; //it was to them so we set the displayed user as the person who sent it. if(shown_user === g_username){ shown_user=data['from']; } //get the channel id. let channel_id=data['room_name']; //see if the current channel is that channel if it is no reason to increment unread count. if(g_current_channel !== channel_id) { //increment unread count by 1. g_pms[channel_id]['msgs'] += 1 //set inner text to the current count of unread messages. $(`#${channel_id}`).find("span").text(g_pms[channel_id]['msgs']); } //make sure it scrolls to the top. document.getElementById('msg_block').scrollTop=100000000000; $('#channel_id').text(g_pms[shown_user]); g_pm_msgs[channel_id].push(data['msg']); //if they're in that channel add the message to their display. if(g_current_channel === channel_id){ add_message(data['msg']); } } }); //update the list of users. socket.on("update_users",data=>{ let users=data["users"]; g_users=g_users.concat(users); let total=users.length; let q='' let p='' let username='' //create teh list of users. for(let i=0;i<total;i++){ username=users[i]; p=`<p id=${username} onclick="message_user(this.id)">${username}</p>` q+=p } //append them to the list. $('#users_online').html(q) }); //same but for channels. socket.on("update_channels",data=>{ let channels=data['channels']; g_channels=channels; let max=channels.length; console.log("adding channels"); for(let i=0;i<max;i++){ add_channel(channels[i],false); } //makes the current channel as active. $(`#${g_current_channel}`).addClass('active'); channels=data['private_channels']; console.log(data); let full_names=data['private_channels']['full_names']; console.log(full_names) if(full_names == undefined){ return; } let channels_length=full_names.length; let full_name = '' //if there's more than 1 private channel then we need to add those too. if(channels_length >= 1) { for (let i=0;i<channels_length;i++) { full_name=full_names[i]; g_privates['full_name'].push(full_name); g_privates['names'].push(channels[full_name]['name']) g_privates['passwords'].push(channels[full_name]['password']); add_private_channel(channels[full_name]['name'],full_name, channels['password']); } } }); //add the message that someone sent to the current room. socket.on("announce_room",data=>{ add_message(data['msg']); }); }); function change_channel(channel){ let private=$(`#${channel}`).data('private'); let password=''; if(private){ let index=g_privates['names'].indexOf(channel); password=g_privates['passwords'][index]; } $(`#${g_current_channel}`).removeClass('active'); $(`#${channel}`).addClass('active'); g_private = false; g_current_channel = channel; localStorage.setItem("current_channel",g_current_channel); socket.emit('join',{'username':g_username,'channel':g_current_channel,'password':password}); } function add_message(message){ $('#msg_block').append(construct_message(message)); document.getElementById('msg_block').scrollTop=100000000000; } function add_messages(messages){ let total_messages=messages.length; let msgs='' for(let i=0;i<total_messages;i++){ msgs+=construct_message(messages[i]); } $('#msg_block').html(msgs); document.getElementById('msg_block').scrollTop=100000000000; } function construct_message(msg_obj) { let user_id=msg_obj['username']; let msg = `<div class="media d-flex"><div> <span><a id="${user_id}" href="#" onclick="message_user(this.id)">${msg_obj['username']}</a></span><span class="pl-2"> @ ${new Date(parseInt(msg_obj['time'])).toLocalTime()}</span><p>${msg_obj['text']}</p></div></div>`; return msg; } function get_msgs(route, type, data) { const req = new XMLHttpRequest(); req.open(type, route); req.send(data) req.onload = () => { let msgs = ''; const json_data = JSON.parse(req.responseText) if (json_data.success) { let total_msgs = json_data.length; for (let i = 0;i<total_msgs; i++) { msgs += construct_message(msg_obj[i]); } document.getElementById('messages').innerHTML = msgs; } } } function unbold_channel() { document.getElementById(g_current_channel).style.fontWeight = "normal"; } function bold_channel(){ document.getElementById(g_current_channel).style.fontWeight = "bold"; } function add_channel(channel_name,private=false){ const li=document.createElement('li'); li.innerText = '#'+channel_name; li.setAttribute('id',channel_name); li.setAttribute('class','list-group-item list-group-item-dark'); li.setAttribute('onclick','change_channel(this.id)'); li.setAttribute('data-private',`${private}`); $('#channels').append(li); } function add_private_channel(short_name,full_name){ const li=document.createElement('li'); li.innerText = '#'+short_name; li.setAttribute('id',full_name); li.setAttribute('class','list-group-item list-group-item-dark'); li.setAttribute('onclick','change_channel(this.id)'); li.setAttribute('data-private',true); $('#channels').append(li); } function add_user(username){ const p=document.createElement('p'); p.innerText=username; p.setAttribute('id',username) p.setAttribute('onclick','message_user(this.id)'); $('#users_online').append(p); } function join_channel(channel_name,password=''){ $(`#${g_current_channel}`).removeClass('active'); $(`#${channel_name}`).addClass('active'); g_current_channel=channel_name localStorage.setItem("current_channel",g_current_channel); if(password !== ''){ socket.emit('join',{'channel':channel_name,'username':g_username,'password':password}); } else{ socket.emit('join',{'channel':channel_name,'username':g_username}); } } function msg_join_channel(msg){ const regex = RegExp('\!join\ #([A-Za-z0-9\-\_][^ ]+)','g'); let matches=[]; let replace_str=''; let index=0; let full_name=''; let password=''; while((matches = regex.exec(msg))!== null){ console.log(matches.join(',')); if(g_channels.indexOf(matches[1]) !== -1){ index=g_channels.indexOf(matches[1]); replace_str=`join <a href="#" title="Join ${g_channels[index]}" onclick="join_channel('${g_channels[index]}'); return false">#${g_channels[index]}</a>` console.log(replace_str); console.log(msg.replace(matches[0],replace_str)); msg=msg.replace(matches[0],replace_str); } else if(g_privates['names'].indexOf(matches[1]) !== -1){ index=g_privates['names'].indexOf(matches[1]); full_name=g_privates['full_name'][index]; password=g_privates['passwords'][index]; replace_str=`join <a href="#" title="Join ${full_name}" onclick="join_channel('${full_name}','${password}'); return false"> #${matches[1]}</a>` console.log(replace_str); msg=msg.replace(matches[0],replace_str); } } return msg; } function send_msg(){ let msg = $('#input_box').val(); $('#input_box').val(''); console.log(msg); msg=msg_join_channel(msg); if(g_private){ let to_user=g_pms[g_current_channel]['to'] socket.emit("send_pm",{'room':g_current_channel,'username':g_username,'to_user':to_user,'msg':msg}); } else{ socket.emit("submit_to_room",{'channel':g_current_channel,'username':g_username,'msg':msg}); } } function update_msg(event){ let key=event.key; //console.log(key); if (document.getElementById('input_box').value.length > 0) { $("#input_button").attr('disabled', false); if (key == "Enter") { send_msg(); } } else { $("#input_button").attr('disabled', true); } } function message_user(username){ if(username !== g_username){ $('#input_row').html(`<div class="col"><label for="modal_input" id="modal_label">Username</label> <input id="modal_input" class="form-control w-50" type="text" data-type="create_pm" value="${username}" onkeypress="modal_update(key)"></div>`); $('.row2').remove() $('#input_row').after(`<div class="row row2" id="message_row"><div class="col"><label for="user_message">Your Message </label><input id="user_message" type="text"></div></div>`); $('#main_modal_title').text(`Sending message to ${username}`); $("#user_message").on('keyup', function (event){ console.log(event.key); if (document.getElementById('user_message').value.length > 0) { $("#modal_button").attr('disabled', false); if (event.key === 'Enter') { $('#modal_button').click(); } } else { $("#modal_button").attr('disabled', true); } }); $("#main_modal").modal('toggle'); } } function get_pms(room_id){ g_private = true; let msgs=g_pm_msgs[room_id]; $('#msg_block').html('') $(`#${g_current_channel}`).removeClass('active'); g_current_channel=room_id; g_pms[g_current_channel]['msgs']=0; $(`#${g_current_channel}`).find("span").text(0); $(`#${room_id}`).addClass('active'); add_messages(msgs); } function modal_update(key){ if (document.getElementById('modal_input').value.length > 0) { $("#modal_button").attr('disabled', false); if (key.keyCode === 13) { $('#modal_button').click(); } } else { $("#modal_button").attr('disabled', true); } }
34.248915
187
0.664117
672ae8a68f810396870c5a90b1243a1d1dffe1a0
2,575
js
JavaScript
Button.js
HighDivineFox/Fireworks-Show
7d341d6d88a6117f0b50b276c23bc728b60714bb
[ "MIT" ]
null
null
null
Button.js
HighDivineFox/Fireworks-Show
7d341d6d88a6117f0b50b276c23bc728b60714bb
[ "MIT" ]
null
null
null
Button.js
HighDivineFox/Fireworks-Show
7d341d6d88a6117f0b50b276c23bc728b60714bb
[ "MIT" ]
null
null
null
import { FireworkSettings } from "./FireworkSettings.js"; import { UpgradesManager } from "./Managers/UpgradesManager.js"; import { GlobalSettings } from "./GlobalSettings.js"; export default class Button{ constructor(x, y, width, height, titleText, onClickEvent, textAlign){ this.x = x; this.y = y; this.width = width; this.height = height; this.titleText = titleText; this.costText = ""; this.onClickEvent = onClickEvent; this.textAlign = textAlign || "left"; this.getCostText(); } onClick(){ this.onClickEvent(); this.getCostText(); GlobalSettings.requestBGRedraw = true; } draw(context){ let textXPos = this.textAlign == "left" ? this.x + 5 : this.x + this.width/2; let textYPos = this.textAlign == "left" ? this.y + 18 : this.y + this.height/1.5; let gradient = context.createLinearGradient(this.x + this.width/2, this.y, this.x + this.width/2, this.y + this.height); gradient.addColorStop(0, "rgb(220, 220, 180)"); gradient.addColorStop(1, "rgb(160, 160, 120)"); context.beginPath(); context.textAlign = this.textAlign; context.fillStyle = gradient; context.rect(this.x, this.y, this.width, this.height); context.fill(); context.stroke(); context.fillStyle = "black"; context.font = "18px Arial"; context.font = this.textAlign == "left" ? "18px Arial" : "28px Arial"; context.fillText(this.titleText, textXPos, textYPos); context.fillText(this.costText, textXPos, textYPos + 27); } getCostText(){ switch (this.titleText) { case "Maximum Fireworks": this.costText = "$" + UpgradesManager.MaxFireworksCost.value; break; case "Firework speed": this.costText = "Increase Fireworks base speed"; break; case "Firework Colour": if(FireworkSettings.maxColourIndex >= 5){ this.costText = "Sold out!"; }else{ this.costText = "More Colourful shows"; } break; case "Explosion Radius": if(FireworkSettings.maxRadius >= 200){ this.costText = "Sold out!"; }else{ this.costText = "Increase Fireworks explosion radius"; } break; default: break; } } }
35.273973
128
0.546796
672c389644a2449e40e0f79dd1717c299080885c
2,235
js
JavaScript
user/themes/holly-chris-wedding/js/script.js
tomealter/holly-chris-wedding
329f99a32de78437feae87f8ec5a6f5dd20a3fb5
[ "MIT" ]
null
null
null
user/themes/holly-chris-wedding/js/script.js
tomealter/holly-chris-wedding
329f99a32de78437feae87f8ec5a6f5dd20a3fb5
[ "MIT" ]
null
null
null
user/themes/holly-chris-wedding/js/script.js
tomealter/holly-chris-wedding
329f99a32de78437feae87f8ec5a6f5dd20a3fb5
[ "MIT" ]
null
null
null
// Custom scripts file jQuery(document).ready(function ($) { 'use strict'; // Generic function that runs on window resize. function resizeStuff() { } // Runs function once on window resize. var TO = false; $(window).resize(function () { if (TO !== false) { clearTimeout(TO); } // 200 is time in miliseconds. TO = setTimeout(resizeStuff, 200); }).resize(); // Scroll Magic var controller = new ScrollMagic.Controller(); setTimeout( function() { new ScrollMagic.Scene({ offset: -10, triggerElement: '.about', triggerHook: .5, reverse: false }) .setClassToggle('.about', 'animation-active') // .addIndicators() .addTo(controller); }, 300); var mobileMenuButton = $('.mobile-menu-button'); var mobileMenu = $('.mobile-menu'); var mobileMenuLink = $('.mobile-menu .menu__link'); if (mobileMenuButton.length) { console.log('the button exists'); } console.log('is this thing on?'); mobileMenuButton.on('click', function (e) { e.preventDefault(); console.log('you clicked it'); if ($(this).hasClass('is-active')) { $(this).removeClass('is-active'); mobileMenu.removeClass('is-active'); } else { $(this).addClass('is-active'); mobileMenu.addClass('is-active'); } }); mobileMenuLink.on('click', function(e) { e.preventDefault(); mobileMenuButton.removeClass('is-active'); mobileMenu.removeClass('is-active'); }); // Smooth Scroll to Anchors $("a").on('click', function (event) { // Make sure this.hash has a value before overriding default behavior if (this.hash !== "") { // Prevent default anchor click behavior event.preventDefault(); // Store hash var hash = this.hash; // Using jQuery's animate() method to add smooth page scroll // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area $('html, body').animate({ scrollTop: $(hash).offset().top }, 800, function () { // Add hash (#) to URL when done scrolling (default click behavior) window.location.hash = hash; }); } // End if }); });
23.776596
112
0.606264
672c83295c0539853ffe9bd466862e773118e445
1,935
js
JavaScript
src/render-html/messageAsHtml.js
ajayns/zulip-mobile
83e0a437345a51ef5af1dc200d07fb267383f1c3
[ "Apache-2.0" ]
null
null
null
src/render-html/messageAsHtml.js
ajayns/zulip-mobile
83e0a437345a51ef5af1dc200d07fb267383f1c3
[ "Apache-2.0" ]
null
null
null
src/render-html/messageAsHtml.js
ajayns/zulip-mobile
83e0a437345a51ef5af1dc200d07fb267383f1c3
[ "Apache-2.0" ]
1
2019-10-14T23:34:46.000Z
2019-10-14T23:34:46.000Z
import { shortTime } from '../utils/date'; import messageTagsAsHtml from './messageTagsAsHtml'; import messageReactionListAsHtml from './messageReactionListAsHtml'; const messageDiv = (id, msgClass, flags) => `<div class="message ${msgClass}" id="msg-${id}" data-msg-id="${id}" ${flags.map(flag => `data-${flag}="true" `).join('')} >`; const messageSubheader = ({ fromName, timestamp, twentyFourHourTime }) => ` <div class="subheader"> <div class="username"> ${fromName} </div> <div class="timestamp"> ${shortTime(timestamp * 1000, twentyFourHourTime)} </div> </div> `; const messageBody = ({ content, flags, id, isOutbox, ownEmail, reactions, realmEmoji, timeEdited, }) => ` ${content} ${isOutbox ? '<div class="loading-spinner outbox-spinner"></div>' : ''} ${messageTagsAsHtml(flags, timeEdited)} ${messageReactionListAsHtml(reactions, id, ownEmail, realmEmoji)} `; const briefMessageAsHtml = ({ content, flags, id, isOutbox, ownEmail, reactions, realmEmoji, timeEdited, }) => ` ${messageDiv(id, 'message-brief', flags)} <div class="content"> ${messageBody({ content, flags, id, isOutbox, ownEmail, reactions, realmEmoji, timeEdited })} </div> </div> `; const fullMessageAsHtml = ({ id, content, flags, fromName, fromEmail, timestamp, avatarUrl, twentyFourHourTime, timeEdited, isOutbox, isStarred, reactions, ownEmail, isMentioned, realmEmoji, }) => ` ${messageDiv(id, 'message-full', flags)} <div class="avatar"> <img src="${avatarUrl}" class="avatar-img" data-email="${fromEmail}"> </div> <div class="content"> ${messageSubheader({ fromName, timestamp, twentyFourHourTime })} ${messageBody({ content, flags, id, isOutbox, ownEmail, reactions, realmEmoji, timeEdited })} </div> </div> `; export default ({ isBrief, ...rest }) => isBrief ? briefMessageAsHtml(rest) : fullMessageAsHtml(rest);
22.241379
97
0.657364
672cf34eec6f335d1d81f8ca5bb5efdb59907bc3
15,820
js
JavaScript
src/TipProvider.js
noway/react-native-tip
3264f1fe41404fd19101cb79e78784ed1b695d14
[ "MIT" ]
34
2021-05-05T04:37:40.000Z
2022-03-22T04:16:54.000Z
src/TipProvider.js
noway/react-native-tip
3264f1fe41404fd19101cb79e78784ed1b695d14
[ "MIT" ]
5
2021-05-18T12:06:48.000Z
2022-03-17T02:10:03.000Z
src/TipProvider.js
noway/react-native-tip
3264f1fe41404fd19101cb79e78784ed1b695d14
[ "MIT" ]
8
2021-05-12T00:55:00.000Z
2022-03-23T14:09:55.000Z
import React, { Component } from 'react' import { Animated, StyleSheet, TouchableOpacity, TouchableWithoutFeedback, Text, Dimensions, View, ViewPropTypes, Easing, Modal } from 'react-native' import TipManager from './TipManager' import PropTypes from 'prop-types' import { getItemCoordinates, getTipPositionProps, ARROW_WIDTH, ARROW_HEIGHT, RENDER_BOUNDARY, clearItemStyles } from './utils' const { width: screenWidth } = Dimensions.get('window') export default class TipProvider extends Component { constructor(props) { super(props) this.state = {} this.animation = new Animated.Value(0) this.overlayAnimation = new Animated.Value(0) this.pulseAnim = new Animated.Value(0) } componentDidMount() { TipManager.register(this) } componentDidUpdate(prevProps, prevState) { if (prevState.itemCoordinates !== this.state.itemCoordinates) { if (this.state.itemCoordinates) { this.animation.setValue(0) this.animateIn() } } } showTip = async (tip) => { if (this.state.itemCoordinates) { this.pulseAnim.setValue(0) this.animation.setValue(0) this.overlayAnimation.setValue(1) this.setState({ tipHasProps: false }) } const itemCoordinates = await getItemCoordinates(tip.target) this.setState({ ...tip, itemCoordinates, destroyItemImediatelly: null }) } closeTip = () => { this.animateOut() } hideCurrentTip = () => { this.setState({ destroyItemImediatelly: true }) Animated.parallel([ Animated.timing(this.animation, { toValue: 0, duration: 250, easing: Easing.out(Easing.ease), useNativeDriver: true }) ]).start() } componentWillUnmount() { TipManager.unregister(this) } animatePulse = () => { const { showItemPulseAnimation = this.props.showItemPulseAnimation } = this.state if (!showItemPulseAnimation) return return Animated.loop( Animated.timing(this.pulseAnim, { toValue: 1, duration: 1500, easing: Easing.inOut(Easing.ease), useNativeDriver: true }) ).start() } animateIn = () => { Animated.parallel([ Animated.timing(this.animation, { toValue: 1, duration: 250, easing: Easing.inOut(Easing.ease), useNativeDriver: true }), Animated.timing(this.overlayAnimation, { toValue: 1, duration: 250, easing: Easing.inOut(Easing.ease), useNativeDriver: true }) ]).start(() => this.animatePulse()) } animateOut = () => { this.setState({ destroyItemImediatelly: true }) Animated.parallel([ Animated.timing(this.animation, { toValue: 0, duration: 250, easing: Easing.out(Easing.ease), useNativeDriver: true }), Animated.timing(this.overlayAnimation, { toValue: 0, duration: 250, easing: Easing.out(Easing.ease), useNativeDriver: true }) ]).start(() => { this.pulseAnim.setValue(0) this.animation.setValue(0) this.overlayAnimation.setValue(0) this.setState({ itemCoordinates: null, tipHasProps: false }) }) } onTipLayout = (e) => { if (this.state.tipHasProps) return const { height, width } = e.nativeEvent.layout const tipProps = getTipPositionProps(this.state.itemCoordinates, height, width) this.setState({ ...tipProps }) } renderOverlay() { const { dismissable = true, onDismiss, overlayOpacity = this.props.overlayOpacity } = this.state return ( <TouchableWithoutFeedback onPress={() => { if (onDismiss) { onDismiss() } else { dismissable && this.closeTip() } }} > <Animated.View style={{ ...StyleSheet.absoluteFill, opacity: this.overlayAnimation.interpolate({ inputRange: [0, 1], outputRange: [0, 1] }), backgroundColor: `rgba(0,0,0,${overlayOpacity || 0.6})` }} /> </TouchableWithoutFeedback> ) } getTipAnimation() { const { pivotPoint = { x: 0, y: 0 } } = this.state return { opacity: this.animation.interpolate({ inputRange: [0, 0.5, 1], outputRange: [0, 0, 1] }), transform: [ { translateX: -1 * pivotPoint.x }, { translateY: -1 * pivotPoint.y }, { scale: this.animation.interpolate({ inputRange: [0, 1], outputRange: [0, 1] }) }, { translateX: pivotPoint.x }, { translateY: pivotPoint.y } ] } } renderItemPulseAnimation = (coordinates) => { const { children, showItemPulseAnimation = this.props.showItemPulseAnimation, pulseColor, layout, pulseStyle = {} } = this.state if (!showItemPulseAnimation) return null return ( <Animated.View style={{ position: 'absolute', // ...coordinates, ...pulseStyle, backgroundColor: pulseColor, transform: [ // ...(coordinates?.transform || []), { scaleX: this.pulseAnim.interpolate({ inputRange: [0, 1], outputRange: [1, 1.5] }) }, { scaleY: this.pulseAnim.interpolate({ inputRange: [0, 1], outputRange: [1, 1.5] }) } ], opacity: this.pulseAnim.interpolate({ inputRange: [0, 0.2, 1], outputRange: [0, 0.6, 0] }) }} /> ) } renderTip() { const { title, body, titleStyle = {}, bodyStyle = {}, tipContainerStyle = {}, renderTip, onTipPress, tipPosition, arrowPosition, tourProps } = this.state const { darkMode: isDarkMode, prevNextTextStyle, prevNextButtonStyle, prevButtonLabel = 'Prev', nextButtonLabel = 'Next', closeButtonLabel = 'Close' } = this.props const tipStyle = { backgroundColor: isDarkMode ? '#303030' : 'white', ...this.props.tipContainerStyle, ...tipContainerStyle } const _titleStyle = { color: isDarkMode ? '#fff' : 'rgba(0, 0, 0, 0.87)', ...this.props.titleStyle, ...titleStyle } const _bodyStyle = { color: isDarkMode ? 'rgba(255, 255, 255, 0.7)' : 'rgba(0, 0, 0, 0.54)', ...this.props.bodyStyle, ...bodyStyle } const _tipStyle = { ...styles.tip, ...tipStyle } const _prevNextButtonStyle = { ...styles.actionBtn, ...prevNextButtonStyle } const _prevNextTextStyle = { ...styles.actionBtnLabel, ...prevNextTextStyle } return ( <Animated.View onLayout={this.onTipLayout} style={{ ..._tipStyle, ...tipPosition, ...this.getTipAnimation() }} > {/* Tip leg */} <View style={{ ...styles.arrow, ...arrowPosition, borderBottomColor: tipStyle.backgroundColor, borderTopColor: tipStyle.backgroundColor }} /> <TouchableOpacity activeOpacity={0.8} disabled={!onTipPress} onPress={onTipPress} > { renderTip ? renderTip({ titleStyle: _titleStyle, bodyStyle: _bodyStyle }) : <> {title && <Text style={_titleStyle}> {title} </Text> } {body && <Text style={_bodyStyle}> {body} </Text> } </> } {tourProps && <View style={styles.actions}> { !!tourProps.prevId && <TouchableOpacity activeOpacity={0.5} onPress={() => TipManager.changeTipTour(tourProps, 'prev') } style={_prevNextButtonStyle} > <Text style={_prevNextTextStyle}> {prevButtonLabel} </Text> </TouchableOpacity> } { !!tourProps.nextId && <TouchableOpacity activeOpacity={0.5} onPress={() => TipManager.changeTipTour(tourProps, 'next') } style={_prevNextButtonStyle} > <Text style={_prevNextTextStyle}> {nextButtonLabel} </Text> </TouchableOpacity> } { !!tourProps.prevId && !tourProps.nextId && <TouchableOpacity activeOpacity={0.5} onPress={this.closeTip} style={_prevNextButtonStyle} > <Text style={_prevNextTextStyle}> {closeButtonLabel} </Text> </TouchableOpacity> } </View> } </TouchableOpacity> </Animated.View> ) } renderItem() { const { itemCoordinates, children, onPressItem, destroyItemImediatelly, layout, activeItemStyle } = this.state if (destroyItemImediatelly) return null const item = React.cloneElement(children, { ...children.props, // onPress: () => onPressItem && onPressItem(), onPressOut: () => onPressItem && onPressItem(), style: clearItemStyles(children.props?.style), }) const width = activeItemStyle?.width || layout.width const height = activeItemStyle?.height || layout.height const coordinates = { ...activeItemStyle, position: 'absolute', width, height, top: itemCoordinates.centerPoint.y, left: itemCoordinates.centerPoint.x, transform: [ { translateX: -width / 2 }, { translateY: -height / 2 } ], } return ( <View style={{ ...coordinates, justifyContent: 'center', alignItems: 'center', }}> {this.renderItemPulseAnimation()} <TouchableOpacity onPress={() => { if (onPressItem) onPressItem() else this.closeTip() }} > {item} </TouchableOpacity> </View> ) } render() { if (!this.state.itemCoordinates) return null return ( <Modal visible onRequestClose={this.closeTip} transparent hardwareAccelerated presentationStyle='overFullScreen' statusBarTranslucent > {this.renderOverlay()} {this.renderTip()} {this.renderItem()} </Modal> ) } } TipProvider.propTypes = { overlayOpacity: PropTypes.number, titleStyle: Text.propTypes.style, bodyStyle: Text.propTypes.style, tipContainerStyle: ViewPropTypes.style, showItemPulseAnimation: PropTypes.bool, darkMode: PropTypes.bool, prevButtonLabel: PropTypes.string, nextButtonLabel: PropTypes.string, closeButtonLabel: PropTypes.string, prevNextTextStyle: Text.propTypes.style, prevNextButtonStyle: ViewPropTypes.style } const styles = StyleSheet.create({ tip: { position: 'absolute', backgroundColor: 'white', borderRadius: 10, padding: 10, maxWidth: screenWidth - RENDER_BOUNDARY * 2, minHeight: 40, zIndex: 999, overflow: 'visible' }, arrow: { position: 'absolute', width: 0, height: 0, borderLeftWidth: ARROW_WIDTH / 2, borderRightWidth: ARROW_WIDTH / 2, borderBottomWidth: ARROW_HEIGHT, borderStyle: 'solid', backgroundColor: 'transparent', borderLeftColor: 'transparent', borderRightColor: 'transparent', borderBottomColor: 'white', borderTopColor: 'white' }, actions: { flexDirection: 'row', marginTop: 10, justifyContent: 'flex-end' }, actionBtn: { padding: 10, marginBottom: -10 }, actionBtnLabel: { fontSize: 16, fontWeight: 'bold' }, prev: { marginRight: 10 } })
30.958904
149
0.423072
672fcd0f991ebd5a37d6e1beb61ed1db28c15594
479
js
JavaScript
sources/connections/redis.js
andreibonnd/tt_auction
e7068d1493f990a8c8fa44cc1fa938fdf8710a14
[ "Apache-2.0" ]
null
null
null
sources/connections/redis.js
andreibonnd/tt_auction
e7068d1493f990a8c8fa44cc1fa938fdf8710a14
[ "Apache-2.0" ]
null
null
null
sources/connections/redis.js
andreibonnd/tt_auction
e7068d1493f990a8c8fa44cc1fa938fdf8710a14
[ "Apache-2.0" ]
null
null
null
import redis from 'redis'; import { promisify } from 'util'; import { environment } from './../configuration/index.js'; const connection = redis.createClient(environment.connections.redis); // @ts-ignore connection.on('error', (error) => console.error(`[redis]: ${error.message}`)); // @ts-ignore const setAsync = promisify(connection.set).bind(connection); // @ts-ignore const getAsync = promisify(connection.get).bind(connection); export { connection, setAsync, getAsync };
31.933333
78
0.726514
6730ad6c1b8ea45fe7ab63d7cd5002faa30cca64
34,593
js
JavaScript
epg-app/app/pages/epg/guide.js
midsnow/epg
c0441914fc6055c03490963ffea662ad4254777b
[ "MIT" ]
1
2019-05-15T07:53:11.000Z
2019-05-15T07:53:11.000Z
epg-app/app/pages/epg/guide.js
midsnow/epg
c0441914fc6055c03490963ffea662ad4254777b
[ "MIT" ]
null
null
null
epg-app/app/pages/epg/guide.js
midsnow/epg
c0441914fc6055c03490963ffea662ad4254777b
[ "MIT" ]
null
null
null
import React, { PureComponent } from "react"; import { unmountComponentAtNode } from 'react-dom'; import Debug from 'debug'; import Gab from '../../common/gab'; import FontIcon from 'material-ui/FontIcon'; import IconButton from 'material-ui/IconButton'; import Divider from 'material-ui/Divider'; import LinearProgress from 'material-ui/LinearProgress'; import MenuItem from 'material-ui/MenuItem'; import { Styles, ColorMe } from '../../common/styles'; import debounce from 'lodash/debounce'; import isObject from 'lodash/isObject'; import isFunction from 'lodash/isFunction'; import findIndex from 'lodash/findIndex'; import Find from 'lodash/find'; import sortBy from 'lodash/sortBy'; import Map from 'lodash/map'; import Filter from 'lodash/filter'; import moment from 'moment'; import AutoSizer from 'react-virtualized/dist/commonjs/AutoSizer'; import Collection from 'react-virtualized/dist/commonjs/Collection'; import Grid from 'react-virtualized/dist/commonjs/Grid'; import ScrollSync from 'react-virtualized/dist/commonjs/ScrollSync'; import scrollbarSize from "dom-helpers/util/scrollbarSize"; import cn from "classnames"; import Menu from '../../common/components/menu'; import natSort from 'javascript-natural-sort'; import RenderChannel from './components/channel'; //import Clock from 'react-live-clock'; let LEFT_COLOR_FROM = hexToRgb("#471061"); let LEFT_COLOR_TO = hexToRgb("#1C1061"); let TOP_COLOR_FROM = hexToRgb("#471061"); let TOP_COLOR_TO = hexToRgb("#1C1061"); let LC = mixColors( LEFT_COLOR_FROM, LEFT_COLOR_TO, 0 ); let TC = mixColors( TOP_COLOR_FROM, TOP_COLOR_TO, 0 ); let MC = mixColors( LC, TC, 0.5 ); MC = LC; let debug = Debug('epg:app:pages:epg:home'); export default class EPGHome extends PureComponent { constructor( props, context ) { super( props, context ) if ( props.initialData ) { debug('got props initialData'); //shows = props.initialData.shows.tvshows || []; this._skipMount = true; } this.displayName = 'EPG'; let _this = this; this.state = { numberOfGuideDays: 1, guidePreHours: 12, minutesPerColumn: 30, columnCount: ( ( ( props.numberOfGuideDays * 24 ) + props.guidePreHours ) * 60 ) / 30, columnWidth: 120, height: 400, overscanColumnCount: 40, overscanRowCount: 40, rowHeight: 90, rowHeaderHeight: 40, rowCount: 300, entries: [], channelList: [], useGenreColors: true, scrollToCell: undefined, group: props.params.group ? props.params.group.trim() : 'All Channels', sortGuideBy: props.query.sortGuideBy ? props.query.sortGuideBy.trim() : 'channel', guideLoaded: false, channelsLoaded: props.channels.length > 0 ? true : false, groupsLoaded: Object.keys(props.groups).length > 0 ? true : false, seriesLoaded: props.series.length > 0 ? true : false, timersLoaded: props.timers.length > 0 ? true : false, recordingsLoaded: props.recordings.length > 0 ? true : false, open: false, get pixelsPerMinute ( ) { return _this.state.columnWidth / _this.state.minutesPerColumn; }, get pixelsPerSecond ( ) { return _this.state.columnWidth / _this.state.minutesPerColumn / 60; } }; this.guideData = []; this.dayOfWeek = moment().format("dddd"); this.scrollTop = 0; let startTime = moment().startOf('hour').subtract(30, 'm').unix() - moment().startOf('hour').subtract(this.props.guidePreHours, 'h').unix() ; this.scrollLeft = startTime * this.state.pixelsPerSecond; this._cachedKeyPress = ''; this.getGuideData = this.getGuideData.bind(this); this._channelList = this._channelList.bind(this); this._cellSizeAndPositionGetter = this._cellSizeAndPositionGetter.bind(this); this._renderBodyCell = this._renderBodyCell.bind(this); this._renderHeaderTimeCell = this._renderHeaderTimeCell.bind(this); this._renderCurrentTimeCell = this._renderCurrentTimeCell.bind(this); this._renderChannelCell = this._renderChannelCell.bind(this); this.handleLeftNav = this.handleLeftNav.bind(this); this.leftNavClose = this.leftNavClose.bind(this); this.toggleDrawer = this.toggleDrawer.bind(this); this.menu = this.menu.bind(this); this._onScroll = this._onScroll.bind(this); this.useGenreColors = this.useGenreColors.bind(this); this.setTimer = this.setTimer.bind(this); this.deleteTimer = this.deleteTimer.bind(this); this.handleKeyPressDebouncing = this.handleKeyPressDebouncing.bind(this); this._mounted = []; this._update = true; } componentDidMount() { debug('######### componentDidMount ## EPG HOME', this.props, this.state); // grab the channels so they load while we wait on guide data this._channelList( { ...this.props, ...this.state } , ( err, ret ) => { this.setState( { channelList: ret, height: document.documentElement.clientHeight - 40 } ) }); if ( !this.props.episode ) { document.removeEventListener( "keypress", this.handleKeyPress, false ); document.addEventListener( "keypress", this.handleKeyPress, false ); document.removeEventListener( "keypress", this.handleKeyPressDebouncing, false ); document.addEventListener( "keypress", this.handleKeyPressDebouncing, false ); } else { document.removeEventListener( "keypress", this.handleKeyPress, false ); document.removeEventListener( "keypress", this.handleKeyPressDebouncing, false ); } // get the guide data const s = moment().startOf('hour').subtract(this.state.guidePreHours, 'h').unix(); const f = moment().add(this.state.numberOfGuideDays, 'days').unix(); this.getGuideData( false, s, f); } _clean() { if ( this._mounted.length > 0 ) { this._mounted.forEach( ref => { //unmountComponentAtNode(ref); }); this._mounted = []; return Promise.resolve(); } return Promise.resolve(); } componentWillUnmount ( ) { document.removeEventListener( "keypress", this.handleKeyPress, false ); document.removeEventListener( "keypress", this.handleKeyPressDebouncing, false ); this._clean(); } componentDidUpdate (prevProps, prevState) { if ( prevState.group !== this.state.group || prevState.sortGuideBy !== this.state.sortGuideBy ) { if ( this.grid2 ) this.grid2.forceUpdate(); if ( this.grid1 ) this.grid1.forceUpdate(); if ( this.collection ) this.collection.forceUpdate() } } componentWillReceiveProps ( props ) { debug('## componentWillReceiveProps ## EPG got props', this.state, props ); return; let state = { group: props.params.group ? props.params.group : this.state.group, sortGuideBy: props.query.sortGuideBy ? props.query.sortGuideBy : this.state.sortGuideBy, numberOfGuideDays: props.numberOfGuideDays, }; state.group = state.group.trim(); state.sortGuideBy = state.sortGuideBy.trim(); if ( props.routes[2].path === 'guide' && props.routes[2].path !== this.state.route ) { debug( 'get guideData' ); this.setState( { entries: [], guideLoaded: false, route: props.routes[2].path }, () => { const s = moment().startOf('hour').subtract(this.state.guidePreHours, 'h').unix(); const f = moment().add(this.state.numberOfGuideDays, 'days').unix(); this.getGuideData( false, s, f); }); } } shouldComponentUpdate ( ) { if(this._update) { this._update = false; return true; } return true; } getGuideData ( id, start, end ) { this.props.Request({ action: 'getGuideData', id, start, end, skipMetadata: true }) .then(data => { debug('### getGuideData ###', data); this._update = true; this.setState({ entries: data.entries.groups, channelList: [], }, () => { debug('start CHANNEL LIST'); this._channelList({ ...this.props, ...this.state }, ( err, ret ) => { debug('goit CHANNEL LIST', ret); this._update = true; this.setState( { channelList: ret, guideLoaded: true, } ) }); }); return {} }) .catch(error => { debug('ERROR from getGuideData', error) }); } handleKeyPress = ( event ) => { this._cachedKeyPress = this._cachedKeyPress + event.key; this.forceUpdate(); // debug( 'handleKeyPress', event.key, event.keyCode, this._cachedKeyPress ); } _bounced = ( ) => { //debug( '_bounced', this._cachedKeyPress ); let found = findIndex(this.state.channelList, ( channel ) => { //debug( channel.channel.substr( 0, this._cachedKeyPress.length), this._cachedKeyPress ) if( channel.channel.substr( 0, this._cachedKeyPress.length) == this._cachedKeyPress ) { //debug( 'Found', channel.channel ); return true; } return false; }) if ( found < 0 ) { found = findIndex(this.state.channelList, ( channel ) => { //debug( channel.channel.substr( 0, this._cachedKeyPress.length), this._cachedKeyPress ) if ( channel.channelName.match(new RegExp(this._cachedKeyPress, "i")) ) { return true; } return false; }) } this._cachedKeyPress = ''; debug( 'GOTO', found ); if ( found >= 0 ) { this.scrollTop = found * this.state.rowHeight; } this.forceUpdate(); } handleKeyPressDebouncing = debounce(this._bounced, 750) useGenreColors () { this.setState( { useGenreColors: !this.state.useGenreColors }, () => { this.collection.forceUpdate(); this.leftNavClose(); }); } setTimer ( timer ) { Gab.emit('snackbar', { style: 'info', html: "Sending Timer Request", open: true, onRequestClose: () => {}, }); this.props.Request({ action: 'setTimer', timer }) .then(data => { if(data.success) { Gab.emit('snackbar', { style: 'warning', html: data.message, open: true, onRequestClose: () => {}, }); //setTimeout( this.props.reload, 10000, ['getSeries', 'getTimers'] ); } else { Gab.emit('snackbar', { style: 'danger', html: data.error, open: true, onRequestClose: () => {} }); } }) .catch(e => { Gab.emit('snackbar', { style: 'danger', html: e.message, open: true, onRequestClose: () => {} }); }); } deleteTimer ( timer ) { Gab.emit('snackbar', { style: 'info', html: "Sending Timer Request", open: true, onRequestClose: () => {}, }); this.props.Request({ action: 'deleteTimer', timer }) .then(data => { if(data.success) { Gab.emit('snackbar', { style: 'success', html: data.message, open: true, onRequestClose: () => {}, }); //setTimeout( this.props.reload, 10000, ['getSeries', 'getTimers'] ); } else { Gab.emit('snackbar', { style: 'danger', html: 'Error deleting Timer', open: true, onRequestClose: () => {} }); } }) .catch(e => { Gab.emit('snackbar', { style: 'danger', html: e.message, open: true, onRequestClose: () => {} }); }); } deleteSeries ( timer ) { Gab.emit('snackbar', { style: 'info', html: "Sending Series Pass Request", open: true, onRequestClose: () => {}, }); this.props.Request({ action: 'deleteSeriesTimer', timer }) .then(data => { if(data.success) { Gab.emit('snackbar', { style: 'success', html: data.message, open: true, onRequestClose: () => {}, }); //setTimeout( this.props.reload, 10000, ['getSeries', 'getTimers'] ); } else { Gab.emit('snackbar', { style: 'danger', html: 'Error deleting Timer', open: true, onRequestClose: () => {} }); } }) .catch(e => { Gab.emit('snackbar', { style: 'danger', html: e.message, open: true, onRequestClose: () => {} }); }); } /** ****************RENDER************************************* **/ render ( ) { LEFT_COLOR_FROM = hexToRgb(this.props.theme.baseTheme.palette.canvasColor); LEFT_COLOR_TO = hexToRgb(ColorMe(10, this.props.theme.baseTheme.palette.canvasColor).bgcolor); TOP_COLOR_FROM = hexToRgb(this.props.theme.baseTheme.palette.primary1Color); TOP_COLOR_TO = hexToRgb(ColorMe(10, this.props.theme.baseTheme.palette.primary1Color).bgcolor); debug(LEFT_COLOR_FROM, LEFT_COLOR_TO, TOP_COLOR_FROM, TOP_COLOR_TO); if ( this.state.channelList.length < 1 ) { return (<div style={{ padding: 50, color: this.props.theme.baseTheme.palette.accent1Color }}> Waiting for channel list to populate </div>); } else if ( this.props.params.channel ) { return this.renderChannel(); } return this.renderGuide(); } /** *****************END RENDER******************************* **/ renderChannel ( ) { const channel= Find( this.state.channelList, item => item.channel == this.props.params.channel ); debug('renderChannel', this.props.params.channel, channel ); return (<RenderChannel ref={ ref => this._mounted.push(ref) } renderChannel={ channel } setTimer={ this.setTimer } deleteTimer={ this.deleteTimer } deleteSeries={ this.deleteSeries.bind(this) } bgcolor={ rgbToHex( { ...LC } ) } goBack={()=>(this.props.goTo({ path: '/tv/guide' }) )} { ...this.props } />); } renderGuide ( ) { debug('## render ## EPG Home Loaded', this.props, this.state, this.guideData.length); const { columnCount, rowHeaderHeight, columnWidth, height, overscanColumnCount, overscanRowCount, rowHeight, channelList } = this.state; const rowCount = channelList.length; const cellCount = this.guideData.length; const _height = height; let hamburger =(<IconButton title="Guide Menu" style={{ position: 'relative', textAlign: 'left', marginLeft: 0, padding: 0, width: 40, height: 40, }} onClick={this.handleLeftNav} ><FontIcon className="material-icons" hoverColor={Styles.Colors.limeA400} style={{fontSize:'20px'}} color={this.props.theme.appBar.textColor || 'initial'} >menu</FontIcon></IconButton>); let changeChannel = this._cachedKeyPress ? ( <div style={{ position: 'absolute', top: '15%', left: '15%', fontSize: 124, color: this.props.theme.baseTheme.palette.accent3Color, zIndex: 1600 }} children={this._cachedKeyPress} />) : ( <span /> ) return ( <div ref={ ref => this._mounted.push(ref) } style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', backgroundColor: `rgb(${TC.r},${TC.g},${TC.b})`, zIndex: 1000 }} > {changeChannel} <div style={{ position: 'fixed', top: 0, left: 0, paddingLeft: 5, zIndex: 1300 }} children={hamburger} /> {this.menu()} <ScrollSync> { ( { clientHeight, clientWidth, onScroll, scrollHeight, scrollLeft, scrollTop, scrollWidth } ) => { const x = scrollLeft / (scrollWidth - clientWidth); const y = scrollTop / (scrollHeight - clientHeight); const leftBackgroundColor = LC = mixColors( LEFT_COLOR_FROM, LEFT_COLOR_TO, y ); const leftColor = "#ffffff"; const topBackgroundColor = TC = mixColors( TOP_COLOR_FROM, TOP_COLOR_TO, x ); const topColor = "#ffffff"; const middleBackgroundColor = MC = LC; const middleColor = "#ffffff"; return ( <AutoSizer > {({ width, height }) => { return ( <div> <div className="GridRow"> <div className="LeftSideGridContainer" style={{ position: "absolute", left: 0, top: 0, color: 'chartreuse', backgroundColor: `rgb(${topBackgroundColor.r},${topBackgroundColor.g},${topBackgroundColor.b})` }} > <Grid cellRenderer={this._renderCurrentTimeCell} className="HeaderGrid" width={columnWidth} height={rowHeaderHeight} rowHeight={rowHeaderHeight} columnWidth={this._getColumnWidth2} rowCount={1} columnCount={2} ref={ ref => this.grid1 = ref } /> </div> <div className="LeftSideGridContainer" style={{ position: "absolute", left: 0, top: rowHeaderHeight, color: leftColor, backgroundColor: `rgb(${leftBackgroundColor.r},${leftBackgroundColor.g},${leftBackgroundColor.b})` }} > <Grid overscanColumnCount={overscanColumnCount} overscanRowCount={overscanRowCount} cellRenderer={this._renderChannelCell} columnWidth={this._getColumnWidth} columnCount={2} className="LeftSideGrid" height={height - scrollbarSize() - 40} rowHeight={rowHeight} rowCount={rowCount} scrollTop={this.scrollTop} width={columnWidth} ref={ ref => this.grid2 = ref } /> </div> <div className="GridColumn"> <div style={{ backgroundColor: `rgb(${topBackgroundColor.r},${topBackgroundColor.g},${topBackgroundColor.b})`, color: topColor, height: rowHeaderHeight, width: width - scrollbarSize() }} > <Grid className="HeaderGrid" columnWidth={columnWidth} columnCount={columnCount} height={rowHeaderHeight} overscanColumnCount={overscanColumnCount} cellRenderer={this._renderHeaderTimeCell} rowHeight={rowHeaderHeight} rowCount={1} scrollLeft={this.scrollLeft} width={width - scrollbarSize()} ref={ ref => this.grid3 = ref } /> </div> <div style={{ backgroundColor: `rgb(${middleBackgroundColor.r},${middleBackgroundColor.g},${middleBackgroundColor.b})`, color: middleColor, height: height - 40, width }} > <Collection className="BodyGrid" cellCount={cellCount} height={height - 40} onScroll={ ( { clientHeight, clientWidth, scrollHeight, scrollLeft, scrollTop, scrollWidth } ) => { this._onScroll.call( this, { clientHeight, clientWidth, scrollHeight, scrollLeft, scrollTop, scrollWidth } ); // run ScrollSync onScroll onScroll( { clientHeight, clientWidth, scrollHeight, scrollLeft, scrollTop, scrollWidth } ); }} scrollLeft={this.scrollLeft} scrollTop={this.scrollTop} horizontalOverscanSize={overscanColumnCount} verticalOverscanSize={overscanRowCount} cellRenderer={this._renderBodyCell} cellSizeAndPositionGetter={this._cellSizeAndPositionGetter} width={width} ref={ ref => this.collection = ref } /> </div> </div> </div> </div> ); //AutoSizer return } } </AutoSizer> ); //ScrollSync return }} </ScrollSync> </div> ); } _channelList ( props, callback ) { props = { ...props }; debug( 'Channel list getter', props.groups[props.group], props.groups, props.group); if ( !Array.isArray(this.guideData) ) this.guideData = []; if ( Object.keys(props.groups).length > 0 && ( props.group !== this.state.group || props.sortGuideBy !== this.state.sortGuideBy || this.state.channelList.length === 0 ) ) { let a = props.groups[props.group] .map( chan => chan[props.sortGuideBy] ) .sort(natSort) .map( channel2 => { let ret = { ...Find( props.groups[props.group], g => g[props.sortGuideBy] === channel2 ) }; let channel = ret.stationID; let data = this.state.entries[channel]; //ret.guide = data; //debug(data); if ( Array.isArray(data) ) { this.guideData = [ ...this.guideData, ...data.filter( c => ( c.startTime < moment().add( ( this.state.minutesPerColumn * ( this.state.columnCount + 1 ) ), 'm' ).unix() ) ) ]; } return ret; }); if ( isFunction( callback ) ) callback(null, a); return; } if ( isFunction( callback ) ) callback(null, []); return []; } _getColumnWidth({ index, time }) { switch (index) { case 0: return 60; case 1: return 60; case 2: return 480; default: return 60; } } _getColumnWidth2({ index }) { switch (index) { case 0: return 50; case 1: return 80; case 2: return 480; default: return 60; } } _onScroll ( { clientHeight, clientWidth, scrollHeight, scrollLeft, scrollTop, scrollWidth } ) { this.scrollLeft = scrollLeft; this.scrollTop = scrollTop; const now = moment().subtract(this.props.guidePreHours, 'h').unix(); // check for a date change // convert our scroll position to seconds and add on 1 columns for the channel number // add the scroll time to the grid start time and we have the current time of the grid const checkBy = ( this.scrollLeft / this.state.pixelsPerSecond ) + now - ( (this.state.minutesPerColumn * 1.2 )* 60 ); const time = moment.unix(checkBy).format("dddd"); if ( time !== this.dayOfWeek ) { this.dayOfWeek = time; if ( this.grid1 ) this.grid1.forceUpdate(); debug( 'Change dayOfWeek', this.dayOfWeek ); } } _cellSizeAndPositionGetter({ index }) { let data = this.guideData[index]; const { columnCount, pixelsPerSecond, rowHeight, channelList } = this.state; const channelIndex = findIndex( channelList, item => item.stationID == data.stationID ); let startTime = moment().startOf('hour').subtract(this.props.guidePreHours, 'h').unix(); if ( data.startTime == 0 ) { data.startTime = startTime; } //debug( '_cellSizeAndPositionGetter', data, channelIndex, now.unix(), pixelsPerSecond ); const end = moment().add( ( this.props.numberOfGuideDays ), 'd' ).unix(); const endsAfter = data.endTime > end; const height = rowHeight; const width = endsAfter ? (end - data.startTime) * pixelsPerSecond : (data.endTime - data.startTime) * pixelsPerSecond; const x = (data.startTime - startTime) * pixelsPerSecond; const y = channelIndex * rowHeight; //debug('_cellSizeAndPositionGetter', data, channelIndex, height, width, x, y); return { height, width, x, y }; } _renderBodyCell( { index, isScrolling, key, style } ) { const { rowHeight, columnWidth, channelList } = this.state; let data = this.guideData[index]; //debug('body cell', data) const channel = Find( channelList, item => item.stationID == data.stationID ); const channelIndex = findIndex( channelList, item => item.stationID == data.stationID ); const isNew = !data.repeat; const isTimer = isObject( Find( this.props.timers, ( v ) => ( v.programId == data.programId ) ) ); const isSeries = isObject( Find( this.props.series, ( v ) => ( v.show == data.title || v.programId == data.programId ) ) ); const isRecorded = isObject( Find( this.props.recordings, [ 'programId', data.programId] ) ); //debug('renderBodyCell', this.scrollLeft, style.left, this.scrollLeft - style.left); let timer = <span />; let series = <span />; let recordings = <span />; if ( isTimer ) { timer = ( <FontIcon className="material-icons" color={Styles.Colors.red800} style={{cursor:'pointer', fontSize: 15}} title="This episode will be recorded">radio_button_checked</FontIcon> ); } if ( isSeries ) { series = ( <FontIcon className="material-icons" color={Styles.Colors.blue500} style={{cursor:'pointer', fontSize: 15}} title="You have a Series Pass enabled for this program">fiber_dvr</FontIcon> ); } if ( isRecorded ) { recordings = ( <FontIcon className="material-icons" color={Styles.Colors.limeA400} style={{cursor:'pointer', fontSize: 15}} title="This program is recorded">play_circle_filled</FontIcon> ); } const bgColor = channelIndex % 2 == 0 ? 'none' : 'rgba(0, 0, 0, .1)'; const classNames = { height: '100%', display: 'flex', overflow: 'hidden', fontWeight: 700, flexDirection: 'column', justifyContent: 'center', alignItems: 'left', textAlign: ((style.left - this.scrollLeft) - columnWidth) < 0 ? 'right' : 'left', padding: '0 5', border: "4px solid " + ColorMe( -5, rgbToHex(LC) ).bgcolor, ...style, }; return ( <div style={{ ...classNames, //background: "url('" + data.iconPath + "') left top / 100% repeat-y fixed", //backgroundRepeat: 'repeat-y', //backgroundSize: 'cover', //backgroundPosition: 'left top / 100%', backgroundColor: this.state.useGenreColors ? "#" + decimalToHexString("" +data.genre) : bgColor, cursor: 'pointer', }} key={key} onClick={ ( ) => ( this.props.goTo({ path: '/tv/channel/' + channel.channel + '/' + data.id, page: 'Program Info' } ) )} > <div style={{ maxHeight: style.height / 2, width: style.width - 10, overflow: 'hidden', padding: '0 0', }} >{data.title} </div> <div style={{ maxHeight: style.height / 2, fontWeight: 400, width: '100%', overflow: 'hidden', padding: ' 0', }} >{data.episode || data.plotOutline} </div> <div style={{ position: 'absolute', top: 0, right: 18, width: 40, height: 15, textAlign: 'right'}}> {recordings} <span style={{ marginLeft: 3 }} /> {timer} </div> <div style={{ position: 'absolute', top: 0, right: 0, width: 15, height: 80, textAlign: 'center'}}> {series} { isNew ? <FontIcon className="material-icons" color={this.props.theme.baseTheme.palette.accent3Color} style={{ fontSize:'15px'}} >fiber_new</FontIcon> : <span /> } </div> </div> ) } _renderHeaderTimeCell({ columnIndex, key, rowIndex, style }) { return ( <div className="headerCell" key={key} style={{ ...style, border: "2px solid " + ColorMe( 2, rgbToHex(TC) ).bgcolor }}> {moment().startOf('hour').subtract(this.props.guidePreHours, 'h').add( ( columnIndex*this.state.minutesPerColumn), 'm').format(' h:mm a')} <div style={{ width: 1, height: '30%', left: '50%', top: '70%', position: 'absolute', borderLeft: "4px solid " + ColorMe( 2, rgbToHex(TC) ).bgcolor }} /> </div> ); } _renderCurrentTimeCell ({ columnIndex, key, rowIndex, style }) { if ( columnIndex === 0 ) return; return ( <div className="headerCell" key={key} style={{ backgroundColor: style.backgroundColor, color: 'chartreuse', paddingLeft: 21 }} children={this.dayOfWeek } //children={ <Clock format={'h:mm:ss a'} ticking={true} timezone={'US/Eastern'} /> } /> ); } _renderChannelCell ({ columnIndex, key, rowIndex, style }) { const { channelList, rowHeight } = this.state; const { channels } = this.props; const rowClass = rowIndex % 2 === 0 ? columnIndex % 2 === 0 ? {} : {backgroundColor: 'rgba(0, 0, 0, .1)'} : columnIndex % 2 !== 0 ? {} : {backgroundColor: 'rgba(0, 0, 0, .1)'}; const rowClass2 = rowIndex % 2 === 0 ? columnIndex % 2 !== 0 ? {} : {backgroundColor: 'rgba(0, 0, 0, .1)'} : columnIndex % 2 === 0 ? {} : {backgroundColor: 'rgba(0, 0, 0, .1)'}; const classNames = { ...rowClass, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', textAlign: 'center', padding: '0 .5em', fontSize: 18, ...style }; if ( columnIndex === 0 ) { const channel = Find( channels, c => c.channel == channelList[rowIndex].channel ); const className = { display: 'flex', justifyContent: 'center', alignItems: 'center', textAlign: 'center', //padding: '0 .5em', fontSize: 9, //background: 'url("' + + '") no-repeat center', overflow: 'hidden', cursor: 'pointer', ...style, ...rowClass2, }; return ( <div onClick={ (e) => ( this.props.goTo( { path: '/tv/channel/' + channel.channel, page: channel.channelName } ) ) } style={className} children={ channel.iconPath == '' ? channelList[rowIndex].name : <img title={channelList[rowIndex].name} alt={channelList[rowIndex].name} style={{ maxWidth: '100%', maxHeight: '100%' }} src={channel.iconPath} /> } /> ); } return ( <div style={classNames} key={key} > {channelList ? <div style={{overflow: 'hidden' }}>{channelList[rowIndex].channel}</div> : ''} </div> ); } menu() { let hamburger =(<IconButton title="Main Menu" style={{ zIndex: 10000, position: 'relative', textAlign: 'left' }} onClick={(e) => { this.leftNavClose(); this.props.handleLeftNav(e) }} ><FontIcon className="material-icons" hoverColor={Styles.Colors.limeA400} style={{fontSize:'20px'}} color={this.props.theme.appBar.textColor || 'initial'} >menu</FontIcon></IconButton>); return ( <Menu { ...this.state } { ...this.props } docked={false} drawer={true} secondary={false} goTo={this.props.goTo} handleLeftNav={this.leftNavClose} toggleDrawer={this.toggleDrawer} > <div className="menu" style={{ height: this.props.window.height, width: '100%', overflow: 'hidden', marginTop: 0, }} > <div style={{ backgroundColor: this.props.theme.baseTheme.palette.canvasColor, height: 50, width: '100%' }} > <div style={{float:'left',width:'25%', textAlign: 'center'}}> {hamburger} </div> <div style={{float:'left',width:'25%', textAlign: 'center'}}> <IconButton title="TV Channels" onClick={(e)=>{ e.preventDefault(); this.props.goTo({path: '/tv/channels', page: 'Live TV'}); }} > <FontIcon className="material-icons" hoverColor={Styles.Colors.limeA400} color={this.props.theme.appBar.buttonColor || 'initial'} > featured_videos </FontIcon> </IconButton> </div> <div style={{float:'left',width:'25%', textAlign: 'center'}}> <IconButton title="Recordings" onClick={(e)=>{ e.preventDefault(); this.props.goTo({path: '/tv/recordings', page: 'Recordings'}, this.leftNavClose); }} > <FontIcon className="material-icons" hoverColor={Styles.Colors.limeA400} color={this.props.theme.appBar.buttonColor || 'initial'} > play_circle_filled </FontIcon> </IconButton> </div> <div style={{float:'left',width:'25%', textAlign: 'center'}}> <IconButton title="Series Pass & Timers" onClick={(e)=>{ e.preventDefault(); this.props.goTo({path: '/tv/scheduled', page: 'Scheduled'}, this.leftNavClose); }} > <FontIcon className="material-icons" hoverColor={Styles.Colors.limeA400} color={this.props.theme.appBar.buttonColor || 'initial'} > fiber_dvr </FontIcon> </IconButton> </div> </div> { Object.keys( this.props.groups ).map( ( keyName, i ) => { return (<MenuItem key={keyName} primaryText={keyName} title={"sort by " + keyName} onClick={ ( ) => { this.props.goTo({ path: '/tv/guide/'+keyName, page: ' by ' + keyName}, this.leftNavClose) } } />) }) } <Divider inset={false} style={{ marginBottom: 15 }}/> <div style={{float:'left',width:'25%', textAlign: 'center'}}> <FontIcon className="material-icons" hoverColor={Styles.Colors.limeA400} color={this.state.sortGuideBy === 'name' ? Styles.Colors.limeA400 : 'white' } style={{cursor:'pointer'}} onClick={ () => { this.props.goTo({ path: '/tv/guide/' + this.state.group, query: {sortGuideBy: 'name'}, page: 'sort by name'}, this.leftNavClose) } } title="sort by channel name">sort_by_alpha</FontIcon> </div> <div style={{float:'left',width:'25%', textAlign: 'center'}}> <FontIcon className="material-icons" hoverColor={Styles.Colors.limeA400} color={this.state.sortGuideBy === 'channel' ? Styles.Colors.limeA400 : 'white' } style={{cursor:'pointer'}} onClick={ () => { this.props.goTo({ path: '/tv/guide/' + this.state.group, query: {sortGuideBy: 'channel'}, page: 'next to air'}, this.leftNavClose) } } title="sort by channel number">filter_8</FontIcon> </div> <div style={{float:'right',width:'25%', textAlign: 'center'}}> <FontIcon className="material-icons" hoverColor={Styles.Colors.limeA400} color={this.state.useGenreColors ? Styles.Colors.limeA400 : 'white' } style={{cursor:'pointer'}} onClick={ this.useGenreColors } title="add genre colors">{this.state.useGenreColors ? 'invert_colors' : 'invert_colors_off'}</FontIcon> </div> </div> </Menu> ); } handleLeftNav ( e , stated ) { if(e && typeof e.preventDefault === 'function') { e.preventDefault(); } debug('handleLeftNav', this.state); this.props.handleLeftNav ( e, false ); this.setState( { open: !this.state.open } ); } toggleDrawer ( open ) { debug('toggleDrawer', open); this.setState( { open } ); } leftNavClose ( ) { this.setState( { open: false }, this.forceUpdate ); } } EPGHome.getInitialData = function ( params ) { let ret = { shows: { action: 'epg' } } console.log( '### RUN getInitialData EPG ###', params ); return ret } function decimalToHexString(number) { if (number < 0) { number = 0xFFFFFFFF + number + 1; } return number.toString(16).toUpperCase(); } function rgbToHex({ r, g, b }) { return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1) } function hexToRgb(hex) { const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null; } /** * Ported from sass implementation in C * https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209 */ function mixColors(color1, color2, amount) { const weight1 = amount; const weight2 = 1 - amount; const r = Math.round(weight1 * color1.r + weight2 * color2.r); const g = Math.round(weight1 * color1.g + weight2 * color2.g); const b = Math.round(weight1 * color1.b + weight2 * color2.b); return { r, g, b }; }
32.29972
391
0.607146
6730d392aee2e5b336af78228ffa733b24d6ffd5
830
js
JavaScript
background.js
Arca-Digital/wwdc_subtitles
5a46d75699dba596a9f94db14ae1f919ee704002
[ "MIT" ]
null
null
null
background.js
Arca-Digital/wwdc_subtitles
5a46d75699dba596a9f94db14ae1f919ee704002
[ "MIT" ]
null
null
null
background.js
Arca-Digital/wwdc_subtitles
5a46d75699dba596a9f94db14ae1f919ee704002
[ "MIT" ]
null
null
null
/* Background action setup Author: Ricardo Sarmiento License: MIT */ function saveFile(contents, filename) { let blob = new Blob([contents], { type: "text/srt" }); let url = URL.createObjectURL(blob); chrome.downloads.download({ filename: filename, saveAs: true, url: url }) } /// Expect a message from the content script, with the subtitles text chrome.runtime.onMessage.addListener( function (request, sender, sendResponse) { if (request.subtitles !== undefined) { let filename = `${request.wwdc} ${request.topicNumber}.srt` saveFile(request.subtitles, filename) } } ) // Executes main.js on the active tab chrome.browserAction.onClicked.addListener(function (tab) { chrome.tabs.executeScript(null, { file: "main.js" }) })
30.740741
78
0.648193
6731785416f01ca062a5a4e29c7cda926c509d09
325
js
JavaScript
src/components/BlogReadmore/index.js
minhduc3701/tastech-ez
61dd8f44f05a909d4d53ad9759ef0052db4d5282
[ "MIT" ]
null
null
null
src/components/BlogReadmore/index.js
minhduc3701/tastech-ez
61dd8f44f05a909d4d53ad9759ef0052db4d5282
[ "MIT" ]
null
null
null
src/components/BlogReadmore/index.js
minhduc3701/tastech-ez
61dd8f44f05a909d4d53ad9759ef0052db4d5282
[ "MIT" ]
null
null
null
import React from "react" import { FormattedMessage } from 'react-intl' import { Wrapper, Button } from './style' const BlogReadmore = props => { return ( <Wrapper> <Button onClick={props.onClick}> <FormattedMessage id="blog.readMore" /> </Button> </Wrapper> ) } export default BlogReadmore
20.3125
47
0.649231
673196463ff4597c44ea75c7b8d29d10de998627
790
js
JavaScript
problems/003-ticket.js
yarman1/js-problems
54fd576ae8715d09ca2ba8dc4bc0a355fa8e9ed1
[ "MIT" ]
null
null
null
problems/003-ticket.js
yarman1/js-problems
54fd576ae8715d09ca2ba8dc4bc0a355fa8e9ed1
[ "MIT" ]
null
null
null
problems/003-ticket.js
yarman1/js-problems
54fd576ae8715d09ca2ba8dc4bc0a355fa8e9ed1
[ "MIT" ]
null
null
null
/** * Счастливым билетом называют такой билет с шестизначным номером, * где сумма первых трех цифр равна сумме последних трех. * * Напишите функцию checkTicket(number) которая проверяет счастливость билета. * * Пример: * * checkTicket('005212') === true * checkTicket('133700') === true * checkTicket('123032') === false * * @param {string} number * @returns {boolean} */ function checkTicket(number) { let firstSum = 0; let secondSum = 0; const numbers = number.split('') .map((number)=>parseInt(number, 10)); for (index in numbers){ if(index > 2){ secondSum += numbers[index]; continue; } firstSum += numbers[index]; } return firstSum === secondSum ? true : false; } module.exports = checkTicket;
24.6875
78
0.626582
6732dfc61c2997ac732a665e20fcf68c5288caee
581
js
JavaScript
e2e-tests/cypress/support/appeal-navigation-confirmation/eligibility/confirmNavigationNoDecisionDatePage.js
Planning-Inspectorate/appeal-planning-decision
45c190540d8bdd4785bb77767dbea25ae100c80c
[ "MIT" ]
5
2021-03-22T16:33:15.000Z
2022-02-14T21:59:24.000Z
e2e-tests/cypress/support/appeal-navigation-confirmation/eligibility/confirmNavigationNoDecisionDatePage.js
Planning-Inspectorate/appeal-planning-decision
45c190540d8bdd4785bb77767dbea25ae100c80c
[ "MIT" ]
189
2021-02-22T14:33:35.000Z
2022-03-29T21:15:46.000Z
e2e-tests/cypress/support/appeal-navigation-confirmation/eligibility/confirmNavigationNoDecisionDatePage.js
foundry4/appeal-planning-decision
45c190540d8bdd4785bb77767dbea25ae100c80c
[ "MIT" ]
4
2020-10-23T14:41:11.000Z
2021-01-28T09:35:31.000Z
module.exports = () => { cy.url().should('include', '/eligibility/no-decision'); cy.wait(2000); const serviceTxt = cy.get('.govuk-heading-l'); assert.exists(serviceTxt, 'This service is only for householder content exists'); const contentTxt = cy.get('.govuk-body'); assert.exists(contentTxt, 'If you applied for householder planning permission content exists'); cy.get('[data-cy="appeal-decision-service"]').invoke('attr', 'href').then((href) => { expect(href).to.contain("https://acp.planninginspectorate.gov.uk/"); }); cy.wait(Cypress.env('demoDelay')); }
44.692308
97
0.688468
6733d3adaf1d1711c5a30d45377ebeefee56e98c
1,828
js
JavaScript
source/ScriptRunner.js
Cykelero/tasklemon
35cbf46f24cdfd7c6d64dfa0cdbe94ef809864fd
[ "MIT" ]
83
2018-10-07T06:38:50.000Z
2021-11-09T11:06:02.000Z
source/ScriptRunner.js
Cykelero/tasklemon
35cbf46f24cdfd7c6d64dfa0cdbe94ef809864fd
[ "MIT" ]
6
2019-08-20T13:36:18.000Z
2021-06-06T19:33:50.000Z
source/ScriptRunner.js
Cykelero/tasklemon
35cbf46f24cdfd7c6d64dfa0cdbe94ef809864fd
[ "MIT" ]
1
2021-04-02T18:48:37.000Z
2021-04-02T18:48:37.000Z
/* Methods for running a TL script, based on its raw source, path, and arguments. */ const path = require('path'); const fs = require('fs'); const os = require('os'); const rimraf = require('rimraf'); const crossSpawn = require('cross-spawn'); const Constants = require('./Constants'); const ScriptParser = require('./ScriptParser'); const PackageCache = require('./PackageCache'); const ScriptEnvironment = require('./ScriptEnvironment'); module.exports = { run(scriptSource, scriptPath, args) { const parser = new ScriptParser(scriptSource); const requiredPackages = parser.requiredPackages; const requiredPackageVersions = parser.requiredPackageVersions; let stagePath; let preparedScriptPath; // Set environment variables ScriptEnvironment.sourceScriptPath = scriptPath; ScriptEnvironment.requiredRuntimeVersion = parser.requiredRuntimeVersion; ScriptEnvironment.rawArguments = args; ScriptEnvironment.defaultBundlePackageList = requiredPackages; ScriptEnvironment.requiredPackageVersions = requiredPackageVersions; // Write script to stage stagePath = fs.mkdtempSync(os.tmpdir() + path.sep); preparedScriptPath = path.join(stagePath, path.basename(scriptPath)); fs.writeFileSync(preparedScriptPath, parser.preparedSource); // Preload packages asynchronously PackageCache.loadPackageBundle(requiredPackages, requiredPackageVersions); // Execute script require(preparedScriptPath); // Delete stage once script has run process.on('exit', () => { rimraf.sync(stagePath); }); }, runInNewProcess(scriptPath, scriptArgs, nodeArgs) { const inspectableProcess = crossSpawn( 'node', [...nodeArgs, Constants.TASKLEMON_PATH, scriptPath, ...scriptArgs], { stdio: 'inherit' } ); inspectableProcess.on('exit', code => { process.exit(code); }); } };
29.967213
84
0.74453
67349117be759326f927c63d14e4581c13060d7a
15,214
js
JavaScript
chrome/content/wizard.js
MaxOfLondon/ppmbuddy
d30a3bee1215b333dede15274d460a7ceb7efdbb
[ "MIT" ]
null
null
null
chrome/content/wizard.js
MaxOfLondon/ppmbuddy
d30a3bee1215b333dede15274d460a7ceb7efdbb
[ "MIT" ]
null
null
null
chrome/content/wizard.js
MaxOfLondon/ppmbuddy
d30a3bee1215b333dede15274d460a7ceb7efdbb
[ "MIT" ]
null
null
null
var wizard = { controls: new Array(), labels: new Array(), valueCount: 0, rowCount: 0, columnCount: 0, startDate: new Date(), endDate: new Date(), onLoad: function() { this.mapControls(); this.mapLabels(); this.columnCount = this.valueCount / this.rowCount; //this.labels.length does not work // this.rowCount = 0; // for (var i in this.labels) // this.rowCount++; var value = 5;//100 / this.rowCount; for (i in this.labels) { this.addLabel(this.sanitizeString(this.labels[i]), value); } var datePicker = document.getElementById("datePicker"); var datePicker1 = document.getElementById("datePicker1"); var now = new Date(); datePicker1.value = now.format("Y-m-d"); now.setDate(now.getDate()-6); // a week including today datePicker.value = now.format("Y-m-d"); this.initialized = true; this.strings = document.getElementById("HelloWorld-strings"); }, mapControls: function() { this.controls = new Array(); var s = window.arguments[0].document.getElementsByTagName('input'); var condValidNames = /(^MISC|^TASK)_.+/i; var condDateControl = /.+_date$/i; for(var i=0;i<s.length;i++) { if (s[i].id.search(condValidNames) != -1) { if (s[i].id.search(condDateControl) == -1) { this.controls[s[i].id] = new Array(s[i], ""); } else { this.valueCount++; this.controls[s[i].id.slice(0, -5)][1] = s[i].value; } } } //return controls; }, mapLabels: function() { var items = new Array(); var s = window.arguments[0].document.getElementsByTagName('input'); var condValidNames = /(^1cw_MISC|^1cw_TASK)_.+/i; var condTypeSubItem = /(_\d+){2}$/i; for (var i=0; i < s.length; i++) { if (s[i].id.search(condValidNames) != -1) { this.rowCount++; var tmp = s[i].parentNode.parentNode.innerHTML; items[s[i].id] = this.stripHtml(tmp);//.replace(/<[^>]*>?/g,''); } } this.labels = items; }, addLabel: function(label, value) { var listbox = document.getElementById('itemList'); var listItem = document.createElement('listitem'); var cell = document.createElement('listcell'); cell.setAttribute('label', label); listItem.appendChild(cell); cell = document.createElement('listcell'); cell.setAttribute('label', value); listItem.appendChild(cell); listbox.appendChild(listItem); }, loadWeight: function(value) { var listbox = document.getElementById('itemList'); var selectedItem = listbox.selectedItem; var weight = document.getElementById('weight'); weight.value = selectedItem.children[1].getAttribute('label'); weight.disabled = false; }, updateWeight: function() { var listbox = document.getElementById('itemList'); var selectedItem = listbox.selectedItem; var ctrlWeight = document.getElementById('weight'); if (selectedItem != null) selectedItem.children[1].setAttribute('label', ctrlWeight.value); }, updateWeight2: function() { var listbox = document.getElementById('itemList'); var selectedItem = listbox.selectedItem; var selectedIndex = listbox.selectedIndex; var ctrlWeight = document.getElementById('weight'); var newWeight = ctrlWeight.value; var oldWeight = selectedItem.children[1].getAttribute('label'); var oldReminderWeight = (100 - oldWeight)/100; var newRemiderWeight = (100 - newWeight)/100; // create weights to array var weights = new Array(); for (var i = 0; i < listbox.itemCount; i++ ) { var value = listbox.getItemAtIndex(i).children[1].getAttribute('label') / 100 / oldReminderWeight * newRemiderWeight; weights[i] = this.roundVal(value * 100 ); } weights[selectedIndex] = this.roundVal(newWeight); //write back all values for (i = 0; i < listbox.itemCount; i++ ) { listbox.getItemAtIndex(i).children[1].setAttribute('label', weights[i]); } this.validateInput(); ctrlWeight.value = selectedItem.children[1].getAttribute('label'); ctrlWeight.focus(); }, updateValues: function() { var datePicker = document.getElementById("datePicker"); var datePicker1 = document.getElementById("datePicker1"); var listbox = document.getElementById('itemList'); var overwriteValues = !document.getElementById('keepExisting').checked; var overtimeTarget = parseFloat((document.getElementById('alowOvertime').checked?document.getElementById('overtimeHours').value:0)); var dayTarget = parseFloat(document.getElementById('targetHours').value); var resolution = Math.round((document.getElementById('resolution').value/60)*100)/100; var startDateParts = datePicker.value.split('-'); var endDateParts = datePicker1.value.split('-'); this.startDate = new Date(startDateParts[0], startDateParts[1] - 1, startDateParts[2]); this.endDate = new Date(endDateParts[0], endDateParts[1] - 1, endDateParts[2]); //Firebug.Console.log(this.startDate); //alert(this.endDate); //this.startDate = new Date(datePicker.value); //this.endDate = new Date(datePicker1.value); if (this.endDate < this.startDate) { // swap dates var tnpDate = this.startDate; this.endDate = this.startDate; this.startDate = tnpDate; } var includedColumnCount = DateDiff.inDays(this.startDate, this.endDate) + 1; var index = ''; var cols = new Array(); var rowIdx = -1; var controlIdx = -1; for (var i in this.controls) { var dateParts = this.controls[i][1].split('/'); var date = new Date(20+dateParts[2], dateParts[0] - 1, dateParts[1]); controlIdx ++; if (date.getDay() == 6 && !document.getElementById('saturdays').checked) continue; if (date.getDay() == 0 && !document.getElementById('sundays').checked) continue; if ((date >= this.startDate) && (date <= this.endDate)) { index = this.controls[i][1].replace(/\//g,'_'); rowIdx = Math.floor(controlIdx / this.columnCount); var value = parseFloat(this.controls[i][0].value); var propability = parseFloat(listbox.getItemAtIndex(rowIdx).children[1].getAttribute('label'))/10; var exclude = (!overwriteValues && value > 0) || (propability == 0); if (cols[index] == undefined) { cols[index] = new Array(); } cols[index].push( new Array( this.controls[i][0] /* [0] object */ ,propability /* [1] weight */ ,(!overwriteValues && value > 0 ?value :0) /* [2] value */ ,false /* [3] target reached */ ,exclude /* [4] exclude from processing and updating */ ) ); } } //for controls for (index in cols) { var columnValue = 0; for (i = 0; i < cols[index].length; i++) { columnValue += cols[index][i][2]; } var target = dayTarget - columnValue + Math.randomMax(overtimeTarget, true, resolution); do { for (i = 0; i < cols[index].length; i++) { if (cols[index][i][3] || cols[index][i][4]) continue; if (Math.random() <= cols[index][i][1]) { cols[index][i][2] += resolution; target -= resolution; } if (target <= 0) break; } } while (target > 0); // update timesheet for (i = 0; i < cols[index].length; i++) { if (cols[index][i][4]) continue; cols[index][i][0].value = cols[index][i][2].toFixed(2); //cols[index][i][0].onChange(); } } }, roundVal: function(val) { var dec = 2; var result = Math.round(val*Math.pow(10,dec))/Math.pow(10,dec); return result; }, stripHtml: function(html) { var tmp = window.arguments[0].document.createElement("div"); tmp.innerHTML = html; var result = tmp.textContent;//||tmp.innerText; return result; }, validateInput: function() { var field = document.getElementById('weight'); var value = field.value.replace(/[^\d\.]/g, ''); value = value.replace(/(\d*)\.+/g, '$1.'); value = value.replace(/(\d*)\.(\d*)\./g, '$1.$2'); if (parseFloat(value) < 0) value = 0; if (parseFloat(value) > 10) value = 10; field.value = value; var button = document.getElementById('saveWeight'); button.disabled = ((field.value == "") && !this.isNumeric(field.value)); }, isNumber: function(n) { return !isNaN(parseFloat(n)) && isFinite(n); }, sanitizeString: function(str) { str = str.replace(/\s{2,}/g, ' '); str = str.replace(/\s\d+\.\d+/g, ''); return str; }, nextStep: function(step) { if (step == 1) { var tab = document.getElementById('myTabList'); tab.tabs.advanceSelectedTab(); } else { this.updateValues(); window.close(); } } }; window.addEventListener("load", function () { wizard.onLoad(); }, false); // Simulates PHP's date function Date.prototype.format = function(format) { var returnStr = ''; var replace = Date.replaceChars; for (var i = 0; i < format.length; i++) { var curChar = format.charAt(i); if (i - 1 >= 0 && format.charAt(i - 1) == "\\") { returnStr += curChar; } else if (replace[curChar]) { returnStr += replace[curChar].call(this); } else if (curChar != "\\"){ returnStr += curChar; } } return returnStr; }; Date.replaceChars = { shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // Day d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); }, D: function() { return Date.replaceChars.shortDays[this.getDay()]; }, j: function() { return this.getDate(); }, l: function() { return Date.replaceChars.longDays[this.getDay()]; }, N: function() { return this.getDay() + 1; }, S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); }, w: function() { return this.getDay(); }, z: function() { var d = new Date(this.getFullYear(),0,1); return Math.ceil((this - d) / 86400000); }, // Fixed now // Week W: function() { var d = new Date(this.getFullYear(), 0, 1); return Math.ceil((((this - d) / 86400000) + d.getDay() + 1) / 7); }, // Fixed now // Month F: function() { return Date.replaceChars.longMonths[this.getMonth()]; }, m: function() { return (this.getMonth() < 9 ? '0' : '') + (this.getMonth() + 1); }, M: function() { return Date.replaceChars.shortMonths[this.getMonth()]; }, n: function() { return this.getMonth() + 1; }, t: function() { var d = new Date(); return new Date(d.getFullYear(), d.getMonth(), 0).getDate() }, // Fixed now, gets #days of date // Year L: function() { var year = this.getFullYear(); return (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)); }, // Fixed now o: function() { var d = new Date(this.valueOf()); d.setDate(d.getDate() - ((this.getDay() + 6) % 7) + 3); return d.getFullYear();}, //Fixed now Y: function() { return this.getFullYear(); }, y: function() { return ('' + this.getFullYear()).substr(2); }, // Time a: function() { return this.getHours() < 12 ? 'am' : 'pm'; }, A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; }, B: function() { return Math.floor((((this.getUTCHours() + 1) % 24) + this.getUTCMinutes() / 60 + this.getUTCSeconds() / 3600) * 1000 / 24); }, // Fixed now g: function() { return this.getHours() % 12 || 12; }, G: function() { return this.getHours(); }, h: function() { return ((this.getHours() % 12 || 12) < 10 ? '0' : '') + (this.getHours() % 12 || 12); }, H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); }, i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); }, s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); }, u: function() { var m = this.getMilliseconds(); return (m < 10 ? '00' : (m < 100 ?'0' : '')) + m; }, // Timezone e: function() { return "Not Yet Supported"; }, I: function() { return "Not Yet Supported"; }, O: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + '00'; }, P: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + ':00'; }, // Fixed now T: function() { var m = this.getMonth(); this.setMonth(0); var result = this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/, '$1'); this.setMonth(m); return result;}, Z: function() { return -this.getTimezoneOffset() * 60; }, // Full Date/Time c: function() { return this.format("Y-m-d\\TH:i:sP"); }, // Fixed now r: function() { return this.toString(); }, U: function() { return this.getTime() / 1000; } }; Math.randomMax = function(maxVal, asFloat, resolution) { if (asFloat) { var result = Math.random()*maxVal; if (resolution != undefined) result = Math.round(result/resolution)*resolution return result; } else return Math.floor(Math.random()*maxVal+1); } // function to use while checking if element is in array function convertToObject(a) { var o = {}; for(var i=0;i<a.length;i++) { o[a[i]]=''; } return o; } var DateDiff = { inDays: function(d1, d2) { var t2 = d2.getTime(); var t1 = d1.getTime(); return parseInt((t2-t1)/(24*3600*1000)); }, inWeeks: function(d1, d2) { var t2 = d2.getTime(); var t1 = d1.getTime(); return parseInt((t2-t1)/(24*3600*1000*7)); }, inMonths: function(d1, d2) { var d1Y = d1.getFullYear(); var d2Y = d2.getFullYear(); var d1M = d1.getMonth(); var d2M = d2.getMonth(); return (d2M+12*d2Y)-(d1M+12*d1Y); }, inYears: function(d1, d2) { return d2.getFullYear()-d1.getFullYear(); } }
37.565432
220
0.560536
6735bfaef9488a608cf26063b9a3cf09439ffdce
787
js
JavaScript
front-end/pocket-front-web-main/src/redux/reducers/rootReducer.js
redatawfik/Pocket-Tanks
078aa9f12104101a53e9c0c2f7814094aa943953
[ "BSD-2-Clause" ]
1
2021-03-20T22:40:39.000Z
2021-03-20T22:40:39.000Z
front-end/pocket-front-web-main/src/redux/reducers/rootReducer.js
MahmoudMuhammedAli/Pocket-Tanks
d457b61e7f90769b3747b4bb898c9d1b870396ed
[ "BSD-2-Clause" ]
null
null
null
front-end/pocket-front-web-main/src/redux/reducers/rootReducer.js
MahmoudMuhammedAli/Pocket-Tanks
d457b61e7f90769b3747b4bb898c9d1b870396ed
[ "BSD-2-Clause" ]
3
2021-01-11T17:43:14.000Z
2021-12-21T17:00:04.000Z
import {SET_AUTH} from '../constants' import {persistReducer} from 'redux-persist' import {combineReducers} from 'redux' import storage from 'redux-persist/lib/storage'; const intialUser = { user : null, } const intialTest = { test : "null" } const user = (state = intialUser, action) => { switch (action.type) { case SET_AUTH : return {...state , user : action.user} default : return state } } const test = (state = intialTest , action) => { switch (action.type) { case 'SET_TEST' : return {...state , test : action.test} default : return state } } const persistConf = { key : 'root', storage, whiteList : ['user'] } const root = combineReducers({user ,test}) export default persistReducer(persistConf , root)
24.59375
64
0.631512
67360ad76a48c6ecffc3bb67426fd39050a08204
7,095
js
JavaScript
src/play/data/maps.js
project-trio/moba
4a394665fe9c25ab6b474e58cbc90ed6c46f0b51
[ "0BSD" ]
null
null
null
src/play/data/maps.js
project-trio/moba
4a394665fe9c25ab6b474e58cbc90ed6c46f0b51
[ "0BSD" ]
null
null
null
src/play/data/maps.js
project-trio/moba
4a394665fe9c25ab6b474e58cbc90ed6c46f0b51
[ "0BSD" ]
null
null
null
const maps = {} { const WALL_RADIUS = 24 let wH, hH // Tutorial const TUTORIAL_WIDTH = 400 const TUTORIAL_HEIGHT = 1000 wH = TUTORIAL_WIDTH / 2 hH = TUTORIAL_HEIGHT / 2 const WALL_Y = hH - 80 const WALL_LENGTH = 116 maps.tutorial = { minSize: 0, maxSize: 0, width: TUTORIAL_WIDTH, height: TUTORIAL_HEIGHT, towers: [ ['base', wH, 44, false], ['turret', WALL_LENGTH + 4, WALL_Y, false], ], walls: [ { start: { x: TUTORIAL_WIDTH / 2, y: 0 }, radius: WALL_RADIUS, move: [ { dx: TUTORIAL_WIDTH / 4, dy: 0}, { dx: 0, dy: WALL_Y / 2 }, { dx: -(WALL_LENGTH) / 2 + WALL_RADIUS, dy: 0 }, ], mirror: false, endCap: true, }, ], spawn: { interval: 25, initialDelay: 10, }, minions: [ { type: 'ranged', paths: [ [[wH - 40, 74, 0, 0], [wH - 40, hH, 0, -1000]], [[wH, 80, 0, 0], [wH, hH, 0, -1000]], [[wH + 40, 74, 0, 0], [wH + 40, hH, 0, -1000]], ], mirror: false, }, ], } // Tiny const TINY_WIDTH = 900 const TINY_HEIGHT = 800 wH = TINY_WIDTH / 2 hH = TINY_HEIGHT / 2 maps.tiny = { minSize: 0, maxSize: 2, width: TINY_WIDTH, height: TINY_HEIGHT, towers: [ ['base', wH, 44, false], ['turret', wH - 70, hH - 95, false], ], walls: [ { start: { x: TINY_WIDTH / 5, y: TINY_HEIGHT / 5 }, radius: WALL_RADIUS, move: [ { dx: 0, dy: -hH / 5 }, ], mirror: true, endCap: true, }, { start: { x: TINY_WIDTH, y: hH }, radius: WALL_RADIUS, move: [ { dx: -15, dy: 0 }, ], mirror: false, endCap: true, }, ], spawn: { interval: 20, initialDelay: 6, }, minions: [ { type: 'ranged', paths: [ [[wH - 40, 74, 0, 0], [wH - 40, hH, 0, -1000]], [[wH, 80, 0, 0], [wH, hH, 0, -1000]], [[wH + 40, 74, 0, 0], [wH + 40, hH, 0, -1000]], ], mirror: false, }, ], } // Small const SMALL_WIDTH = 1000 const SMALL_HEIGHT = 1400 wH = SMALL_WIDTH / 2 hH = SMALL_HEIGHT / 2 maps.small = { minSize: 0, maxSize: 4, width: SMALL_WIDTH, height: SMALL_HEIGHT, towers: [ ['base', wH, 44, false], ['tower', 210, 340, true], ['turret', wH + 80, hH - 100, false], ], walls: [ { start: { x: wH - 100, y: 330 }, radius: WALL_RADIUS, move: [ { dx: 100, dy: 0 }, ], mirror: false, endCap: true, }, { start: { x: SMALL_WIDTH, y: hH - 80 }, radius: WALL_RADIUS, move: [ { dx: -50, dy: 0 }, ], mirror: false, endCap: true, }, ], spawn: { interval: 20, initialDelay: 6, }, minions: [ { type: 'melee', paths: [ [[wH - 80, 30, 0, 0], [wH / 2 + 60, 300 - 30, 417, -909], [wH - 80 + 30, hH, -310, -951]], [[wH - 80, 60, 0, 0], [wH / 2 + 30, 300 + 0, 504, -864], [wH - 80 + 0, hH, -330, -944]], [[wH - 80, 90, 0, 0], [wH / 2 + 0, 300 + 30, 578, -816], [wH - 80 - 30, hH, -354, -935]], ], mirror: true, }, ], } // Standard const STANDARD_WIDTH = 1200 const STANDARD_HEIGHT = 2000 wH = STANDARD_WIDTH / 2 hH = STANDARD_HEIGHT / 2 maps.standard = { minSize: 2, maxSize: 12, width: STANDARD_WIDTH, height: STANDARD_HEIGHT, towers: [ ['base', wH, 44, false], ['tower', 435, 360, true], ['turret', 44, 440, true], ['turret', wH - 300, hH - 160, true], ], walls: [ { start: { x: 380, y: 360 }, radius: WALL_RADIUS, move: [ { dx: -60, dy: 0 }, { dx: 0, dy: -60 }, ], mirror: true, endCap: true, }, ], spawn: { interval: 20, initialDelay: 6, }, minions: [ { type: 'melee', paths: [ [[wH - 80, 90, 0, 0], [90, 100, hH, -23], [90, 360, 0, -hH], [260, 880, -311, -950], [260, hH, 0, -hH]], [[wH - 80, 60, 0, 0], [120, 70, hH, -25], [120, 390, 0, -hH], [300, 880, -345, -939], [300, hH, 0, -hH]], [[wH - 80, 30, 0, 0], [150, 40, hH, -27], [150, 420, 0, -hH], [340, 880, -382, -924], [340, hH, 0, -hH]], ], mirror: true, }, { type: 'ranged', paths: [ [[wH - 40, 74, 0, 0], [wH - 40, hH, 0, -hH]], [[wH, 80, 0, 0], [wH, hH, 0, -hH]], [[wH + 40, 74, 0, 0], [wH + 40, hH, 0, -hH]], ], mirror: false, }, ], } // Large const LARGE_WIDTH = 2000 const LARGE_HEIGHT = 2000 wH = LARGE_WIDTH / 2 hH = LARGE_HEIGHT / 2 maps.large = { minSize: 6, maxSize: 25, width: LARGE_WIDTH, height: LARGE_HEIGHT, towers: [ ['base', wH, 44, false], ['tower', wH - 350, 400, true], ['tower', 44, 440, true], ['turret', 400, hH - 200, true], ['turret', wH - 120, hH - 100, false], ], walls: [ { start: { x: 380, y: 400 }, radius: WALL_RADIUS, move: [ { dx: -60, dy: 0 }, { dx: 0, dy: -60 }, ], mirror: true, endCap: true, }, { start: { x: wH - 100, y: 400 }, radius: WALL_RADIUS, move: [ { dx: 100, dy: 0 }, ], mirror: false, endCap: true, }, ], spawn: { interval: 20, initialDelay: 6, }, minions: [ { type: 'melee', paths: [ [[wH - 80, 90, 0, 0], [90, 100, hH, -12], [90, 360, 0, -hH], [260, 880, -311, -950], [260, hH, 0, -hH]], [[wH - 80, 60, 0, 0], [120, 70, hH, -12], [120, 390, 0, -hH], [300, 880, -345, -939], [300, hH, 0, -hH]], [[wH - 80, 30, 0, 0], [150, 40, hH, -13], [150, 420, 0, -hH], [340, 880, -382, -924], [340, hH, 0, -hH]], ], mirror: true, }, { type: 'ranged', paths: [ [[wH + 10, 80, 0, 0], [wH + 170, hH / 2, -356, -934], [wH + 170, hH, 0, -1000]], [[wH + 50, 80, 0, 0], [wH + 210, hH / 2, -356, -934], [wH + 210, hH, 0, -1000]], [[wH + 90, 80, 0, 0], [wH + 250, hH / 2, -356, -934], [wH + 250, hH, 0, -1000]], ], mirror: true, }, ], } // Retro const RETRO_WIDTH = 1000 const RETRO_HEIGHT = 1666 const RETRO_WALL_RADIUS = 36 wH = RETRO_WIDTH / 2 hH = RETRO_HEIGHT / 2 maps.retro = { minSize: 1, maxSize: 12, width: RETRO_WIDTH, height: RETRO_HEIGHT, towers: [ ['base', wH, 56, false], ['tower', 317, 393, true], ['tower', 285, 684, false], ['tower', 800, 684, false], ], walls: [ { start: { x: 220, y: 320 }, radius: RETRO_WALL_RADIUS, move: [ { dx: 48, dy: 0 }, { dx: 0, dy: -48 }, ], mirror: true, endCap: true, }, ], spawn: { interval: 20, initialDelay: 6, rangedDelay: 3, rangedWaveEvery: 2, }, minions: [ { type: 'melee', paths: [ [[wH - 60, 90, 0, 0], [90, 100, hH, -23], [90, 360, 0, -hH], [260, 880, -311, -950], [260, hH, 0, -hH]], [[wH - 60, 60, 0, 0], [120, 70, hH, -25], [120, 390, 0, -hH], [300, 880, -345, -939], [300, hH, 0, -hH]], [[wH - 60, 30, 0, 0], [150, 40, hH, -27], [150, 420, 0, -hH], [340, 880, -382, -924], [340, hH, 0, -hH]], ], mirror: true, }, { type: 'ranged', paths: [ [[wH - 40, 74, 0, 0], [wH - 40, hH, 0, -hH]], [[wH, 80, 0, 0], [wH, hH, 0, -hH]], [[wH + 40, 74, 0, 0], [wH + 40, hH, 0, -hH]], ], mirror: false, }, ], } } module.exports = maps
19.227642
110
0.467653
6736252ee48981ca0280f749fe407c6a1550de0c
4,273
js
JavaScript
ui.js
sangwo/abetterpassword.today
76b8b43a1cceb2d6052c04da8c2bdace7b9045cd
[ "MIT" ]
null
null
null
ui.js
sangwo/abetterpassword.today
76b8b43a1cceb2d6052c04da8c2bdace7b9045cd
[ "MIT" ]
null
null
null
ui.js
sangwo/abetterpassword.today
76b8b43a1cceb2d6052c04da8c2bdace7b9045cd
[ "MIT" ]
null
null
null
$(document).ready(function() { var DEFAULT_LENGTH = 8; var DEFAULT_HAS_DIGITS = true; var DEFAULT_HAS_LOWERCASE_LETTERS = true; var DEFAULT_HAS_UPPERCASE_LETTERS = true; var DEFAULT_HAS_SPACES = false; var DEFAULT_HAS_SPECIAL_CHARS = false; var DEFAULT_MIN_NUM_DIGITS = 1; var DEFAULT_MIN_NUM_LOWERCASE_LETTERS = 1; var DEFAULT_MIN_NUM_UPPERCASE_LETTERS = 1; var inputs = { length: $('input[name="length"]'), useDigitsCheckbox: $('input[name="use_digits"]'), useLowercaseLettersCheckbox: $('input[name="use_lowercase_letters"]'), useUppercaseLettersCheckbox: $('input[name="use_uppercase_letters"]'), minNumDigits: $('input[name="min_num_digits"]'), minNumLowercaseLetters: $('input[name="min_num_lowercase_letters"]'), minNumUppercaseLetters: $('input[name="min_num_uppercase_letters"]') } function setDefaults() { inputs.length.val(DEFAULT_LENGTH); inputs.useDigitsCheckbox.prop("checked", DEFAULT_HAS_DIGITS); inputs.useLowercaseLettersCheckbox.prop("checked", DEFAULT_HAS_LOWERCASE_LETTERS); inputs.useUppercaseLettersCheckbox.prop("checked", DEFAULT_HAS_LOWERCASE_LETTERS); inputs.minNumDigits.val(DEFAULT_MIN_NUM_DIGITS); inputs.minNumLowercaseLetters.val(DEFAULT_MIN_NUM_LOWERCASE_LETTERS); inputs.minNumUppercaseLetters.val(DEFAULT_MIN_NUM_UPPERCASE_LETTERS); } function setPasswordFromSettings() { // clear prev error message $('#error-message').text(''); var length = parseInt(inputs.length.val()); var hasDigits = inputs.useDigitsCheckbox.prop("checked"); var hasLowercaseLetters = inputs.useLowercaseLettersCheckbox.prop("checked"); var hasUppercaseLetters = inputs.useUppercaseLettersCheckbox.prop("checked"); var hasSpaces = $('input[name="use_spaces"]').prop("checked"); var hasSpecialChars = $('input[name="use_special_chars"]').prop("checked"); // minimum numbers if(inputs.minNumDigits.prop("disabled")) { var minNumDigits = 0; } else { var minNumDigits = parseInt(inputs.minNumDigits.val()); } if(inputs.minNumLowercaseLetters.prop("disabled")) { var minNumLowercaseLetters = 0; } else { var minNumLowercaseLetters = parseInt(inputs.minNumLowercaseLetters.val()); } if(inputs.minNumUppercaseLetters.prop("disabled")) { var minNumUppercaseLetters = 0; } else { var minNumUppercaseLetters = parseInt(inputs.minNumUppercaseLetters.val()); } try { var generatedPassword = generatePassword( length || DEFAULT_LENGTH, hasDigits, hasLowercaseLetters, hasUppercaseLetters, hasSpaces, hasSpecialChars, minNumDigits, minNumLowercaseLetters, minNumUppercaseLetters ); $('#generated-password').text(generatedPassword); } catch(err) { $('#error-message').text(err); } } // check if digits/lowercase/uppercase checkboxes are checked, if not checked, disable min inputs function addEventHandlers() { inputs.useDigitsCheckbox.on('change', function() { if(!$(this).prop("checked")) { inputs.minNumDigits.prop("disabled", true); } else { inputs.minNumDigits.prop("disabled", false); } }); inputs.useLowercaseLettersCheckbox.on('change', function() { if(!$(this).prop("checked")) { inputs.minNumLowercaseLetters.prop("disabled", true); } else { inputs.minNumLowercaseLetters.prop("disabled", false); } }); inputs.useUppercaseLettersCheckbox.on('change', function() { if(!$(this).prop("checked")) { inputs.minNumUppercaseLetters.prop("disabled", true); } else { inputs.minNumUppercaseLetters.prop("disabled", false); } }); // select all min num inputs var minNumInputs = inputs.minNumDigits .add(inputs.minNumLowercaseLetters) .add(inputs.minNumUppercaseLetters); // on blur, if input is empty, make it into 0 minNumInputs.on('blur', function() { if($(this).val() == '') { $(this).val(0); } }); // when user clicks button, generate password $('#generate-password-button').on('click', setPasswordFromSettings); } setDefaults(); // generate password by default on page load setPasswordFromSettings(); addEventHandlers(); });
32.618321
99
0.692722
6736f89b6afedac11edf344d0174c27f43c2558a
1,220
js
JavaScript
packages/meen-utils/index.js
ducdhm/meen
e251214b478ce8bd3ba20b418e311b5c6e6419fd
[ "MIT" ]
6
2018-12-12T08:35:11.000Z
2020-06-06T08:23:28.000Z
packages/meen-utils/index.js
ducdhm/meen-core
e251214b478ce8bd3ba20b418e311b5c6e6419fd
[ "MIT" ]
6
2021-08-13T11:33:49.000Z
2021-08-13T11:33:50.000Z
packages/meen-utils/index.js
ducdhm/meen
e251214b478ce8bd3ba20b418e311b5c6e6419fd
[ "MIT" ]
null
null
null
module.exports = { cleanFolder: require('./src/cleanFolder'), ensureArray: require('./src/ensureArray'), formatCurrency: require('./src/formatCurrency'), getExcelSheetData: require('./src/getExcelSheetData'), getFileList: require('./src/getFileList'), getFolderList: require('./src/getFolderList'), getLogger: require('./src/getLogger'), getObjectValues: require('./src/getObjectValues'), getUploadFileName: require('./src/getUploadFileName'), getWinstonLogger: require('./src/getWinstonLogger'), isValidJsonString: require('./src/isValidJsonString'), loopArray: require('./src/loopArray'), newError: require('./src/newError'), normalizeSpace: require('./src/normalizeSpace'), removeTone: require('./src/removeTone'), resolvePath: require('./src/resolvePath'), toCamelCase: require('./src/toCamelCase'), toKebabCase: require('./src/toKebabCase'), toPascalCase: require('./src/toPascalCase'), toSentenceCase: require('./src/toSentenceCase'), toSnakeCase: require('./src/toSnakeCase'), toTitleCase: require('./src/toTitleCase'), writeExcel: require('./src/writeExcel'), writeExcelToFile: require('./src/writeExcelToFile'), };
45.185185
58
0.697541
673760148fbb0fcbe91c0abe7182e5d8a17de482
3,604
js
JavaScript
JS-Applications/Course-Projects/02.Movies/Movies-Project/services.js
nixford/SoftUni-JavaScript-2020-TasksAndExams
cbddef757269317de778a813229538cc3446dbc2
[ "MIT" ]
null
null
null
JS-Applications/Course-Projects/02.Movies/Movies-Project/services.js
nixford/SoftUni-JavaScript-2020-TasksAndExams
cbddef757269317de778a813229538cc3446dbc2
[ "MIT" ]
null
null
null
JS-Applications/Course-Projects/02.Movies/Movies-Project/services.js
nixford/SoftUni-JavaScript-2020-TasksAndExams
cbddef757269317de778a813229538cc3446dbc2
[ "MIT" ]
null
null
null
const apiKey = 'AIzaSyDuIoJstS-cz6VnpUD6PT0-Q6uhxij9MSc'; const databaseUrl = `https://movies-60361-default-rtdb.europe-west1.firebasedatabase.app`; const request = async (url, method, body) => { let options = { method, }; if (body) { Object.assign(options, { headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); } let response = await fetch(url, options); let data = await response.json(); return data; } // ASYNC FUNCTION const authService = { async login(email, password) { let respose = await fetch(`https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=${apiKey}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ // wrap/serialize the object with JSON.stringify email, password, returnSecureToken: true, }) }); let data = await respose.json(); // We have to save idToken in order to have auhorized requests to the server (in order not to login every time) // therefore we save them locally with localStorage localStorage.setItem('auth', JSON.stringify(data)); // In localStorage we cannot save objects - thr must be serializt with JSON.stringify(data) return data; }, async register(email, password) { let respose = await fetch(`https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=${apiKey}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ // wrap/serialize the object with JSON.stringify email, password, returnSecureToken: true, }) }); let data = await respose.json(); localStorage.setItem('auth', JSON.stringify(data)); return data; }, getData() { try { let data = JSON.parse(localStorage.getItem('auth')); return { isAuthenticated: Boolean(data.idToken), email: data.email || '' }; } catch (error) { return { isAuthenticated: false, email: '' }; } }, logout() { localStorage.setItem('auth', ''); } }; // NOT ASYNC FUNCTION // const authService = { // login(email, password) { // fetch(`https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=${apiKey}`, { // method: 'POST', // headers: { // 'content-type': 'application/json', // }, // body: JSON.stringify({ // wrap/serialize the object with JSON.stringify // email, // password, // }) // }) // .then(res => res.json()) // .then(data => { // // We have to save idToken in order to have auhorized requests to the server (in order not to login every time) // // therefore we save them locally with localStorage // console.log(`DEBUG service.js: data: ${JSON.stringify(data)}`); // localStorage.setItem('auth', JSON.stringify(data)); // // In localStorage we cannot save objects - thr must be serializt with JSON.stringify(data) // }) // } // } const movieService = { async add(movieData) { let res = await request(`${databaseUrl}/movies.json`, 'POST', movieData); return res; }, async getAll() { let res = await request(`${databaseUrl}/movies.json`, 'GET'); // ({key, ...res[key]}) // Object.assign(res[key], {key}) return Object.keys(res).map(key => ({key, ...res[key]})); }, async getOne(id) { let res = await request(`${databaseUrl}/movies/${id}.json`, 'GET'); return res; } }
27.723077
120
0.600166
67383376ffe832bcb458aaf2909c8138a51563c3
1,192
js
JavaScript
resources/assets/js/validations.js
mahendralakmal/ewis
5a94d00a7ec6d8aa46cf949ba1e21ec6af3ba88c
[ "MIT" ]
null
null
null
resources/assets/js/validations.js
mahendralakmal/ewis
5a94d00a7ec6d8aa46cf949ba1e21ec6af3ba88c
[ "MIT" ]
null
null
null
resources/assets/js/validations.js
mahendralakmal/ewis
5a94d00a7ec6d8aa46cf949ba1e21ec6af3ba88c
[ "MIT" ]
null
null
null
$( "#clientProfile" ).validate({ rules: { name: "required", email: { required: true, email: true }, address: { required: true }, telephone: { required: true }, logo: { required: true }, color: { required: true }, cp_name: { required: true }, cp_designation: { required: true }, cp_branch: { required: true }, cp_telephone: { required: true }, cp_email: { required: true } } }); $( "#userCreate" ).validate({ rules: { email: { required: true, email: true }, password: { required:true, minlength:6, maxlength:12 }, cpassword: { equalTo: "#password" }, name: "required", designation: { required: true, }, nic_pass: { required:true, maxlength:12, minlength:7 }, } });
18.060606
32
0.366611
67390fcc6a0d6ff8332ca4e6fef89e411fd5b158
645
js
JavaScript
app/components/task-list/sortable-task-list.js
dev-tim/task-list
a61a2fb66cdece3020a85fdff402bab172c0cb9a
[ "MIT" ]
2
2017-04-20T12:21:52.000Z
2017-11-09T20:20:00.000Z
app/components/task-list/sortable-task-list.js
dev-tim/task-list
a61a2fb66cdece3020a85fdff402bab172c0cb9a
[ "MIT" ]
null
null
null
app/components/task-list/sortable-task-list.js
dev-tim/task-list
a61a2fb66cdece3020a85fdff402bab172c0cb9a
[ "MIT" ]
null
null
null
import React, {PropTypes} from 'react'; import {SortableContainer} from 'react-sortable-hoc'; import TaskList from './task-list'; const SortableTL = SortableContainer(TaskList); class SortableTaskList extends React.Component { render() { const {children, isLoading, onReorder} = this.props; return ( <SortableTL useDragHandle={true} isLoading={isLoading} onSortEnd={onReorder}> {children} </SortableTL> ) }; } SortableTaskList.propTypes = { children: PropTypes.node.isRequired, isLoading: PropTypes.bool, onReorder: PropTypes.func.isRequired }; export default SortableContainer(SortableTaskList);
23.888889
83
0.727132
673a8cf221ca83cd3f3ef220fc8523805975b654
262
js
JavaScript
server/models/settings.js
tartarouga/support-technique
68f5eb1cdec07d6d7734f1bd29cfe13a6ee1ed65
[ "MIT" ]
null
null
null
server/models/settings.js
tartarouga/support-technique
68f5eb1cdec07d6d7734f1bd29cfe13a6ee1ed65
[ "MIT" ]
7
2021-03-09T20:55:16.000Z
2022-03-02T05:59:58.000Z
server/models/settings.js
tartarouga/support-technique
68f5eb1cdec07d6d7734f1bd29cfe13a6ee1ed65
[ "MIT" ]
null
null
null
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var settingsSchema = new mongoose.Schema({ code: { type: String }, userId: { type: Schema.Types.ObjectId, ref: 'user' } }) module.exports = mongoose.model('settings', settingsSchema);
21.833333
60
0.69084
673a9c2837d86e44086e8f45d9e7373d87684b24
1,049
js
JavaScript
db/models/suncor_full.js
zhenyit/my-first-nodejs
aea4dfc32e22d139a53d37d421902a51a1ab4f8b
[ "MIT" ]
null
null
null
db/models/suncor_full.js
zhenyit/my-first-nodejs
aea4dfc32e22d139a53d37d421902a51a1ab4f8b
[ "MIT" ]
4
2021-03-02T00:30:13.000Z
2022-03-08T22:56:31.000Z
db/models/suncor_full.js
zhenyit/my-first-nodejs
aea4dfc32e22d139a53d37d421902a51a1ab4f8b
[ "MIT" ]
null
null
null
module.exports = function(sequelize, DataTypes) { const Suncor_full = sequelize.define('suncor_full', { id: { type: DataTypes.INTEGER, primaryKey: true }, Date: { type: DataTypes.STRING }, '101STM': { type: DataTypes.DOUBLE }, '102STM': { type: DataTypes.DOUBLE }, '103STM': { type: DataTypes.DOUBLE }, '104STM': { type: DataTypes.DOUBLE }, '105STM': { type: DataTypes.DOUBLE }, '106STM': { type: DataTypes.DOUBLE }, '107STM': { type: DataTypes.DOUBLE }, '108STM': { type: DataTypes.DOUBLE }, '109STM': { type: DataTypes.DOUBLE }, '110STM': { type: DataTypes.DOUBLE }, '115STM': { type: DataTypes.DOUBLE }, '116STM': { type: DataTypes.DOUBLE }, '117STM': { type: DataTypes.DOUBLE }, 'WOR': { type: DataTypes.DOUBLE } }, { freezeTableName: true }) Suncor_full.removeAttribute('id') return Suncor_full }
17.196721
55
0.525262
673d35fc0aa744a69f0b33d732e86e9cb51bab62
372
js
JavaScript
public/modules/despachoproduccions/services/despachoproduccions.client.service.js
gustavosinbandera1/meanStack
c770e0b94244c1e87f6b453789348a2e79af3ec2
[ "MIT" ]
null
null
null
public/modules/despachoproduccions/services/despachoproduccions.client.service.js
gustavosinbandera1/meanStack
c770e0b94244c1e87f6b453789348a2e79af3ec2
[ "MIT" ]
null
null
null
public/modules/despachoproduccions/services/despachoproduccions.client.service.js
gustavosinbandera1/meanStack
c770e0b94244c1e87f6b453789348a2e79af3ec2
[ "MIT" ]
null
null
null
'use strict'; //Despachoproduccions service used to communicate Despachoproduccions REST endpoints angular.module('despachoproduccions').factory('Despachoproduccions', ['$resource', function($resource) { return $resource('despachoproduccions/:despachoproduccionId', { despachoproduccionId: '@_id' }, { update: { method: 'PUT' } }); } ]);
26.571429
85
0.69086
673e198c6c93fafdba06fe2ca9344401713042fe
34
js
JavaScript
data/users.js
mrsharpoblunto/nameday
f2ae0e9c23978478ea43dd8ef34b798164d24816
[ "MIT" ]
null
null
null
data/users.js
mrsharpoblunto/nameday
f2ae0e9c23978478ea43dd8ef34b798164d24816
[ "MIT" ]
null
null
null
data/users.js
mrsharpoblunto/nameday
f2ae0e9c23978478ea43dd8ef34b798164d24816
[ "MIT" ]
null
null
null
module.exports = ['Alice','Bob'];
17
33
0.617647
673e2de7ca7beaccfbe570c9ff5948160c423e59
91
js
JavaScript
downloaders/index.js
JambDev/libkissanime
8c9eb9d833226efda5739cc965249f419122870e
[ "MIT" ]
1
2020-11-09T06:47:06.000Z
2020-11-09T06:47:06.000Z
downloaders/index.js
JambDev/libkissanime
8c9eb9d833226efda5739cc965249f419122870e
[ "MIT" ]
2
2020-11-09T05:27:31.000Z
2020-11-15T22:03:56.000Z
downloaders/index.js
JambDev/libkissanime
8c9eb9d833226efda5739cc965249f419122870e
[ "MIT" ]
null
null
null
module.exports = { //hydrax: require("./hydrax"), fserver: require("./fserver"), };
22.75
34
0.582418
673e97e51afeb13c4e56b0ee346ce4b9e87ef64c
510
js
JavaScript
app.js
zhoujiahua/layui-mirror
8e4f4c3a137a6b867a8f4810d5259bcc2d3b3717
[ "MIT" ]
2
2021-10-16T05:58:22.000Z
2021-10-16T09:06:11.000Z
app.js
zhoujiahua/layui-mirror
8e4f4c3a137a6b867a8f4810d5259bcc2d3b3717
[ "MIT" ]
null
null
null
app.js
zhoujiahua/layui-mirror
8e4f4c3a137a6b867a8f4810d5259bcc2d3b3717
[ "MIT" ]
3
2021-11-18T13:33:47.000Z
2021-12-27T09:14:43.000Z
const express = require("express"); const path = require("path"); const app = express(); //Set public folder app.use(express.static(path.join(__dirname, "public"))); app.use('/mirror', express.static(path.join(__dirname, "mirror"))); app.use('/docs', express.static(path.join(__dirname, "docs"))); // Home page app.get("/", (req, res) => { return res.redirect('/mirror/www.layui.net/index.htm') }); const port = process.env.PORT || 7000; app.listen(port, () => console.log(`http://localhost:${port}`));
30
67
0.664706
673f6e8b06e0fca7fcd9c5a5c5c77a3c9d2321ed
3,158
js
JavaScript
utm.js
stevenli5/utm
d47618bb371492a48e9ea62c0672b6a7707f4705
[ "MIT" ]
null
null
null
utm.js
stevenli5/utm
d47618bb371492a48e9ea62c0672b6a7707f4705
[ "MIT" ]
null
null
null
utm.js
stevenli5/utm
d47618bb371492a48e9ea62c0672b6a7707f4705
[ "MIT" ]
null
null
null
const mydata = JSON.parse(data); function generateURL(engLink, fraLink) { let source = document.getElementById("source").value; let source2 = document.getElementById("source2").value; let medium = document.getElementById("medium").value; let medium2 = document.getElementById("medium2").value; let campaign = document.getElementById("campaign").value; let campaign2 = document.getElementById("campaign2").value; let term = document.getElementById("term").value; let term2 = document.getElementById("term2").value; let content = document.getElementById("content").value; let content2 = document.getElementById("content2").value; let sourceChecked = true; let mediumChecked = true; let campaignChecked = true; let termChecked = true; let contentChecked = true; let utm = ""; let eng = engLink.value; let fra = fraLink.value; let engURL = ""; let fraURL = ""; if ((source === "") && (source2 === "")) { sourceChecked = false; } if ((medium === "") && (medium2 === "")) { mediumChecked = false; } if ((campaign === "") && (campaign2 === "")) { campaignChecked = false; } if ((term === "") && (term2 === "")) { termChecked = false; } if ((content === "") && (content2 === "")) { contentChecked = false; } if (sourceChecked) { utm += "?utm_source="; if (source2 !== "") { utm += source2; } else { utm += source; } } if (mediumChecked) { if (sourceChecked) { utm += "&utm_medium="; } else { utm += "?utm_medium="; } if (medium2 !== "") { utm += medium2; } else { utm += medium; } } if (campaignChecked) { if (sourceChecked || mediumChecked) { utm += "&utm_campaign="; } else { utm += "?utm_campaign="; } if (campaign2 !== "") { utm += campaign2; } else { utm += campaign; } } if (termChecked) { if (sourceChecked || mediumChecked || campaignChecked) { utm += "&utm_term="; } else { utm += "?utm_term="; } if (term2 !== "") { utm += term2; } else { utm += term; } } if (contentChecked) { if (sourceChecked || mediumChecked || campaignChecked || termChecked) { utm += "&utm_content="; } else { utm += "?utm_content="; } if (content2 !== "") { utm += content2; } else { utm += content; } } if (eng !== "") { engURL = eng + utm; } else { engURL = ""; } if (fra !== "") { fraURL = fra + utm; } else { fraURL = ""; } document.getElementById("engLink").value = engURL; document.getElementById("fraLink").value = fraURL; }
25.264
80
0.464851
673fe5dadd4c3ba1909be3331f07e55916f26cdf
122
js
JavaScript
test/karma/test-app/custom-elements-output-webpack/index.esm.js
TestOlliQuadrat/stencil
4a5da0ff052ed4bd303274b33d23f4989e410654
[ "MIT" ]
1
2022-01-21T08:52:42.000Z
2022-01-21T08:52:42.000Z
test/karma/test-app/custom-elements-output-webpack/index.esm.js
TestOlliQuadrat/stencil
4a5da0ff052ed4bd303274b33d23f4989e410654
[ "MIT" ]
null
null
null
test/karma/test-app/custom-elements-output-webpack/index.esm.js
TestOlliQuadrat/stencil
4a5da0ff052ed4bd303274b33d23f4989e410654
[ "MIT" ]
3
2021-07-29T15:53:22.000Z
2022-03-24T16:10:15.000Z
import { defineCustomElement } from '../../test-output/test-custom-elements/custom-element-root'; defineCustomElement();
30.5
97
0.762295
67403667bb47f9990fa21a4f49dfb61279c0352d
433
js
JavaScript
src/utils/colour.js
twinraven/pad
ee4dc38665a818a914b0e54ccf6b942f5b8e7002
[ "Apache-2.0" ]
null
null
null
src/utils/colour.js
twinraven/pad
ee4dc38665a818a914b0e54ccf6b942f5b8e7002
[ "Apache-2.0" ]
61
2018-04-24T15:51:00.000Z
2018-05-21T13:09:43.000Z
src/utils/colour.js
twinraven/pad
ee4dc38665a818a914b0e54ccf6b942f5b8e7002
[ "Apache-2.0" ]
null
null
null
import { DEFAULT_LIGHT_COLOR, DEFAULT_DARK_COLOR } from 'config.js'; export function getAutoTextColor(hex = DEFAULT_LIGHT_COLOR) { if (!/^#(?:[0-9a-f]{3}){1,2}$/gi.test(hex)) return DEFAULT_DARK_COLOR; let color = hex.replace('#', ''); if (color.length === 3) { color = color .split('') .map(char => char + char) .join(''); } return `0x${color}` > 0xffffff * 0.75 ? DEFAULT_DARK_COLOR : DEFAULT_LIGHT_COLOR; }
24.055556
71
0.637413
67448cfe7901fc847f94c0c6ea04d46dc7b1c395
1,608
js
JavaScript
index.js
SiwenFeng/whiteboard
dbe1457b7d6784f5bd33c593db9b2c6ad3f079fb
[ "BSD-2-Clause" ]
null
null
null
index.js
SiwenFeng/whiteboard
dbe1457b7d6784f5bd33c593db9b2c6ad3f079fb
[ "BSD-2-Clause" ]
3
2019-09-21T21:23:37.000Z
2019-09-24T01:19:28.000Z
index.js
SiwenFeng/whiteboard
dbe1457b7d6784f5bd33c593db9b2c6ad3f079fb
[ "BSD-2-Clause" ]
3
2019-09-18T04:08:22.000Z
2019-09-23T00:19:12.000Z
const fs = new Filer.FileSystem(); var str = ""; window.addEventListener('DOMContentLoaded', (event) => { fs.readFile('/note', 'utf8', function (err, data) { if (err !== null) { str = "Welcome to my note-taking app!" } else if (data !== null) { str = data; } document.querySelector('#note').innerHTML = str; showNote(); }) }); window.setInterval(() => { saveNote(); }, 2000); window.setInterval(() => { showNote(); }, 500); function wipeNote() { document.querySelector('#note').innerHTML = ""; document.getElementById("nwrite").value = ""; document.querySelector('#wcount').innerHTML = ""; } function showNote() { var count = document.getElementById("nwrite").value.trim(); count = count.replace(/&nbsp;+/g, " "); count = count.replace(/<[^>]*>/g, " "); count = count.replace(/\s+/g, " "); count = count.split(" "); var p = 0; for (var i = 0; i < count.length; i++) { if (count[i] == "") { ++p; } } count = count.length - p; document.getElementById("wcount").innerHTML = "Word Count: " + count; } function saveNote() { fs.writeFile('/note', document.getElementById("nwrite").value, function (err) { if (err) { throw err; } //if (err) { alert(err); } }); } function printNote() { let file = new File( [document.getElementById("nwrite").value], "notes.txt", { type: "text/plain;charset=utf-8" } ); saveAs(file); }
25.935484
84
0.516169
67457460a73fa0a87b816a78d90043e55878618e
8,672
js
JavaScript
assets/js/transacao.js
kryptonica/mercado-moedas
1def3538e803f389ce8d50afc3ef290d8310d2d4
[ "MIT" ]
2
2018-03-20T20:21:49.000Z
2018-06-24T01:44:57.000Z
assets/js/transacao.js
kryptonica/mercado-moedas
1def3538e803f389ce8d50afc3ef290d8310d2d4
[ "MIT" ]
50
2018-04-09T11:26:33.000Z
2018-06-03T20:35:53.000Z
assets/js/transacao.js
kryptonica/mercado-moedas
1def3538e803f389ce8d50afc3ef290d8310d2d4
[ "MIT" ]
1
2018-04-03T07:29:45.000Z
2018-04-03T07:29:45.000Z
$( function(){ checar_etapa(1); function timeline_etapa(width_vl) { if(width_vl!=0){ width_vl = width_vl + "%"; $(".timeline-horizontal").animate({ width: width_vl }, 1500); } } function ultima_msg() { var objDiv = $('.wrap_msg'); var h = objDiv.get(0).scrollHeight; objDiv.animate({ scrollTop: h }); } ultima_msg(); $("#btn-enviar-mensagem").click((event) => { event.preventDefault(); var form_data = $('#enviar-mensagem').serialize(); //Encode form elements for submission $.ajax({ url: $base_url+'index.php/Transacao_c/adicionar_mensagem/' + transacao_id, type: 'post', data: form_data, success: function (response) { $('#mensagem').val(''); ultima_msg(); }, error: function (err1, err2, err3) { console.log(err1); console.log(err2); console.log(err3); } }); }); $("#btn-confirmar-etapa").click((event) => { event.preventDefault(); var form_data = $('#enviar-mensagem').serialize(); //Encode form elements for submission $.ajax({ url: $base_url+'index.php/Transacao_c/adicionar_mensagem/' +transacao_id, type: 'post', data: form_data + '&confirmacao=' + 1, success: function (response) { ultima_msg(); }, error: function (err1, err2, err3) { console.log(err1); console.log(err2); console.log(err3); } }); }); $(".btn_aceitar_dado").click((event) => { confirmar(event); }); $(".btn_rejeitar_dado").click((event) => { rejeitar(event); }); function confirmar(event) { event.preventDefault(); $msg = $(event.currentTarget).parent().parent().parent().parent().attr('msg'); console.log($msg); $.ajax({ url: $base_url+'index.php/Transacao_c/confirmar_mensagem/' +transacao_id, type: 'post', data: { tipo:"confirmar", status: status_atual, msg_id: $msg, etapa: etapa_atual }, dataType: 'json', success: function (response) { //console.log("TEste:"); //console.log(response); checarMsg(1); checar_etapa(); ultima_msg(); }, error: function (err1, err2, err3) { console.log(err1); console.log(err2); console.log(err3); } }); } function rejeitar(event) { event.preventDefault(); $msg = $(event.currentTarget).parent().parent().parent().parent().attr('msg'); console.log('ID:'+$msg); $.ajax({ url: $base_url+'index.php/Transacao_c/confirmar_mensagem/' + transacao_id, type: 'post', data: { tipo:"rejeitar", status: status_atual, msg_id: $msg, etapa: etapa_atual }, dataType: 'json', success: function (response) { checarMsg(1); checar_etapa(); ultima_msg(); }, error: function (err1, err2, err3) { console.log(err1); console.log(err2); console.log(err3); } }); } function checar_etapa($forcado) { $.ajax({ type: "post", url: $base_url+'index.php/Transacao_c/checar_etapa', data: { id_transacao: transacao_id }, dataType: "json", success: function (response) { //console.log(response); $comprador_b = $comprador == $usuario_id; $vendedor_b = $vendedor == $usuario_id; etapa = response.transacao[0].etapa; etapa_atual = etapa; status = response.transacao[0].status; console.log("PQP"); if(etapa == 3){ $('#btn-confirmar-etapa').fadeOut(); $('#btn-finalizar').fadeIn(); } if(status != status_atual){ console.log("Status Checar"); checarMsg(1); } if(status != status_atual || $forcado){ status_atual = status; width = 0; if (etapa > 1) { width = 28 * (etapa - 1); } timeline_etapa(width); for (let index = 1; index <= etapa; index++) { if (index == etapa) $(".etapa" + index).addClass('info'); else { $(".etapa" + index).addClass('success'); $(".etapa" + index).removeClass('info'); } } $disabled = (etapa==1&&$vendedor_b)||(etapa==2&&$comprador_b)?true:false; console.log("Etapa: "+etapa+" id_user: "+$usuario_id+" vendedor: "+$vendedor+" comprador: "+$comprador+" vendedorb: "+$vendedor_b+" compradorb: "+$comprador_b+" disabled: "+$disabled); $('#btn-confirmar-etapa').attr('disabled', $disabled); } } }); } function checarMsg($forcado) { $id = $(".header_transacao").attr('id_t'); $.ajax({ type: "post", url: $base_url+'index.php/Transacao_c/checar', data: { id_transacao: $id }, dataType: "json", success: function (response) { mensagens = response.transacao.mensagens; mensagens_html = $('.panel_msg>.panel-body'); badges = $('.panel_msg>.timeline-badge'); if (mensagens_html.length != mensagens.length || $forcado) { mensagens_html.remove(); badges.remove(); mensagens.forEach((mensagem, index) => { $msg = $('<div class="panel-body" msg="' + mensagem.id + '">'); $badge = $('<div class="timeline-badge">'); if (mensagem.tipo == 0) { $badge.append($('<i class="fa fa-envelope">')); if (mensagem.usuario.id == response.id_usuario) { $msg.html( '<div class="col-sm-6 col-sm-offset-6"> <div class="panel panel-info"> <div class="panel-heading text-right"> <span class="raleway-bold">'+$lang.Voce_em+ mensagem.data_hora + '</span> </div> <div class="panel-body"> <p class="text-justify raleway-medium">' + mensagem.mensagem + '</p></div></div> </div>'); } else { $msg.html( '<div class="col-sm-6"><div class="panel panel-info"><div class="panel-heading"><span class="raleway-bold">' + mensagem.usuario.nome + $lang.em + mensagem.data_hora + '</span></div><div class="panel-body"> <p class="text-justify raleway-medium">' + mensagem.mensagem + '</p> </div> </div> </div>'); } } else { panel = ""; disabled = ""; //console.log("tipo:"+mensagem.tipo); if (mensagem.tipo == 2) { disabled = "disabled"; panel = "success"; $badge.addClass('badge-success'); $badge.append($('<i class="fa fa-check-circle">')); } else if (mensagem.tipo == -1) { disabled = "disabled"; panel = "danger"; $badge.addClass('badge-danger'); $badge.append($('<i class="fa fa-times-circle">')); } else { panel = "info"; $badge.append($('<i class="fa fa-receipt">')); } if (mensagem.usuario.id == response.id_usuario) { $msg.html('<div class="col-sm-6 col-sm-offset-6"> <div class="panel panel-' + panel + '"> <div class="panel-heading text-right"> <span class="raleway-bold">'+$lang.Voce_em + mensagem.data_hora + '</span> </div> <div class="panel-body"> <p class="text-justify raleway-medium">' + mensagem.mensagem + '</p></div> <div class="panel-footer"> <button disabled type="button" class="btn btn-danger"><span class="fa fa-times-circle"></span> '+$lang.Rejeitar+' </button> <button disabled type="button" class="btn btn-success"><span class="fa fa-check-circle"></span> '+$lang.Confirmar+' </button> </div> </div> </div>' ); } else { $msg.html('<div class="col-sm-6"><div class="panel panel-' + panel + '"><div class="panel-heading"><span class="raleway-bold">' + mensagem.usuario.nome + $lang.em + mensagem.data_hora + '</span></div><div class="panel-body"> <p class="text-justify raleway-medium">' + mensagem.mensagem + '</p> </div> <div class="panel-footer"> <button ' + disabled + ' type="button" class="btn_rejeitar_dado btn btn-danger "><span class="fa fa-times-circle"></span> '+$lang.Rejeitar+' </button> <button ' + disabled + ' type="button" class="btn_aceitar_dado btn btn-success"><span class="fa fa-check-circle"></span> '+$lang.Confirmar+' </button> </div> </div> </div>' ); } } $('.panel_msg').append($badge); $('.panel_msg').append($msg); }); ultima_msg(); $(".btn_aceitar_dado").click((event) => { confirmar(event); }); $(".btn_rejeitar_dado").click((event) => { rejeitar(event); }); } }, error: function (err1, err2, err3) { console.log(err1); console.log(err2); console.log(err3); } }); } setInterval(() => { checarMsg(); checar_etapa(); }, 500); });
24.848138
319
0.557426
6745c8eb2c54158b4b639ca6bee49b6dca78a481
654
js
JavaScript
src/features/machine/MachineSettings.js
texx00/sandify
8d7d589319d47cb58b78ce8c29762e0655ac7f17
[ "MIT" ]
136
2017-06-30T17:23:33.000Z
2022-03-24T07:56:33.000Z
src/features/machine/MachineSettings.js
texx00/sandify
8d7d589319d47cb58b78ce8c29762e0655ac7f17
[ "MIT" ]
171
2017-07-02T20:46:16.000Z
2022-03-14T19:31:02.000Z
src/features/machine/MachineSettings.js
texx00/sandify
8d7d589319d47cb58b78ce8c29762e0655ac7f17
[ "MIT" ]
18
2017-07-05T22:48:36.000Z
2022-03-23T18:12:25.000Z
import React, { Component } from 'react' import { connect } from 'react-redux' import { Accordion } from 'react-bootstrap' import RectSettings from './RectSettings' import PolarSettings from './PolarSettings' const mapStateToProps = (state, ownProps) => { return { rectangular: state.machine.rectangular, } } class MachineSettings extends Component { render() { return ( <div className="p-3"> <Accordion defaultActiveKey={this.props.rectangular ? 2 : 1}> <RectSettings /> <PolarSettings /> </Accordion> </div> ) } } export default connect(mapStateToProps, null)(MachineSettings)
22.551724
69
0.66055
67473139ccd3fd093b47e34a4bbe60102d460b99
231
js
JavaScript
migrations/2_deploy_contracts.js
maqzi/Chisel
f2cdf67dc4ef0496363cbde694842a30920c8807
[ "MIT" ]
null
null
null
migrations/2_deploy_contracts.js
maqzi/Chisel
f2cdf67dc4ef0496363cbde694842a30920c8807
[ "MIT" ]
null
null
null
migrations/2_deploy_contracts.js
maqzi/Chisel
f2cdf67dc4ef0496363cbde694842a30920c8807
[ "MIT" ]
null
null
null
var SimpleStorage = artifacts.require("./SimpleStorage.sol"); var Chisel = artifacts.require("./Chisel.sol"); module.exports = async function(deployer) { await deployer.deploy(SimpleStorage); await deployer.deploy(Chisel); };
28.875
61
0.748918
6747c134a8576b20b557b0e377bf18f8c6105ddd
1,751
js
JavaScript
rails5_api/public/docs-designer/test/spec/config.js
hadwinzhy/common_platform
5ac3ee7a00a3d235dbb1d8a5dbb68602fdde7e96
[ "MIT" ]
null
null
null
rails5_api/public/docs-designer/test/spec/config.js
hadwinzhy/common_platform
5ac3ee7a00a3d235dbb1d8a5dbb68602fdde7e96
[ "MIT" ]
null
null
null
rails5_api/public/docs-designer/test/spec/config.js
hadwinzhy/common_platform
5ac3ee7a00a3d235dbb1d8a5dbb68602fdde7e96
[ "MIT" ]
null
null
null
'use strict'; describe('RAML Config Service', function () { var config; beforeEach(module('raml')); beforeEach(inject(function ($injector) { config = $injector.get('config'); config.clear(); })); it('should obtain value from localStorage', function () { localStorage['config.a'] = '5'; localStorage['config.b'] = '7'; config.get('a').should.be.equal('5'); config.get('b').should.be.equal('7'); should.not.exist(config.get('c')); }); it('should retrieve a previously stored value correctly', function () { config.set('a', 19); config.get('a').should.be.equal('19'); }); it('should use get default value when no value associated', function () { config.get('x', 99).should.be.equal(99); }); it('should ignore default when value previously set', function () { config.set('y', 9); config.get('y', 18).should.be.equal('9'); }); it('should correctly persist the configuration to localStorage', function () { should.not.exist(localStorage['config.t']); should.not.exist(localStorage['config.8']); config.set('t', '87'); config.set('8', '123'); localStorage['config.t'].should.be.equal('87'); localStorage['config.8'].should.be.equal('123'); }); it('should properly remove key', function () { config.set('a', 'a'); config.get('a').should.be.equal('a'); config.remove('a'); should.not.exist(config.get('a')); }); it('should properly clear itself', function () { var keys = ['a', 'b', 'c']; keys.forEach(function (key) { config.set(key, key); config.get(key).should.be.equal(key); }); config.clear(); keys.forEach(function (key) { should.not.exist(config.get(key)); }); }); });
24.661972
80
0.599657
6748495970c66ed343539a28e5f12a3755ea83fc
1,736
js
JavaScript
gatsby-node.js
harshnagoratela/digitalstride
78bbbe2c22098a86bf2caf9130945fc9bc888a24
[ "RSA-MD" ]
null
null
null
gatsby-node.js
harshnagoratela/digitalstride
78bbbe2c22098a86bf2caf9130945fc9bc888a24
[ "RSA-MD" ]
null
null
null
gatsby-node.js
harshnagoratela/digitalstride
78bbbe2c22098a86bf2caf9130945fc9bc888a24
[ "RSA-MD" ]
null
null
null
const path = require('path') exports.createSchemaCustomization = ({ actions }) => { const { createTypes } = actions const typeDefs = ` type siteSearchIndex1 implements Node { index: String } ` createTypes(typeDefs) } exports.createPages = ({ graphql, actions }) => { const { createPage } = actions return new Promise((resolve, reject) => { const pageTemplate = path.resolve('./src/templates/page-template.js') const serviceTemplate = path.resolve('./src/templates/service-template.js') resolve( graphql( ` { allContentfulPages { edges { node { title slug } } } allContentfulServices { edges { node { title slug } } } } ` ).then(result => { if (result.errors) { console.log(result.errors) reject(result.errors) } const pages = result.data.allContentfulPages.edges pages.forEach((page, index) => { createPage({ path: `/${page.node.slug}/`, component: pageTemplate, context: { slug: page.node.slug }, }) }) const services = result.data.allContentfulServices.edges services.forEach((service, index) => { createPage({ path: `/service/${service.node.slug}/`, component: serviceTemplate, context: { slug: service.node.slug }, }) }) }) ) }) }
24.111111
79
0.46371
67487f4582dc2f44879c8c927d619b8453e3ec23
1,601
js
JavaScript
workspaces/ui/src/contexts/ColorContext.js
matthewhudson/optic
fbe46fb9e6f5ae411bd7ad0e637420dea43110fa
[ "MIT" ]
1
2020-04-12T19:12:44.000Z
2020-04-12T19:12:44.000Z
workspaces/ui/src/contexts/ColorContext.js
matthewhudson/optic
fbe46fb9e6f5ae411bd7ad0e637420dea43110fa
[ "MIT" ]
1
2020-04-17T23:36:37.000Z
2020-04-17T23:36:37.000Z
workspaces/ui/src/contexts/ColorContext.js
matthewhudson/optic
fbe46fb9e6f5ae411bd7ad0e637420dea43110fa
[ "MIT" ]
null
null
null
import React from 'react'; import {GenericContextFactory} from './GenericContextFactory'; export const ColorTags = { ADDED: 'added', CHANGED: 'changed', } const { Context: ColoredIdsContext, withContext: withColoredIdsContext } = GenericContextFactory(null) class ColoredIdsStore extends React.Component { render() { const context = { coloredIds: this.props.ids || [], coloredTag: this.props.tag || ColorTags.ADDED } return ( <ColoredIdsContext.Provider value={context}> {this.props.children} </ColoredIdsContext.Provider> ) } } export { ColoredIdsStore, withColoredIdsContext } //Shared Styles export const AddedGreen = '#17c8a3' export const AddedGreenBackground = 'rgba(23,200,163,0.1)' export const ChangedYellow = '#c8b768' export const ChangedYellowBackground = 'rgba(200,183,104,0.1)' export const RemovedRed = '#c86363' export const RemovedRedBackground = 'rgba(200,99,99,0.1)' export const UpdatedBlue = '#2b7bd1' export const UpdatedBlueBackground = 'rgba(43,123,209,0.11)' export const ChangedYellowBright = '#f2dd7e' export const AddedStyle = (paddingLeft = 15, paddingTop = 9, paddingBottom = 9) => ({ borderLeft: `3px solid ${AddedGreen}`, backgroundColor: AddedGreenBackground, paddingLeft, paddingTop, paddingBottom }) export const ChangedStyle = (paddingLeft = 15, paddingTop = 9, paddingBottom = 9) => ({ borderLeft: `3px solid ${ChangedYellow}`, backgroundColor: ChangedYellowBackground, paddingLeft, paddingTop, paddingBottom })
25.015625
87
0.693941
6748c2ebb38e78e1798f35c415ad02cada66c91f
1,905
js
JavaScript
src/pages/portfolio/pages/fox-ccxp.js
letgodoy/duee-site
82a3932c80347e379a43f9cd18c390a95d7461ac
[ "MIT" ]
null
null
null
src/pages/portfolio/pages/fox-ccxp.js
letgodoy/duee-site
82a3932c80347e379a43f9cd18c390a95d7461ac
[ "MIT" ]
14
2020-09-10T14:55:36.000Z
2022-02-28T02:29:39.000Z
src/pages/portfolio/pages/fox-ccxp.js
letgodoy/duee-site
82a3932c80347e379a43f9cd18c390a95d7461ac
[ "MIT" ]
1
2020-11-18T03:09:56.000Z
2020-11-18T03:09:56.000Z
import React from 'react' import './default.scss' export default class FoxCcxp extends React.Component { constructor(props) { super(props) } componentDidMount() { document.querySelector(".loading").style.visibility = 'hidden' } render() { return <article className="cases row col-xs-12" style={{ backgroundColor: "white" }}> <div className="col-12 title"> <h2 style={{ color: 'black' }}>FOX – CCXP 2014</h2> {/* <img src="https://portfolio.duee.com.br/wp-content/uploads/2018/09/KV-Starbucks-NITRODRAFT_V32.png" alt="" /> */} </div> <div className="row conteudo content"> <div className="col-xs-12"> <img src="https://portfolio.duee.com.br/wp-content/uploads/2016/02/fox1-1.jpg" alt="" /> <img src="https://portfolio.duee.com.br/wp-content/uploads/2016/02/fox2.jpg" alt="" /> <img src="https://portfolio.duee.com.br/wp-content/uploads/2016/02/fox3.jpg" alt="" /> <img src="https://portfolio.duee.com.br/wp-content/uploads/2016/02/fox4.jpg" alt="" /> </div> </div> <div className="row content describes" style={{ color: 'black' }}> <div className="col-xs-12 col-md-8 col-sm-6"> <p><b>SOBRE O PROJETO</b></p> <p>Desenvolvemos ambientes incríveis para a Fox, durante a Comic Con Experience 2014, com estandes, promotores fantasiados de personagens, ativações de filmes e muito mais.</p> </div> <div className="col-xs-12 col-md-4 col-sm-6"> <p><b>DETALHES DO PROJETO</b></p> <p><b>CLIENTE</b> Fox Film do Brasil</p> <p><b>DATA</b> 2014</p> </div> </div> </article> } }
45.357143
196
0.537008
67493881757cc766381243e8b0a81472bbe89c1d
1,681
js
JavaScript
ifitwala_ed/admission/doctype/student_applicant/student_applicant.js
mohsinalimat/ifitwala_ed
8927695ed9dee36e56571c442ebbe6e6431c7d46
[ "MIT" ]
13
2020-09-02T10:27:57.000Z
2022-03-11T15:28:46.000Z
ifitwala_ed/admission/doctype/student_applicant/student_applicant.js
mohsinalimat/ifitwala_ed
8927695ed9dee36e56571c442ebbe6e6431c7d46
[ "MIT" ]
43
2020-09-02T07:00:42.000Z
2021-07-05T13:22:58.000Z
ifitwala_ed/admission/doctype/student_applicant/student_applicant.js
mohsinalimat/ifitwala_ed
8927695ed9dee36e56571c442ebbe6e6431c7d46
[ "MIT" ]
6
2020-10-19T01:02:18.000Z
2022-03-11T15:28:47.000Z
// Copyright (c) 2020, ifitwala and contributors // For license information, please see license.txt frappe.ui.form.on('Student Applicant', { setup: function(frm) { frm.add_fetch('guardian', 'guardian_full_name', 'guardian_name'); }, refresh: function(frm) { if (frm.doc.application_status === 'Applied' && frm.doc.status === 1) { frm.add_custom_button(__('Approve'), function() { frm.set_value('application_status', 'Approved'); frm.save_or_update(); }, 'Actions'); frm.add_custom_button(__('Reject'), function() { frm.set_value('application_status', 'Rejected'); frm.save_or_update(); }, 'Actions'); } if (frm.doc.application_status === 'Approved' && frm.doc.status === 1) { frm.add_custom_button(__('Enroll'), function() { frm.events.enroll(frm) }).addClass('btn-primary'); frm.add_custom_button(__('Reject'), function() { frm.set_value('application_status', 'Rejected'); frm.save_or_update(); }, 'Actions'); } frappe.realtime.on("enroll_student_progress", function(data) { if(data.progress) { frappe.hide_msgprint(true); frappe.show_progress(__("Enrolling student"), data.progress[0],data.progress[1]); } }); }, enroll: function(frm) { frappe.model.open_mapped_doc({ method: "ifitwala_ed.ifitwala_ed.api.enroll_student", frm: frm }) } }); frappe.ui.form.on('Student Sibling', { setup: function(frm) { frm.add_fetch("student", "title", "sibling_name"); frm.add_fetch("student", "gender", "sibling_gender"); frm.add_fetch("student", "date_of_birth", "sibling_date_of_birth"); } });
30.017857
89
0.635931
6749c292571777dd9e9f74a7d0ce312db1bf0995
1,263
js
JavaScript
src/router/index.js
mvxt/vendo
5b0c399cc093c93155ca3247cba3a2c2e31fb0b2
[ "MIT" ]
null
null
null
src/router/index.js
mvxt/vendo
5b0c399cc093c93155ca3247cba3a2c2e31fb0b2
[ "MIT" ]
2
2019-09-03T18:14:51.000Z
2019-09-03T18:19:09.000Z
src/router/index.js
mvxt/vendo
5b0c399cc093c93155ca3247cba3a2c2e31fb0b2
[ "MIT" ]
null
null
null
import Vue from 'vue' import Router from 'vue-router' import Home from '@/pages/Home' import Cart from '@/pages/Cart' import Details from '@/pages/Details' import Index from '@/pages/admin/Index' import New from '@/pages/admin/New' import Products from '@/pages/admin/Products' import Edit from '@/pages/admin/Edit' Vue.use(Router) const router = new Router({ created () { console.log(this.$route.params.id) }, mode: 'history', linkActiveClass: 'is-active', scrollBehavior: (to, from, savedPosition) => ({ if (savedPosition) { return savedPosition } }), routes: [ { path: '/', component: Home }, { path: '/admin', component: Index, children: [ { path: 'edit/:id', name: 'Edit', props: true, component: Edit }, { path: 'new', name: 'New', component: New }, { path: '', name: 'Products', component: Products } ] }, { path: '/cart', name: 'Cart', component: Cart }, { path: '/details/:id', name: 'Details', props: true, component: Details } ] }) export default router
18.304348
49
0.517023
674a8a603bc540b3e9c49b47d77d6e25095241b3
3,703
js
JavaScript
js/screens/SettingsScreen.js
discourse/DiscourseMobile
9b25564847791a47813594078fdaa345e5e16321
[ "MIT" ]
199
2016-09-08T03:44:56.000Z
2022-03-19T04:18:30.000Z
js/screens/SettingsScreen.js
discourse/DiscourseMobile
9b25564847791a47813594078fdaa345e5e16321
[ "MIT" ]
50
2016-09-07T23:44:14.000Z
2022-02-16T16:50:25.000Z
js/screens/SettingsScreen.js
discourse/DiscourseMobile
9b25564847791a47813594078fdaa345e5e16321
[ "MIT" ]
67
2016-09-19T10:18:45.000Z
2022-02-16T09:42:47.000Z
/* @flow */ 'use strict'; import React from 'react'; import AsyncStorage from '@react-native-community/async-storage'; import { Platform, SafeAreaView, StyleSheet, Switch, Text, View, } from 'react-native'; import Components from './NotificationsScreenComponents'; import {ThemeContext} from '../ThemeContext'; import i18n from 'i18n-js'; class SettingsScreen extends React.Component { constructor(props) { super(props); this.state = { progress: 0, androidCustomTabs: false, }; AsyncStorage.getItem('@Discourse.androidCustomTabs').then(val => { this.setState({ androidCustomTabs: val ? true : false, }); }); this.toggleAndroidCustomTabs = this.toggleAndroidCustomTabs.bind(this); this.toggleDarkMode = this.toggleDarkMode.bind(this); } render() { const theme = this.context; return ( <SafeAreaView style={{flex: 1, backgroundColor: theme.background}} forceInset={{top: 'never', bottom: 'always'}}> <Components.NavigationBar onDidPressRightButton={() => this._onDidPressRightButton()} progress={this.state.progress} title={i18n.t('settings')} /> {this._renderSettings()} </SafeAreaView> ); } toggleAndroidCustomTabs() { AsyncStorage.getItem('@Discourse.androidCustomTabs').then(val => { if (!val) { AsyncStorage.setItem('@Discourse.androidCustomTabs', 'true'); this.setState({androidCustomTabs: true}); } else { AsyncStorage.removeItem('@Discourse.androidCustomTabs'); this.setState({androidCustomTabs: false}); } }); } toggleDarkMode() { const theme = this.context; const newTheme = theme.background === '#FFFFFF' ? 'dark' : 'light'; AsyncStorage.setItem('@Discourse.androidLegacyTheme', newTheme).done(() => { this.props.screenProps.toggleTheme(newTheme); }); } _renderSettings() { const theme = this.context; const isDark = !!(theme.background !== '#FFFFFF'); return ( <View style={styles.container}> <View style={styles.settingItem}> <Text style={{...styles.text, color: theme.grayTitle}}> {i18n.t('browser_toggle_label')} </Text> <Switch onValueChange={this.toggleAndroidCustomTabs} value={this.state.androidCustomTabs} /> <Text style={{...styles.desc, color: theme.grayTitle}}> {i18n.t('browser_toggle_description')} </Text> </View> {Platform.OS === 'android' && Platform.Version < 29 && ( <View style={styles.settingItem}> <Text style={{...styles.text, color: theme.grayTitle}}> {i18n.t('switch_dark')} </Text> <Switch onValueChange={this.toggleDarkMode} value={isDark} /> <Text style={{...styles.desc, color: theme.grayTitle}}> {i18n.t('browser_toggle_description')} </Text> </View> )} </View> ); } _onDidPressRightButton() { this.props.navigation.goBack(); } } SettingsScreen.contextType = ThemeContext; const styles = StyleSheet.create({ container: { alignItems: 'center', backgroundColor: 'transparent', justifyContent: 'center', flex: 5, }, settingItem: { alignItems: 'center', backgroundColor: 'transparent', justifyContent: 'center', marginBottom: 20, }, text: { fontSize: 20, padding: 12, paddingBottom: 24, textAlign: 'center', }, desc: { fontSize: 16, padding: 12, paddingTop: 24, textAlign: 'center', }, }); export default SettingsScreen;
25.715278
80
0.604375
674a9e86f37ecad07d50445386024ef62ddc7d62
820
js
JavaScript
docs/iot/api/5.0/tizen-iot-headed/group__Ecore__Con__Group.js
hyundukkim/tizen-docs
e98bafca26a3626010416df827141f009b62cf8c
[ "CC-BY-3.0", "BSD-3-Clause" ]
1
2020-09-11T00:54:22.000Z
2020-09-11T00:54:22.000Z
docs/iot/api/5.0/tizen-iot-headed/group__Ecore__Con__Group.js
hyundukkim/tizen-docs
e98bafca26a3626010416df827141f009b62cf8c
[ "CC-BY-3.0", "BSD-3-Clause" ]
2
2020-09-30T12:16:39.000Z
2020-10-26T09:49:45.000Z
docs/iot/api/5.0/tizen-iot-headed/group__Ecore__Con__Group.js
hyundukkim/tizen-docs
e98bafca26a3626010416df827141f009b62cf8c
[ "CC-BY-3.0", "BSD-3-Clause" ]
1
2022-03-15T03:51:14.000Z
2022-03-15T03:51:14.000Z
var group__Ecore__Con__Group = [ [ "Ecore Connection Buffering", "group__Ecore__Con__Buffer.html", null ], [ "Ecore Connection Client Functions", "group__Ecore__Con__Client__Group.html", null ], [ "Ecore Connection Events Functions", "group__Ecore__Con__Events__Group.html", null ], [ "Ecore Connection Library Functions", "group__Ecore__Con__Lib__Group.html", null ], [ "Ecore Connection SOCKS functions", "group__Ecore__Con__Socks__Group.html", null ], [ "Ecore Connection SSL Functions", "group__Ecore__Con__SSL__Group.html", null ], [ "Ecore Connection Server Functions", "group__Ecore__Con__Server__Group.html", null ], [ "Ecore URL Connection Functions", "group__Ecore__Con__Url__Group.html", null ], [ "Eet connection functions", "group__Ecore__Con__Eet__Group.html", null ] ];
68.333333
91
0.752439
674aaf1709ef6259b2b24a180a90a9ba2ffe62b5
19,290
js
JavaScript
test/validator.spec.js
mauricedoepke/fastest-validator
58cf5811ec18239c2d43aed9e8e9030498e836ca
[ "MIT" ]
null
null
null
test/validator.spec.js
mauricedoepke/fastest-validator
58cf5811ec18239c2d43aed9e8e9030498e836ca
[ "MIT" ]
null
null
null
test/validator.spec.js
mauricedoepke/fastest-validator
58cf5811ec18239c2d43aed9e8e9030498e836ca
[ "MIT" ]
null
null
null
"use strict"; const Validator = require("../lib/validator"); describe("Test constructor", () => { it("should create instance", () => { let v = new Validator(); expect(v).toBeDefined(); expect(v.messages).toBeDefined(); expect(v.compile).toBeInstanceOf(Function); expect(v.validate).toBeInstanceOf(Function); expect(v.add).toBeInstanceOf(Function); expect(Object.keys(v.rules).length).toBe(13); }); it("should create instance with custom messages", () => { let v = new Validator({ messages: { numberMin: "Custom validation error message" } }); expect(v).toBeDefined(); expect(v.messages).toBeDefined(); expect(v.messages.numberMin).toBe("Custom validation error message"); expect(v.messages.numberMax).toBe("The '{field}' field must be less than or equal to {expected}!"); }); }); describe("Test validate", () => { const v = new Validator(); const compiledFn = jest.fn(() => true); v.compile = jest.fn(() => compiledFn); const schema = { name: { type: "string" } }; const obj = { name: "John" }; it("should call compile & compiled check function", () => { let res = v.validate(obj, schema); expect(res).toBe(true); expect(v.compile).toHaveBeenCalledTimes(1); expect(v.compile).toHaveBeenCalledWith(schema); expect(compiledFn).toHaveBeenCalledTimes(1); expect(compiledFn).toHaveBeenCalledWith(obj); }); }); describe("Test add", () => { const v = new Validator(); const validFn = jest.fn(() => true); it("should not contain the new validator", () => { expect(v.rules.myValidator).toBeUndefined(); }); it("should contain the new validator", () => { v.add("myValidator", validFn); expect(v.rules.myValidator).toBeDefined(); }); it("should call the new validator", () => { const schema = { a: { type: "myValidator" } }; const obj = { a: 5 }; v.validate(obj, schema); expect(validFn).toHaveBeenCalledTimes(1); expect(validFn).toHaveBeenCalledWith(5, schema.a, "a", obj); }); }); describe("Test resolveMessage", () => { const v = new Validator(); it("should resolve variables in message string", () => { let res = v.resolveMessage({ type: "stringLength", field: "age", expected: 3, actual: 6 }); expect(res).toBe("The 'age' field length must be 3 characters long!"); }); it("should resolve 0 value in message string", () => { let res = v.resolveMessage({ type: "numberNotEqual", field: "b", expected: 0, actual: 0 }); expect(res).toBe("The 'b' field can't be equal with 0!"); }); it("should resolve more variables in message string", () => { v.messages.custom = "Field {field} and again {field}. Expected: {expected}, actual: {actual}."; let res = v.resolveMessage({ type: "custom", field: "country", expected: "London", actual: 350 }); expect(res).toBe("Field country and again country. Expected: London, actual: 350."); }); }); describe("Test compile (unit test)", () => { const v = new Validator(); v._processRule = jest.fn(); it("should call processRule", () => { v.compile({ id: { type: "number" }, name: { type: "string", min: 5}, status: "boolean" }); expect(v._processRule).toHaveBeenCalledTimes(3); expect(v._processRule).toHaveBeenCalledWith({"type": "number"}, "id", false); expect(v._processRule).toHaveBeenCalledWith({"type": "string", "min": 5}, "name", false); expect(v._processRule).toHaveBeenCalledWith("boolean", "status", false); }); it("should call processRule for root-level array", () => { v._processRule.mockClear(); v.compile([ { type: "array", items: "number" }, { type: "string", min: 2 } ]); expect(v._processRule).toHaveBeenCalledTimes(2); expect(v._processRule).toHaveBeenCalledWith({"type": "array", items: "number"}, null, false); expect(v._processRule).toHaveBeenCalledWith({"type": "string", min: 2 }, null, false); }); it("should throw error is the schema is null", () => { expect(() => { v.compile(); }).toThrowError("Invalid schema!"); expect(() => { v.compile(null); }).toThrowError("Invalid schema!"); expect(() => { v.compile("Nothing"); }).toThrowError("Invalid schema!"); expect(() => { v.compile(1); }).toThrowError("Invalid schema!"); }); it("should throw error is the schema array element count is not 1", () => { expect(() => { v.compile([]); }).toThrowError(); expect(() => { v.compile([], []); }).toThrowError(); }); }); describe("Test _processRule", () => { const v = new Validator(); v.compile = jest.fn(); v._checkWrapper = jest.fn(); it("should return array of rules", () => { let res = v._processRule({ type: "number", positive: true }, "id", false); expect(res).toBeInstanceOf(Array); expect(res.length).toBe(1); expect(res[0].fn).toBeInstanceOf(Function); expect(res[0].type).toBe("number"); expect(res[0].name).toBe("id"); expect(res[0].schema).toEqual({ type: "number", positive: true }); expect(res[0].iterate).toBe(false); }); it("should convert shorthand definition", () => { let res = v._processRule("string", "name", false); expect(res).toBeInstanceOf(Array); expect(res.length).toBe(1); expect(res[0].fn).toBeInstanceOf(Function); expect(res[0].type).toBe("string"); expect(res[0].name).toBe("name"); expect(res[0].schema).toEqual({ type: "string" }); expect(res[0].iterate).toBe(false); }); it("should throw error if the type is invalid", () => { expect(() => { v._processRule({ type: "unknow" }, "id", false); }).toThrowError("Invalid 'unknow' type in validator schema!"); }); it("should call compile if type is object", () => { let res = v._processRule({ type: "object", props: { id: "number" } }, "item", false); expect(res).toBeInstanceOf(Array); expect(res.length).toBe(2); expect(res[0].fn).toBeInstanceOf(Function); expect(res[0].type).toBe("object"); expect(res[0].name).toBe("item"); expect(res[0].iterate).toBe(false); //expect(res[1].fn).toBeInstanceOf(Function); expect(res[1].type).toBe("object"); expect(res[1].name).toBe("item"); expect(res[1].iterate).toBe(false); expect(v.compile).toHaveBeenCalledTimes(1); expect(v.compile).toHaveBeenCalledWith({id: "number"}); }); it("should call checkWrapper & processRule if type is Array", () => { let res = v._processRule({ type: "array", items: "number" }, "list", false); expect(res).toBeInstanceOf(Array); expect(res.length).toBe(2); expect(res[0].fn).toBeInstanceOf(Function); expect(res[0].type).toBe("array"); expect(res[0].name).toBe("list"); expect(res[0].iterate).toBe(false); //expect(res[1].fn).toBeInstanceOf(Function); expect(res[1].type).toBe("array"); expect(res[1].name).toBe("list"); expect(res[1].iterate).toBe(true); expect(v._checkWrapper).toHaveBeenCalledTimes(1); expect(v._checkWrapper).toHaveBeenCalledWith([{"fn": expect.any(Function), "iterate": false, "name": null, "schema": {"type": "number"}, "type": "number"}]); }); }); describe("Test compile (integration test)", () => { describe("Test check generator with good obj", () => { const v = new Validator(); v.rules.string = jest.fn(() => true); v.rules.number = jest.fn(() => true); const schema = { id: { type: "number" }, name: { type: "string" } }; let check; it("should give a check function", () => { check = v.compile(schema); expect(check).toBeInstanceOf(Function); }); it("should call rules validators", () => { const obj = { id: 5, name: "John" }; const res = check(obj); expect(res).toBe(true); expect(v.rules.number).toHaveBeenCalledTimes(1); expect(v.rules.number).toHaveBeenCalledWith(5, schema.id, "id", obj); expect(v.rules.string).toHaveBeenCalledTimes(1); expect(v.rules.string).toHaveBeenCalledWith("John", schema.name, "name", obj); }); }); describe("Test check generator with shorthand schema", () => { const v = new Validator(); v.rules.string = jest.fn(() => true); v.rules.number = jest.fn(() => true); const schema = { id: "number", name: "string" }; let check; it("should give a check function", () => { check = v.compile(schema); expect(check).toBeInstanceOf(Function); }); it("should call rules validators", () => { const obj = { id: 5, name: "John" }; let res = check(obj); expect(res).toBe(true); expect(v.rules.number).toHaveBeenCalledTimes(1); expect(v.rules.number).toHaveBeenCalledWith(5, { type: "number" }, "id", obj); expect(v.rules.string).toHaveBeenCalledTimes(1); expect(v.rules.string).toHaveBeenCalledWith("John", { type: "string" }, "name", obj); }); }); describe("Test check generator with wrong obj", () => { const v = new Validator(); const schema = { id: { type: "number" }, name: { type: "string", min: 5, optional: true }, password: { type: "forbidden" } }; let check = v.compile(schema); it("should give back one errors", () => { let res = check({id: 5, name: "John" }); expect(res).toBeInstanceOf(Array); expect(res.length).toBe(1); expect(res[0]).toEqual({ type: "stringMin", field: "name", message: "The 'name' field length must be larger than or equal to 5 characters long!", expected: 5, actual: 4 }); }); it("should give back more errors", () => { let res = check({ password: "123456" }); expect(res).toBeInstanceOf(Array); expect(res.length).toBe(2); expect(res[0].type).toBe("required"); expect(res[1].type).toBe("forbidden"); }); }); }); describe("Test nested schema", () => { const v = new Validator(); let schema = { id: { type: "number", positive: true }, name: { type: "string" }, address: { type: "object", props: { country: { type: "string" }, city: { type: "string" }, zip: { type: "number", min: 100, max: 99999} }} }; let check = v.compile(schema); it("should give true if obj is valid", () => { let obj = { id: 3, name: "John", address: { country: "Germany", city: "Munchen", zip: 4455 } }; let res = check(obj); expect(res).toBe(true); }); it("should give errors (flatten)", () => { let obj = { id: 0, name: "John", address: { city: "Munchen", zip: 55 } }; let res = check(obj); expect(res.length).toBe(3); expect(res[0].type).toBe("numberPositive"); expect(res[0].field).toBe("id"); expect(res[1].type).toBe("required"); expect(res[1].field).toBe("address.country"); expect(res[2].type).toBe("numberMin"); expect(res[2].field).toBe("address.zip"); }); }); describe("Test 3 level nested schema", () => { const v = new Validator(); let schema = { a: { type: "object", props: { b: { type: "object", props: { c: { type: "string", min: 5} }} }} }; let check = v.compile(schema); it("should give true if obj is valid", () => { let obj = { a: { b: { c: "John Doe" } } }; let res = check(obj); expect(res).toBe(true); }); it("should give errors (flatten)", () => { let obj = { a: { b: { c: "John" } } }; let res = check(obj); expect(res.length).toBe(1); expect(res[0].type).toBe("stringMin"); expect(res[0].field).toBe("a.b.c"); expect(res[0].message).toBe("The 'a.b.c' field length must be larger than or equal to 5 characters long!"); }); }); describe("Test nested array", () => { const v = new Validator(); let schema = { arr1: { type: "array", items: { type: "array", empty: false, items: { type: "number" } }} }; let check = v.compile(schema); it("should give true if obj is valid", () => { let obj = { arr1: [ [ 5, 10 ], [ 1, 2 ] ] }; let res = check(obj); expect(res).toBe(true); }); it("should give error 'not a number'", () => { let obj = { arr1: [ [ 5, 10 ], [ "1", 2 ] ] }; let res = check(obj); expect(res.length).toBe(1); expect(res[0].type).toBe("number"); expect(res[0].field).toBe("arr1[1][0]"); }); it("should give error 'empty array'", () => { let obj = { arr1: [ [ ], [ 1, 2 ] ] }; let res = check(obj); expect(res.length).toBe(1); expect(res[0].type).toBe("arrayEmpty"); expect(res[0].field).toBe("arr1[0]"); }); }); describe("Test 3-level array", () => { const v = new Validator(); let schema = { arr1: { type: "array", items: { type: "array", items: { type: "array", items: "string" } }} }; let check = v.compile(schema); it("should give true if obj is valid", () => { let obj = { arr1: [ [ [ "apple", "peach" ], [ "pineapple", "plum" ] ], [ [ "orange", "lemon", "lime"] ] ] }; let res = check(obj); expect(res).toBe(true); }); it("should give error 'not a string'", () => { let obj = { arr1: [ [ [ "apple", "peach" ], [ "pineapple", "plum" ] ], [ [ "orange", {}, "lime"] ] ] }; let res = check(obj); expect(res.length).toBe(1); expect(res[0].type).toBe("string"); expect(res[0].field).toBe("arr1[1][0][1]"); }); }); describe("Test multiple rules", () => { const v = new Validator(); let schema = { value: [ { type: "string", min: 3, max: 255 }, { type: "boolean" } ] }; let check = v.compile(schema); let schemaOptional = { a: [ { type: 'number', optional: true }, { type: 'string', optional: true }, ] }; let checkOptional = v.compile(schema); it("should give true if value is string", () => { let obj = { value: "John" }; let res = check(obj); expect(res).toBe(true); }); it("should give true if value is boolean", () => { let obj = { value: true }; let res = check(obj); expect(res).toBe(true); obj = { value: false }; res = check(obj); expect(res).toBe(true); }); it("should give error if the value is not string and not boolean", () => { let obj = { value: 100 }; let res = check(obj); expect(res.length).toBe(2); expect(res[0].type).toBe("string"); expect(res[0].field).toBe("value"); expect(res[1].type).toBe("boolean"); expect(res[1].field).toBe("value"); }); it("should give error if the value is a too short string", () => { let obj = { value: "Al" }; let res = check(obj); expect(res.length).toBe(2); expect(res[0].type).toBe("stringMin"); expect(res[0].field).toBe("value"); expect(res[1].type).toBe("boolean"); expect(res[1].field).toBe("value"); }); it("should work with optional", () => { let obj = {}; let res = checkOptional(obj); expect(res).toBe(true); }); }); describe("Test multiple rules with objects", () => { const v = new Validator(); let schema = { list: [ { type: "object", props: { name: {type: "string"}, age: {type: "number"}, } }, { type: "object", props: { country: {type: "string"}, code: {type: "string"}, } } ] }; let check = v.compile(schema); it("should give true if first object is given", () => { let obj = { list: { name: "Joe", age: 34 } }; let res = check(obj); expect(res).toBe(true); }); it("should give true if second object is given", () => { let obj = { list: { country: "germany", code: "de" }}; let res = check(obj); expect(res).toBe(true); }); it("should give error if the object is broken", () => { let obj = { list: { name: "Average", age: "Joe" } }; let res = check(obj); expect(res).toBeInstanceOf(Array); expect(res.length).toBe(3); expect(res[0].type).toBe("number"); expect(res[0].field).toBe("list.age"); expect(res[1].type).toBe("required"); expect(res[1].field).toBe("list.country"); }); it("should give error if the object is only partly given", () => { let obj = { list: {} }; let res = check(obj); expect(res).toBeInstanceOf(Array); expect(res.length).toBe(4); expect(res[0].type).toBe("required"); expect(res[0].field).toBe("list.name"); expect(res[1].type).toBe("required"); expect(res[1].field).toBe("list.age"); }); }); describe("Test multiple rules with objects within array", () => { const v = new Validator(); let schema = { list: { type: "array", items: [ { type: "object", props: { name: {type: "string"}, age: {type: "number"}, } }, { type: "object", props: { country: {type: "string"}, code: {type: "string"}, } } ] } }; let check = v.compile(schema); it("should give true if one valid object is given", () => { let obj = { list: [ { name: "Joe", age: 34 } ]}; let res = check(obj); expect(res).toBe(true); let obj2 = { list: [ { country: "germany", code: "de" } ]}; let res2 = check(obj2); expect(res2).toBe(true); }); it("should give true if three valid objects given", () => { let obj = { list: [ { name: "Joe", age: 34 }, { country: "germany", code: "de" }, { country: "hungary", code: "hu" } ]}; let res = check(obj); expect(res).toBe(true); }); it("should give error if one object is broken", () => { let obj = { list: [ { name: "Joe", age: 34 }, { country: "germany", }, { country: "hungary", code: "hu" } ]}; let res = check(obj); expect(res).toBeInstanceOf(Array); expect(res.length).toBe(3); expect(res[0].type).toBe("required"); expect(res[0].field).toBe("list[1].name"); expect(res[1].type).toBe("required"); expect(res[1].field).toBe("list[1].age"); }); it("should give error if one object is empty", () => { let obj = { list: [ { name: "Joe", age: 34 }, { country: "hungary", code: "hu" }, { } ]}; let res = check(obj); expect(res).toBeInstanceOf(Array); expect(res.length).toBe(4); expect(res[0].type).toBe("required"); expect(res[0].field).toBe("list[2].name"); expect(res[1].type).toBe("required"); expect(res[1].field).toBe("list[2].age"); }); }); describe("Test multiple rules with arrays", () => { const v = new Validator(); let schema = { list: [ { type: "array", items: "string" }, { type: "array", items: "number" } ] }; let check = v.compile(schema); it("should give true if first array is given", () => { let obj = { list: ["hello", "there", "this", "is", "a", "test"] }; let res = check(obj); expect(res).toBe(true); }); it("should give true if second array is given", () => { let obj = { list: [1, 3, 3, 7] }; let res = check(obj); expect(res).toBe(true); }); it("should give error if the array is broken", () => { let obj = { list: ["hello", 3] }; let res = check(obj); expect(res).toBeInstanceOf(Array); expect(res.length).toBe(2); expect(res[0].type).toBe("string"); expect(res[0].field).toBe("list[1]"); expect(res[1].type).toBe("number"); expect(res[1].field).toBe("list[0]"); }); it("should give error if the array is broken", () => { let obj = { list: [true, false] }; let res = check(obj); expect(res).toBeInstanceOf(Array); expect(res.length).toBe(4); expect(res[0].type).toBe("string"); expect(res[0].field).toBe("list[0]"); expect(res[1].type).toBe("string"); expect(res[1].field).toBe("list[1]"); }); });
21.128149
159
0.579523
674c2649ba66a13da96616e4232239552a5fa07f
1,499
js
JavaScript
bitrix/modules/landing/install/js/landing/ui/field/color/src/layout/primary/primary.js
Poulhouse/dev_don360
9e7b60e38cdd8be47d31a0080c9cdfabe22215ce
[ "Apache-2.0" ]
null
null
null
bitrix/modules/landing/install/js/landing/ui/field/color/src/layout/primary/primary.js
Poulhouse/dev_don360
9e7b60e38cdd8be47d31a0080c9cdfabe22215ce
[ "Apache-2.0" ]
null
null
null
bitrix/modules/landing/install/js/landing/ui/field/color/src/layout/primary/primary.js
Poulhouse/dev_don360
9e7b60e38cdd8be47d31a0080c9cdfabe22215ce
[ "Apache-2.0" ]
null
null
null
import {EventEmitter} from 'main.core.events'; import {Cache, Tag, Event, Dom, Loc} from 'main.core'; import ColorValue from "../../color_value"; import './css/primary.css'; export default class Primary extends EventEmitter { static ACTIVE_CLASS: string = 'active'; static CSS_VAR: string = '--primary'; // todo: layout or control? constructor() { super(); this.cache = new Cache.MemoryCache(); this.setEventNamespace('BX.Landing.UI.Field.Color.Primary'); Event.bind(this.getLayout(), 'click', () => this.onClick()); } getLayout(): HTMLElement { return this.cache.remember('layout', () => { return Tag.render` <div class="landing-ui-field-color-primary"> <i class="landing-ui-field-color-primary-preview"></i> <span class="landing-ui-field-color-primary-text"> ${Loc.getMessage('LANDING_FIELD_COLOR-PRIMARY_TITLE')} </span> </div> `; }); } getValue(): ColorValue { return this.cache.remember('value', () => { return new ColorValue(Primary.CSS_VAR); }); } onClick() { this.setActive(); this.emit('onChange', {color: this.getValue()}); } setActive() { Dom.addClass(this.getLayout(), Primary.ACTIVE_CLASS); } unsetActive() { Dom.removeClass(this.getLayout(), Primary.ACTIVE_CLASS); } isActive(): boolean { return Dom.hasClass(this.getLayout(), Primary.ACTIVE_CLASS); } isPrimaryValue(value: ColorValue): boolean { return (value !== null) && (this.getValue().getCssVar() === value.getCssVar()); } }
21.724638
81
0.662442
674c72b255f543bee0d3a10b730c7bda2b864f58
917
js
JavaScript
client/components/login.js
setiaanggraeni/live-code-phase2
8be169ce73d6b75dd0489bb2d50822139b558d0a
[ "MIT" ]
null
null
null
client/components/login.js
setiaanggraeni/live-code-phase2
8be169ce73d6b75dd0489bb2d50822139b558d0a
[ "MIT" ]
null
null
null
client/components/login.js
setiaanggraeni/live-code-phase2
8be169ce73d6b75dd0489bb2d50822139b558d0a
[ "MIT" ]
null
null
null
Vue.component('login', { template: ` <div id="loginForm" style="width:60%; margin-left:20%"> <form> <label>Username</label> <input type="email" v-model="username" class="form-control" placeholder="Username"> <label>Password</label> <input type="password" v-model="password" class="form-control" placeholder="Password"><br> <button type="submit" class="btn btn-primary" @click.prevent="login()">Login</button> </form> </div> `, data () { return { username: '', password: '' } }, methods: { login () { axios.post('http://localhost:3000/request_token', { username: this.username, password: this.password }) .then(userLogin => { localStorage.setItem('token', userLogin.data.token) window.location="home.html" }) .catch(err => { console.log(err.message) }) } } })
26.2
96
0.572519
674d64a08b6def54fc184907882d3e7124945654
2,434
js
JavaScript
spotify-backend/server.js
tleuschner/spotify-project
edabae1ff4f727cae8647c8ff1844013340d0df4
[ "Apache-2.0" ]
null
null
null
spotify-backend/server.js
tleuschner/spotify-project
edabae1ff4f727cae8647c8ff1844013340d0df4
[ "Apache-2.0" ]
9
2020-07-17T08:09:59.000Z
2022-02-18T02:39:42.000Z
spotify-backend/server.js
tleuschner/spotify-project
edabae1ff4f727cae8647c8ff1844013340d0df4
[ "Apache-2.0" ]
null
null
null
require('dotenv').config(); let express = require('express'); let bodyParser = require('body-parser'); let mysql = require('mysql'); let cors = require('cors'); const app = express(); const jsonParser = bodyParser.json(); const PORT = process.env.PORT || 1234; /** * Setup connection credentials */ let connection; let dbConfig = { host: process.env.DB_HOST, user: process.env.DB_USER, password: process.env.DB_PASSWORD, database: process.env.DB_NAME, } /** * Connect to database */ function handleDisconnect() { connection = mysql.createConnection(dbConfig); connection.connect((err) => { if (err) { console.log('error connecting to database', err); setTimeout(handleDisconnect, 2000); } }); connection.on('error', (err) => { console.log('Database error', err); if (err.code === 'PROTOCOL_CONNECTION_LOST') { handleDisconnect(); } else { throw err; } }); } handleDisconnect(); app.use(jsonParser).use(cors()); //Debug feature app.get('/', (req, res, next) => { res.write('Hello World'); res.end(); }) /** * Get current Visitors from Database and send response as JSON * on error send 500 response */ app.get('/visitors', (req, res) => { let uniqueUsers; connection.query('SELECT COUNT(*) AS visitors FROM users ', (err, result) => { if (err) { res.status(500).json({ "visitors": 000 }); } else { uniqueUsers = result[0].visitors; res.status(200).json({ "visitors": uniqueUsers }); } }); }); /** * insert users into MySQL Databse. Use INSERT IGNORE to only insert if user hasnt already been added to DB * * */ app.post('/user', (req, res) => { if (req.body && req.body.spotifyID && req.body.country) { let country = req.body.country; let spotifyID = req.body.spotifyID; connection.query('INSERT IGNORE INTO users (SPOTIFY_ID, COUNTRY) VALUES (?, ?)', [spotifyID, country], (err) => { if (err) { res.status(500).json(null); throw err; } }); res.status(200).json(null); } else { res.status(500).json(null); } }); /** * Start server on specified port */ app.listen(PORT, () => { console.log(`listening on Port ${PORT}`); });
24.09901
121
0.564092
674ded5dbfef642324a5861590f062ad0e1c0340
3,599
js
JavaScript
public/js/admin/sockets/dashboard/context-menu.js
AprendiendoNode/alice
61238c7c7bdbb80cb1821d78963b99a514cae72b
[ "MIT" ]
null
null
null
public/js/admin/sockets/dashboard/context-menu.js
AprendiendoNode/alice
61238c7c7bdbb80cb1821d78963b99a514cae72b
[ "MIT" ]
null
null
null
public/js/admin/sockets/dashboard/context-menu.js
AprendiendoNode/alice
61238c7c7bdbb80cb1821d78963b99a514cae72b
[ "MIT" ]
1
2021-03-04T15:17:29.000Z
2021-03-04T15:17:29.000Z
$(window).on("load", function() { var areaActual; $.contextMenu({ selector: '.ui-widget-content', trigger: (($(window).width() < 700) ? 'left' : 'right'), events: { show : function(options) { ctrl_status = 0; try { $(".blink").resizable('disable'); } catch(e) {} $('#mapa').contextMenu(false); //$("#"+this[0].id).css("opacity", "0.5"); if(!$("#"+this[0].id).hasClass("ui-selected")) { $(".blink").removeClass('ui-selected'); $("#"+this[0].id).addClass("ui-selected"); } }, hide : function(options) { ctrl_status = 1; if($(".ui-selected").length == 0) { $(".blink").resizable('enable'); } $('#mapa').contextMenu(true); //$("#"+this[0].id).css("opacity", "1"); //$("#"+this[0].id).removeClass("ui-selected"); } }, callback: function(key, options) { var areaId = this[0].id; areaActual = allAreas.filter(function (area) { return area.id == areaId.split("area")[1]; }); elementsarray = []; $(".ui-selected").each(function (index, element) { elementsarray.push(parseInt(element.getAttribute("id").replace('area',''))); }); switch(key) { case "nombre": $("#nuevoNombre").val(areaActual[0].nombre); $("#CambiarNombre").modal("show"); break; case "estado": $("#nuevoEstado").val(areaActual[0].estado); $("#CambiarEstado").modal("show"); break; case "piso": $("#nuevoPiso").val(areaActual[0].piso); $("#nuevoPiso").trigger('change'); $("#CambiarPisoMenu").modal("show"); break; case "eliminar": $("#EliminarArea").modal("show"); break; } }, items: { "ver": {name: "Ver detalles", icon: "fas fa-eye"}, "nombre": {name: "Cambiar nombre", icon: "fas fa-edit"}, "estado": {name: "Cambiar estado", icon: "fas fa-sync-alt"}, "piso": {name: "Cambiar piso", icon: "fas fa-clone"}, "equipos": {name: "Gestionar equipos", icon: "fas fa-broadcast-tower"}, "split": "---------", "eliminar": {name: "Eliminar", icon: "fas fa-trash-alt"} } }); $("#CambiarNombreButton").click(function() { var nombre = $("#nuevoNombre").val(); socket.emit('nuevoNombre', { nombre: nombre, area: elementsarray,//$('#selected_area').val(), hotel_id: hotel_id }); $("#CambiarNombre").modal("hide"); }); $("#CambiarEstadoButton").click(function() { var estado = $("#nuevoEstado").val(); socket.emit('nuevoEstado', { estado: estado, area: elementsarray,//$('#selected_area').val(), hotel_id: hotel_id }); $("#CambiarEstado").modal("hide"); }); $("#CambiarPisoMenuButton").click(function() { var piso = $("#nuevoPiso").val(); pisoActual = piso; socket.emit('nuevoPiso', { piso: piso, area: elementsarray,//$('#selected_area').val(), hotel_id: hotel_id }); $("#CambiarPisoMenu").modal("hide"); }); $("#EliminarAreaButton").click(function() { socket.emit('eliminarArea', { area: elementsarray,//$('#selected_area').val(), hotel_id: hotel_id }); $("#EliminarArea").modal("hide"); }); });
22.778481
85
0.482912
674e06ca0b0b90c035997cfc93618f8b07f21697
403
js
JavaScript
src/components/menus/MegaMenus/MegaMenuLists/Style1/ListStyles.js
arhoy/new_barber
7a2ec10351759797b1fd237512abf80e685304e2
[ "MIT" ]
1
2019-11-18T10:17:24.000Z
2019-11-18T10:17:24.000Z
src/components/menus/MegaMenus/MegaMenuLists/Style1/ListStyles.js
arhoy/new_barber
7a2ec10351759797b1fd237512abf80e685304e2
[ "MIT" ]
null
null
null
src/components/menus/MegaMenus/MegaMenuLists/Style1/ListStyles.js
arhoy/new_barber
7a2ec10351759797b1fd237512abf80e685304e2
[ "MIT" ]
null
null
null
import styled from '@emotion/styled'; import NoStyleLink from '../../../../Links/NoStyleLink'; const MegaMenuUl = styled.ul` display: flex; flex-direction: column; align-items: center; `; const MegaMenuLi = styled.li` margin: 1px 0; padding: 2px 4px; &:hover { font-weight: bolder; } `; const MegaMenuLink = styled(NoStyleLink)``; export { MegaMenuUl, MegaMenuLi, MegaMenuLink };
18.318182
56
0.679901
674e6c4d29468454d3e69330d07b4120083193e9
474
js
JavaScript
sit/static/js/ZYJW.250bb33b.js
loveless277/vue-temp
a056e408b61709ec3a88563e030ac0dc41a6de5b
[ "MIT" ]
null
null
null
sit/static/js/ZYJW.250bb33b.js
loveless277/vue-temp
a056e408b61709ec3a88563e030ac0dc41a6de5b
[ "MIT" ]
null
null
null
sit/static/js/ZYJW.250bb33b.js
loveless277/vue-temp
a056e408b61709ec3a88563e030ac0dc41a6de5b
[ "MIT" ]
null
null
null
(window.webpackJsonp=window.webpackJsonp||[]).push([["ZYJW"],{ZYJW:function(e,n,t){"use strict";t.r(n);var i=function(e,n){var t=n._c;return t("div",{staticStyle:{padding:"30px"}},[t("el-alert",{attrs:{closable:!1,title:"menu 1-2-1",type:"warning"}})],1)};i._withStripped=!0;var l=t("ZrdR"),r=Object(l.a)({},i,[],!0,null,null,null);r.options.__file="src\\views\\nested\\menu1\\menu1-2\\menu1-2-1\\index.vue";n.default=r.exports}}]); //# sourceMappingURL=ZYJW.250bb33b.js.map
237
432
0.675105
674fc5a8c3a5ab019a4bd1bd7bd297ea842e8a3f
2,463
js
JavaScript
Gruntfile.js
ClaudiuCreanga/track-productivity
6e050b587ebe10a9ffcf352afbdf5069871012c5
[ "MIT" ]
2
2017-06-16T14:29:39.000Z
2020-10-22T10:35:23.000Z
Gruntfile.js
ClaudiuCreanga/track-productivity
6e050b587ebe10a9ffcf352afbdf5069871012c5
[ "MIT" ]
null
null
null
Gruntfile.js
ClaudiuCreanga/track-productivity
6e050b587ebe10a9ffcf352afbdf5069871012c5
[ "MIT" ]
null
null
null
module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { options: { separator: ';' }, dist:{ src: ['src/js/*.js','!src/js/d3.v3.min.js'], dest: 'dist/<%= pkg.name %>.js' } }, uglify: { options: { banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n' }, dist: { files: { 'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>'] } } }, cssmin: { options: { shorthandCompacting: false, roundingPrecision: -1, keepSpecialComments:0 }, minify : { expand : true, cwd : 'src/css', src : ['*.css', '!*.min.css'], dest : 'dist/css', ext : '.min.css' }, combine : { files: { 'dist/combined.css': ['dist/css/*.css'] } }, }, htmlmin: { dist: { options: { removeComments: true, collapseWhitespace: true }, files: { 'dist/index.html': 'src/index.html', } } }, watch: { /* js: { files: ['src/js/*.js'], tasks: ['jshint'] }, */ css: { files: 'src/css/*.css', tasks: ['css'] }, html:{ files: 'src/index.html', tasks: ['html'] } }, requirejs: { compile: { options: { baseUrl: 'src/js/app', mainConfigFile: 'src/js/appFrontend.js', out: 'dist/meAnalytics.js' } } }, jshint: { files: ['Gruntfile.js', 'src/js/app/menu/eventListeners.js'], } }); // Load plugins. grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-contrib-htmlmin'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-requirejs'); // Default task(s). grunt.registerTask('default', ['cssmin','htmlmin','concat','uglify']); grunt.registerTask('js', ['concat','uglify']); grunt.registerTask('requirejs', ['requirejs']); grunt.registerTask('jshint', ['jshint']); grunt.registerTask('css', ['cssmin']); grunt.registerTask('html', ['htmlmin']); };
23.682692
84
0.488023
675040ef76d527407ca64f38c3f50ec42df0c026
108
js
JavaScript
app/helpers/humanize-compact-number.js
mediapop/ember-humanize
b484e4563c47ca16b8ad0076e8f947b8fbdb8a17
[ "MIT" ]
null
null
null
app/helpers/humanize-compact-number.js
mediapop/ember-humanize
b484e4563c47ca16b8ad0076e8f947b8fbdb8a17
[ "MIT" ]
null
null
null
app/helpers/humanize-compact-number.js
mediapop/ember-humanize
b484e4563c47ca16b8ad0076e8f947b8fbdb8a17
[ "MIT" ]
null
null
null
export { default, humanizeCompactNumberc } from '@mediapop/ember-humanize/helpers/humanize-compact-number';
54
107
0.814815
67507620a84f453e69762c165aef86092bc5ecdd
2,322
js
JavaScript
assets/js/toolitup-jrate.min.js
toolitup/toolitup.github.io
1c373a39eee1b2cbe895e913036aac0eef96a667
[ "MIT" ]
null
null
null
assets/js/toolitup-jrate.min.js
toolitup/toolitup.github.io
1c373a39eee1b2cbe895e913036aac0eef96a667
[ "MIT" ]
null
null
null
assets/js/toolitup-jrate.min.js
toolitup/toolitup.github.io
1c373a39eee1b2cbe895e913036aac0eef96a667
[ "MIT" ]
null
null
null
function generateJRate(a,b){var c={rating:3,shape:"STAR",count:5,width:"30",height:"30",widthGrowth:0,heightGrowth:0,backgroundColor:"white",startColor:"yellow",endColor:"green",strokeColor:"black",shapeGap:"0px",opacity:1,min:0,max:5,precision:1,minSelected:0,horizontal:!0,reverse:!1,readOnly:!1,onChange:null,onSet:null},d=$.extend({},c,b);$("#"+a).jRate({rating:d.rating,shape:d.shape,count:d.count,width:d.width,height:d.height,widthGrowth:d.widthGrowth,heightGrowth:d.heightGrowth,backgroundColor:d.backgroundColor,startColor:d.startColor,endColor:d.endColor,strokeColor:d.strokeColor,shapeGap:d.shapeGap,opacity:d.opacity,min:d.min,max:d.max,precision:d.precision,minSelected:d.minSelected,horizontal:d.horizontal,reverse:d.reverse,readOnly:d.readOnly,onChange:function(b){$("#"+a+"-value").text(b)},onSet:d.onSet})}function callOnChange(){$("#demo-onchange").jRate({rating:3,width:30,height:30,onChange:function(a){$("#demo-onchange-value").text("Your Rating: "+a)}})}function callOnSet(){$("#demo-onset").jRate({rating:3,width:30,height:30,onSet:function(a){$("#demo-onset-value").text("Selected Rating: "+a)}})}$(function(){console.log("Entering into Start"),generateJRate("demo-main",{}),generateJRate("demo-color",{startColor:"cyan",endColor:"blue"}),generateJRate("demo-rating",{rating:"1"}),generateJRate("demo-width",{width:"60",height:"60"}),generateJRate("demo-shape",{shape:"FOOD",startColor:"lightpink",endColor:"darkmagenta",width:"40",height:"40",rating:5}),generateJRate("demo-shape-twitter",{shape:"TWITTER",width:"40",height:"40",startColor:"#58E4FF",endColor:"#4485F5",rating:5}),generateJRate("demo-shape-bulb",{shape:"BULB",width:"40",height:"40",startColor:"#FFFEBE",endColor:"#419A11",rating:5}),generateJRate("demo-width-growth",{widthGrowth:.2,heightGrowth:.2}),generateJRate("demo-count",{count:10}),generateJRate("demo-bg-color",{backgroundColor:"black"}),generateJRate("demo-gap",{shapeGap:"10px"}),generateJRate("demo-opacity",{opacity:.3}),generateJRate("demo-min-max",{min:10,max:15,rating:11}),generateJRate("demo-min-selected",{minSelected:3}),generateJRate("demo-precision",{precision:.5}),generateJRate("demo-horizontal",{horizontal:!1}),generateJRate("demo-reverse",{reverse:!0}),generateJRate("demo-readonly",{readOnly:!0}),callOnChange(),callOnSet(),console.log("Ending all")});
2,322
2,322
0.752369
6750a8eee65da4330be96b4dc76b531960706c80
2,315
js
JavaScript
src/components/Deposits.js
zaraehhs/Ante
c763c38a110b67e0c3bac6ab56deee5aa0d41a50
[ "MIT" ]
null
null
null
src/components/Deposits.js
zaraehhs/Ante
c763c38a110b67e0c3bac6ab56deee5aa0d41a50
[ "MIT" ]
null
null
null
src/components/Deposits.js
zaraehhs/Ante
c763c38a110b67e0c3bac6ab56deee5aa0d41a50
[ "MIT" ]
1
2021-01-11T04:02:34.000Z
2021-01-11T04:02:34.000Z
import React, { useEffect, useState, useContext } from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Typography from '@material-ui/core/Typography'; import Title from './Title'; import { firestore } from "../firebase/firebase.utils"; import { UserContext } from "../firebase/auth-provider"; const useStyles = makeStyles({ depositContext: { flex: 1, }, }); export default function Deposits() { const classes = useStyles(); const [total, settotal] = useState([]); const [days, setdate] = useState([]); const business = useContext(UserContext).business; useEffect(() => { const salesDB = firestore.collection("sales").where("business", "==", business); const unsubscribeFromSnapshot = salesDB.onSnapshot(async snapshot => { const totals = []; let today = new Date(); // get the date let day = ("0" + today.getDate()).slice(-2); //get day with slice to have double digit day let month = ("0" + (today.getMonth() + 1)).slice(-2); //get your zero in front of single month digits so you have 2 digit months let todaysdate = month + '/' + day + '/' + today.getFullYear(); snapshot.docs.forEach((doc) => { const { timestamp, total} = doc.data(); let today1 = new Date(timestamp); // get the date let day1 = ("0" + today1.getDate()).slice(-2); //get day with slice to have double digit day let month1 = ("0" + (today1.getMonth() + 1)).slice(-2); //get your zero in front of single month digits so you have 2 digit months let purchaseDate = month1 + '/' + day1 + '/' + today1.getFullYear(); if (todaysdate == purchaseDate) { totals.push(total); } },); const sum = totals.reduce(function(a, b){ return a + b; }, 0); settotal(sum); setdate(todaysdate); }); return () => { unsubscribeFromSnapshot(); //unmounts } },[]); //anytime [] changes return ( <React.Fragment> <Title>Today's Sales</Title> <Typography component="p" variant="h4"> $ {parseFloat(total).toFixed(2)} </Typography> <Typography color="textSecondary" className={classes.depositContext}> {days} </Typography> <div> </div> </React.Fragment> ); }
33.071429
138
0.599136
67521cb3fd6f0478d9c4d48ef21a49b34d11bd74
1,465
js
JavaScript
src/components/shared/Button.js
bcorey85/vsainte-gatsby
545aa67b4e7aff9181035bfec406063db1ce0fcd
[ "MIT" ]
null
null
null
src/components/shared/Button.js
bcorey85/vsainte-gatsby
545aa67b4e7aff9181035bfec406063db1ce0fcd
[ "MIT" ]
9
2020-10-05T00:44:17.000Z
2022-02-27T06:13:31.000Z
src/components/shared/Button.js
bcorey85/vsainte-gatsby
545aa67b4e7aff9181035bfec406063db1ce0fcd
[ "MIT" ]
null
null
null
import React from 'react'; // import { Link } from 'react-router-dom'; import { Link } from 'gatsby'; import './Button.css'; const Button = props => { const { to, href, type, color, width, padding, margin, borderRadius } = props; const colors = { default: 'var(--primary-dark)', cta: 'var(--red)' }; const widths = { default: 'auto', full: '100%' }; const paddings = { default: '0 4.8rem', tight: '0 1.6rem' }; const margins = { default: '0 1.6rem', left: '0 0 0 1.6rem', right: '0 1.6rem 0 0', none: '0' }; if (href) { return ( <a href={href} className='btn' style={{ backgroundColor: `${colors[color]}`, width: `${widths[width]}`, padding: `${paddings[padding]}`, margin: `${margins[margin]}`, borderRadius: borderRadius }}> {props.children} </a> ); } if (type) { return ( <button className='btn' style={{ backgroundColor: `${colors[color]}`, width: `${widths[width]}`, padding: `${paddings[padding]}`, margin: `${margins[margin]}`, borderRadius: borderRadius }}> {props.children} </button> ); } return ( <Link to={to} className='btn' style={{ backgroundColor: `${colors[color]}`, width: `${widths[width]}`, padding: `${paddings[padding]}`, margin: `${margins[margin]}`, borderRadius: borderRadius }}> {props.children} </Link> ); }; export default Button;
16.098901
43
0.552901
6752f0205c89daf45ae352b0cd624fa97093e746
723
js
JavaScript
src/shared/model/BaseTrail.js
eleven-labs/curvytron
bddc847123c2c269924585ad8def40776ccbd946
[ "MIT" ]
null
null
null
src/shared/model/BaseTrail.js
eleven-labs/curvytron
bddc847123c2c269924585ad8def40776ccbd946
[ "MIT" ]
null
null
null
src/shared/model/BaseTrail.js
eleven-labs/curvytron
bddc847123c2c269924585ad8def40776ccbd946
[ "MIT" ]
null
null
null
/** * BaseTrail */ function BaseTrail(avatar) { EventEmitter.call(this); this.avatar = avatar; this.color = this.avatar.color; this.radius = this.avatar.radius; this.points = []; } BaseTrail.prototype = Object.create(EventEmitter.prototype); BaseTrail.prototype.constructor = BaseTrail; /** * Add point * * @param {Array} point */ BaseTrail.prototype.addPoint = function(point) { this.points.push(point); }; /** * Get last point * * @return {Array} */ BaseTrail.prototype.getLast = function() { return this.points.length ? this.points[this.points.length - 1] : null; }; /** * Clear * * @param {Array} point */ BaseTrail.prototype.clear = function() { this.points = []; };
16.066667
75
0.647303
67530f69e32f1af1e543a125642e87a3be2f0fdf
3,486
js
JavaScript
src/loupan-sell.js
zhoukekestar/tmsf
3f1aece48541f5920875a84a474ee59740cc072d
[ "MIT" ]
null
null
null
src/loupan-sell.js
zhoukekestar/tmsf
3f1aece48541f5920875a84a474ee59740cc072d
[ "MIT" ]
null
null
null
src/loupan-sell.js
zhoukekestar/tmsf
3f1aece48541f5920875a84a474ee59740cc072d
[ "MIT" ]
null
null
null
/* 楼盘总体销售数据 */ // // 可售 // const sellUrl = `http://sz.tmsf.com/newhouse/property_33_133319_price.htm?isopen=1&presellid=&buildingid=&area=&allprice=&housestate=1&housetype=&page=`; // // 可售并小于 50 // const sellUrl50 = `http://sz.tmsf.com/newhouse/property_33_133319_price.htm?isopen=1&presellid=&buildingid=&area=0_50&allprice=&housestate=1&housetype=&page=`; // // 已售 // const soldUrl = `http://sz.tmsf.com/newhouse/property_33_133319_price.htm?isopen=1&presellid=&buildingid=&area=&allprice=&housestate=2&housetype=&page=`; // // 已售并小于 50 // const soldUrl50 = `http://sz.tmsf.com/newhouse/property_33_133319_price.htm?isopen=1&presellid=&buildingid=&area=0_50&allprice=&housestate=2&housetype=&page=`; async function fetchDocument(url) { var text = await fetch(url).then(t => t.text()); var doc = document.createElement('div'); doc.innerHTML = text; return doc; } async function fetchTotalNumber(url) { const doc = await fetchDocument(url); return doc.querySelector('div.bggrey.w1000 > div:nth-child(8) > div > div.spagenext > span').innerText.match(/总数:(\d+)套/)[1]; } async function transUrl(url) { const sellUrl = url.replace('_info.htm', '_price.htm?isopen=1&presellid=&buildingid=&area=&allprice=&housestate=1&housetype=&page='); const sellUrl50 = url.replace('_info.htm', '_price.htm?isopen=1&presellid=&buildingid=&area=0_50&allprice=&housestate=1&housetype=&page='); const soldUrl = url.replace('_info.htm', '_price.htm?isopen=1&presellid=&buildingid=&area=&allprice=&housestate=2&housetype=&page='); const soldUrl50 = url.replace('_info.htm', '_price.htm?isopen=1&presellid=&buildingid=&area=0_50&allprice=&housestate=2&housetype=&page='); return { sell: await fetchTotalNumber(sellUrl), sell50: await fetchTotalNumber(sellUrl50), sold: await fetchTotalNumber(soldUrl), sold50: await fetchTotalNumber(soldUrl50), } } !(async function init() { const urls = `http://sz.tmsf.com/newhouse/property_33_133319_info.htm http://sz.tmsf.com/newhouse/property_33_209800506_info.htm http://sz.tmsf.com/newhouse/property_33_431137829_info.htm http://sz.tmsf.com/newhouse/property_33_1770989_info.htm http://sz.tmsf.com/newhouse/property_33_135424_info.htm http://sz.tmsf.com/newhouse/property_33_133125_info.htm http://sz.tmsf.com/newhouse/property_33_1694875_info.htm http://sz.tmsf.com/newhouse/property_33_135092_info.htm http://sz.tmsf.com/newhouse/property_33_133437_info.htm http://sz.tmsf.com/newhouse/property_33_134855_info.htm http://sz.tmsf.com/newhouse/property_33_134035_info.htm http://sz.tmsf.com/newhouse/property_33_274318_info.htm http://sz.tmsf.com/newhouse/property_33_134895_info.htm http://sz.tmsf.com/newhouse/property_33_135133_info.htm http://sz.tmsf.com/newhouse/property_33_274286_info.htm http://sz.tmsf.com/newhouse/property_33_135043_info.htm http://sz.tmsf.com/newhouse/property_33_133594_info.htm http://sz.tmsf.com/newhouse/property_33_3158256_info.htm http://sz.tmsf.com/newhouse/property_33_135004_info.htm http://sz.tmsf.com/newhouse/property_33_201740937_info.htm http://sz.tmsf.com/newhouse/property_33_311176_info.htm http://sz.tmsf.com/newhouse/property_33_133521_info.htm http://sz.tmsf.com/newhouse/property_33_292204_info.htm`.split('\n'); const result = []; for (let i = 0; i < urls.length; i++) { result.push(await transUrl(urls[i])); } console.log(result); console.log( result .map(t => `${t.sell}\t${t.sell50}\t${t.sold}\t${t.sold50}`) .join("\n") ); })()
44.126582
162
0.751865
6753cfa13e14af45042dc26ba60d251211c45c92
828
js
JavaScript
bootstrap.js
mxsgx/simple-chat-app
6d3813be77aaf6136a5ea1f63b3b86da3b31a76a
[ "MIT" ]
1
2021-07-28T04:51:32.000Z
2021-07-28T04:51:32.000Z
bootstrap.js
mxsgx/simple-chat-app
6d3813be77aaf6136a5ea1f63b3b86da3b31a76a
[ "MIT" ]
null
null
null
bootstrap.js
mxsgx/simple-chat-app
6d3813be77aaf6136a5ea1f63b3b86da3b31a76a
[ "MIT" ]
null
null
null
const path = require('path'); module.exports = function (fastify) { require('./config')(fastify); fastify.register(require('fastify-cors'), { origin: fastify.config.CORS_ORIGIN, }); fastify.register(require('fastify-static'), { root: path.join(__dirname, 'public'), wildcard: false, }); fastify.register(require('point-of-view'), { engine: { ejs: require('ejs'), }, root: path.join(__dirname, 'resources', 'views'), viewExt: path.join('ejs'), }); fastify .register(require('fastify-socket.io'), { cors: fastify.config.CORS_ORIGIN_SOCKET, }) .ready(() => { fastify.io.on('connection', function (socket) { require('./routes/ws')(socket, fastify); }); }); require('./routes/http')(fastify); require('./plugins/mix')(fastify); };
23
53
0.602657
6753ec3dfa71cd798bf86aa32656fa624a0802bb
748
js
JavaScript
utils/errors/http.js
nerjs/pwc
c897644cd37c9698fea74dfd49e1199671cde68d
[ "MIT" ]
null
null
null
utils/errors/http.js
nerjs/pwc
c897644cd37c9698fea74dfd49e1199671cde68d
[ "MIT" ]
null
null
null
utils/errors/http.js
nerjs/pwc
c897644cd37c9698fea74dfd49e1199671cde68d
[ "MIT" ]
null
null
null
const { STATUS_CODES } = require('http') class HttpError extends Error { constructor(code, message) { super('HTTPERROR') this.fromJSON(code && typeof code === 'object' ? code : { code, message }) } get name() { return 'HttpError' } toString() { return `${this.name}[${this.code}]: ${this.message}` } toJSON() { const { name, code, message } = this return { name, code, message } } fromJSON({ code, message }) { this.code = code || 500 this.message = message || STATUS_CODES[this.code] if (message && message != this.message) { this.originalMessage = STATUS_CODES[this.code] } } } module.exports = HttpError
21.371429
82
0.549465
36c503820bff2650271665a876efd4285278540c
2,369
js
JavaScript
src/components/commentList/index.js
dengzy321/react-NeteaseCloudMusic-mobile
c03de8094d0f85d513b359edbc0c2706a7dfcff5
[ "AFL-3.0" ]
2
2021-06-25T14:33:33.000Z
2021-09-03T09:09:38.000Z
src/components/commentList/index.js
dengzy321/react-NeteaseCloudMusic-mobile
c03de8094d0f85d513b359edbc0c2706a7dfcff5
[ "AFL-3.0" ]
5
2021-03-10T05:58:32.000Z
2022-02-26T23:01:13.000Z
src/components/commentList/index.js
dengzy321/react-NeteaseCloudMusic-mobile
c03de8094d0f85d513b359edbc0c2706a7dfcff5
[ "AFL-3.0" ]
null
null
null
import React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as actions from '@/store/actions'; import './index.css'; import { Link } from 'react-router-dom' import { http } from '@/api/http' import Iconpath from '@/utils/iconpath' import Loading from '@/components/Loading' export default function CommentItem({ data = [], commentsId }) { // 点赞 function onLive(item) { http.getCommentLike({ id: commentsId, cid: item.commentId, t: item.liked ? 0 : 1, tpye: 0 }).then(res => { data.forEach(item2 => { if (item2 == item) item2.liked = item2.liked ? 0 : 1 }) }) } data.forEach(item => { let date = new Date(item.time) let year = date.getFullYear() let min = date.getMonth() + 1 let d = date.getDay() item.publishTime = `${year}年${min >= 10 ? min : '0' + min}月${d >= 10 ? d : '0' + d}日` item.likeCount = item.likedCount >= 100000 ? (item.likedCount / 10000).toFixed(1) + '万' : item.likedCount }) // if(data.length == 0) return <Loading/> return ( <div className='commentItem'> <ul className='comment-ul'> { data.map((item, index) => ( <li className='comment-li' key={index}> <div className='userInfo da'> <img className='avatar' src={item.user.avatarUrl} /> <p className='flex'> <span className='nickname'>{item.user.nickname}</span> <span className='time'>{item.publishTime}</span> </p> <p className='liveCount da' onClick={onLive.bind(this, item)}> <span className='count'>{item.likeCount}</span> <img className='live-icon' src={item.liked ? Iconpath.live_red : Iconpath.live_$999} /> </p> </div> <div className='content'>{item.content}</div> </li> )) } </ul> </div> ) }
40.152542
123
0.460532
36c58e1ea0d72faadbdad46fd8ad0872efd60e3c
831
js
JavaScript
src/desktop/collections/partner_artists.js
jpoczik/force
bfa78df8dc4316c67697196f8d1228f276c32533
[ "MIT" ]
377
2016-08-16T18:57:09.000Z
2022-03-24T15:32:47.000Z
src/desktop/collections/partner_artists.js
jpoczik/force
bfa78df8dc4316c67697196f8d1228f276c32533
[ "MIT" ]
5,516
2016-08-16T18:52:12.000Z
2022-03-31T20:10:39.000Z
src/desktop/collections/partner_artists.js
jpoczik/force
bfa78df8dc4316c67697196f8d1228f276c32533
[ "MIT" ]
158
2016-08-16T18:48:12.000Z
2022-02-13T21:19:56.000Z
/* * decaffeinate suggestions: * DS206: Consider reworking classes to avoid initClass * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ let _PartnerArtists const _ = require("underscore") const Backbone = require("backbone") const { PartnerArtist } = require("../models/partner_artist") const { API_URL } = require("sharify").data const { Fetch } = require("@artsy/backbone-mixins") export default _PartnerArtists = (function () { _PartnerArtists = class PartnerArtists extends Backbone.Collection { static initClass() { _.extend(this.prototype, Fetch(API_URL)) this.prototype.model = PartnerArtist this.prototype.comparator = "sortable_id" } } _PartnerArtists.initClass() return _PartnerArtists })() export const PartnerArtists = _PartnerArtists
30.777778
90
0.737665
36c637235dd42c2ee104683e8cfb8695fcf11720
1,191
js
JavaScript
server/app.js
huangyan321/fst-blog
80f3e4f32940d8c7d06a458b17d89890185835b5
[ "MIT" ]
null
null
null
server/app.js
huangyan321/fst-blog
80f3e4f32940d8c7d06a458b17d89890185835b5
[ "MIT" ]
null
null
null
server/app.js
huangyan321/fst-blog
80f3e4f32940d8c7d06a458b17d89890185835b5
[ "MIT" ]
1
2022-03-16T09:29:54.000Z
2022-03-16T09:29:54.000Z
var express = require("express"); var path = require("path"); var history = require("connect-history-api-fallback"); var cookieParser = require("cookie-parser"); var logger = require("morgan"); global.globalkey = "123456"; //全局key var app = express(); //跨域配置 app.all("*", function (req, res, next) { //设置允许跨域的域名,*代表允许任意域名跨域 res.header("Access-Control-Allow-Origin", "*"); //允许的header类型 res.header( "Access-Control-Allow-Headers", "Content-Type,Access-Token,Appid,Secret,Authorization" ); //跨域允许的请求方式 res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS"); if (req.method.toLowerCase() == "options") res.sendStatus(200); //让options尝试请求快速结束 else next(); }); app.use( //使用history模式 history({ index: "/index.html", }) ); app.use(logger("dev")); app.use(express.json()); app.use( express.urlencoded({ extended: false, }) ); app.use(cookieParser()); // app.use(express.static(path.join(__dirname, 'public'))) // app.use('/admin', express.static(__dirname + '/../admin/dist')) app.use(express.static(__dirname + "/../front/dist")); require("./routes/admin/index")(app); require("./routes/user/index")(app); module.exports = app;
25.340426
76
0.669186
36c85b244e69e0be7433f8693589a0b74f051abe
1,192
js
JavaScript
api/controllers/mailController.js
borgfu95/dr-server
2b433da6f5ec93d65cf38d223db9561aaefd344d
[ "MIT" ]
1
2018-11-30T02:57:15.000Z
2018-11-30T02:57:15.000Z
api/controllers/mailController.js
borgfu95/dr-server
2b433da6f5ec93d65cf38d223db9561aaefd344d
[ "MIT" ]
null
null
null
api/controllers/mailController.js
borgfu95/dr-server
2b433da6f5ec93d65cf38d223db9561aaefd344d
[ "MIT" ]
null
null
null
'use strict'; const nodemailer = require('nodemailer'); class mailController { static sendMail (req, res) { let html = req.body.content; let host = 'mail2.augmentum.com.cn'; let userName = 'borgfu@augmentum.com.cn'; let password = '111111'; let transporter = nodemailer.createTransport({ host: host, secure: false, secureConnection: true, port: 25, auth: { user: userName, pass: password, }, tls: {rejectUnauthorized: false} }); var option = { from:"borgfu@augmentum.com.cn", to:"borgfu@augmentum.com.cn" } let date = new Date(); let day = date.getDate().toString().length > 1 ? date.getDate() : '0' + date.getDate() option.subject = '[Services - CloudSearch] DailyStatus_' + (date.getMonth() + 1) + day + date.getFullYear(); option.html= html; transporter.sendMail(option, function(error, response){ if(error){ return res.status(500).send({message: 'Send email failed'}); }else{ return res.status(200).send({message: 'Send email success'}); } }); } } module.exports = { sendMail: mailController.sendMail };
27.090909
112
0.599832
36c889cd2304efc4dbc8be6e7d020a4f19c57541
317
js
JavaScript
aulas/aula 20 - DO WHILE/script.js
marioarl/javascript-cfbcursos
f06efba05803cb560c1a52de474198d46d697223
[ "MIT" ]
1
2021-11-26T19:39:12.000Z
2021-11-26T19:39:12.000Z
aulas/aula 20 - DO WHILE/script.js
marioarl/javascript-cfbcursos
f06efba05803cb560c1a52de474198d46d697223
[ "MIT" ]
null
null
null
aulas/aula 20 - DO WHILE/script.js
marioarl/javascript-cfbcursos
f06efba05803cb560c1a52de474198d46d697223
[ "MIT" ]
null
null
null
var num=5; while(num<10){ document.write("CFB Cursos<br>") num++; } document.write("<hr>") do { //Garantia de execucao de pelo menos 1 vez dos comandos do bloco document.write("CFB Cursos<br>") num++; }while(num<10); //O WHILE primeiro testa e depois faz os comandos, o DO WHILE faz os comandos e depois testa
22.642857
92
0.697161
36c974e97b3d47ce19e924d129ab7687df476033
3,447
js
JavaScript
challenges/ransomNote.js
JamesLeggero/100_Days
978c8ff7d9d31fd795d4412452fe585ec16e5792
[ "MIT" ]
null
null
null
challenges/ransomNote.js
JamesLeggero/100_Days
978c8ff7d9d31fd795d4412452fe585ec16e5792
[ "MIT" ]
null
null
null
challenges/ransomNote.js
JamesLeggero/100_Days
978c8ff7d9d31fd795d4412452fe585ec16e5792
[ "MIT" ]
null
null
null
/* Harold is a kidnapper who wrote a ransom note, but now he is worried it will be traced back to him through his handwriting. He found a magazine and wants to know if he can cut out whole words from it and use them to create an untraceable replica of his ransom note. The words in his note are case-sensitive and he must use only whole words available in the magazine. He cannot use substrings or concatenation to create the words he needs. Given the words in the magazine and the words in the ransom note, print Yes if he can replicate his ransom note exactly using whole words from the magazine; otherwise, print No. For example, the note is "Attack at dawn". The magazine contains only "attack at dawn". The magazine has all the right words, but there's a case mismatch. The answer is No. Function Description Complete the checkMagazine function in the editor below. It must print yes if the note can be formed using the magazine, or No. checkMagazine has the following parameters: magazine: an array of strings, each a word in the magazine note: an array of strings, each a word in the ransom note Input Format The first line contains two space-separated integers, m and n, the numbers of words in the magazine and the note. The second line contains m space-separated strings, each magazine[i]. The third line contains n space-separated strings, each note[i]. Constraints 1 <= m, n <= 30000 1 <= |magazine[i]|, |note[i]| <= 5 Each word consists of English alphabetic letters (i.e., a to z and A to Z). Output Format Print Yes if he can use the magazine to create an untraceable replica of his ransom note. Otherwise, print No. Sample Input 0 6 4 give me one grand today night give one grand today Sample Output 0 Yes Sample Input 1 6 5 two times three is not four two times two is four Sample Output 1 No Explanation 1 'two' only occurs once in the magazine. Sample Input 2 7 4 ive got a lovely bunch of coconuts ive got some coconuts Sample Output 2 No Explanation 2 Harold's magazine is missing the word 'some'. */ 'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', function() { inputString = inputString.replace(/\s*$/, '') .split('\n') .map(str => str.replace(/\s*$/, '')); main(); }); function readLine() { return inputString[currentLine++]; } // Complete the checkMagazine function below. function checkMagazine(magazine, note) { function inMag(word) { for (let i = 0; i < magazine.length; i++) { if (word === magazine[i]) { return i } } return false } function noteTest(words) { for (let i = 0; i < words.length; i++){ if (inMag(words[i]) === false) { // console.log(words[i], 'not found in mag') console.log('No') return } else { magazine.splice(inMag(words[i]), 1) } } console.log('Yes') return } noteTest(note) } function main() { const mn = readLine().split(' '); const m = parseInt(mn[0], 10); const n = parseInt(mn[1], 10); const magazine = readLine().split(' '); const note = readLine().split(' '); checkMagazine(magazine, note); }
25.533333
438
0.663185
36cb02c2c06c498a5ee5af8bb215c4c15dbf8805
15,528
js
JavaScript
tests/unit/services/elide-test.js
www-jrtorres042-github-enterprise-org/git_microsoft-powershell_achived-credential_tracking-scans_covid-19_dashboard-diff-1
fd39399b838e5a3ce82528d4da0e91b01125084c
[ "Apache-2.0" ]
40
2020-04-22T21:06:37.000Z
2022-02-21T10:02:58.000Z
tests/unit/services/elide-test.js
www-jrtorres042-github-enterprise-org/git_microsoft-powershell_achived-credential_tracking-scans_covid-19_dashboard-diff-1
fd39399b838e5a3ce82528d4da0e91b01125084c
[ "Apache-2.0" ]
6
2020-04-27T15:37:02.000Z
2020-07-19T17:22:45.000Z
tests/unit/services/elide-test.js
www-jrtorres042-github-enterprise-org/git_microsoft-powershell_achived-credential_tracking-scans_covid-19_dashboard-diff-1
fd39399b838e5a3ce82528d4da0e91b01125084c
[ "Apache-2.0" ]
10
2020-05-01T07:33:07.000Z
2022-01-04T07:46:56.000Z
import { module, test } from 'qunit'; import { setupTest } from 'ember-qunit'; import setupMirage from 'ember-cli-mirage/test-support/setup-mirage'; module('Unit | Service | elide', function (hooks) { setupTest(hooks); setupMirage(hooks); hooks.beforeEach(function () { this.service = this.owner.lookup('service:elide'); }); test('it exists', function (assert) { assert.ok(this.service); }); test('_buildUrl - search', function (assert) { const { service } = this; const actualUrl = service._buildUrl('counties', { search: { label: 'Cham' }, fields: { counties: ['id', 'label'], parents: ['label'] }, include: ['parents'], }); assert.equal( actualUrl.toString(), 'https://covid19.knowledge.yahoo.com/api/json/v1/counties?fields%5Bcounties%5D=id%2Clabel&fields%5Bparents%5D=label&filter=label%3D%3D%27*Cham*%27&include=parents&page%5Boffset%5D=0&page%5Blimit%5D=4000', '_buildSearchUrl build a url given a request' ); }); test('_buildFetchUrl - in list', function (assert) { const { service } = this; const actualUrl = service._buildUrl('counties', { isIn: { label: ['Champaign County, Illinois'], 'parents.id': [123], }, fields: { place: ['id', 'label'], parents: ['label'] }, include: ['parents'], }); assert.equal( actualUrl.toString(), 'https://covid19.knowledge.yahoo.com/api/json/v1/counties?fields%5Bplace%5D=id%2Clabel&fields%5Bparents%5D=label&filter=label%3Din%3D%28%27Champaign+County%5C%2C+Illinois%27%29%3Bparents.id%3Din%3D%28%27123%27%29&include=parents&page%5Boffset%5D=0&page%5Blimit%5D=4000', '_buildSearchUrl build a url given a request' ); }); test('_buildFetchUrl - null & eq', function (assert) { const { service } = this; const actualUrl = service._buildUrl('healthRecords', { eq: { referenceDate: '2020-04-03T00:00Z' }, isNull: ['dataSource'], }); assert.equal( actualUrl.toString(), 'https://covid19.knowledge.yahoo.com/api/json/v1/healthRecords?filter=referenceDate%3D%3D%272020-04-03T00%3A00Z%27%3BdataSource%3Disnull%3Dtrue&page%5Boffset%5D=0&page%5Blimit%5D=4000', '_buildSearchUrl builds a url given a request' ); }); test('_buildFetchUrl - gt, lt, ge & le', function (assert) { const { service } = this; const actualUrl = service._buildUrl('healthRecords', { gt: { referenceDate: '2020-04-03T00:00Z' }, ge: { referenceDate: '2020-04-04T00:00Z' }, lt: { referenceDate: '2020-05-01T00:00Z' }, le: { referenceDate: '2020-04-30T00:00Z' }, }); assert.equal( actualUrl.toString(), 'https://covid19.knowledge.yahoo.com/api/json/v1/healthRecords?filter=referenceDate%3Dlt%3D2020-05-01T00%3A00Z%3BreferenceDate%3Dgt%3D2020-04-03T00%3A00Z%3BreferenceDate%3Dle%3D2020-04-30T00%3A00Z%3BreferenceDate%3Dge%3D2020-04-04T00%3A00Z&page%5Boffset%5D=0&page%5Blimit%5D=4000', '_buildSearchUrl builds a url given a request' ); }); test('fetch - by id', async function (assert) { const { service } = this; const actualData = await service.fetch.perform('places', { isIn: { id: ['Champaign_County,_Illinois'] }, include: ['parents'], }); assert.deepEqual( actualData, { data: [ { type: 'places', id: 'Champaign_County,_Illinois', attributes: { type: 'places', label: 'Champaign County, Illinois', latitude: 40.13986, longitude: -88.19619, placeType: 'CountyAdminArea', population: 209689, wikiId: 'Champaign_County,_Illinois', childrenIds: [], }, relationships: { children: { data: [], }, parents: { data: [ { type: 'places', id: 'Illinois', }, ], }, }, }, ], included: [ { type: 'places', id: 'Illinois', attributes: { type: 'places', label: 'Illinois', latitude: 40.06446, longitude: -89.19884, placeType: 'StateAdminArea', population: 12671821, wikiId: 'Illinois', childrenIds: [ 'DuPage_River', 'Lee_County,_Illinois', 'Bond_County,_Illinois', 'Cass_County,_Illinois', 'Clay_County,_Illinois', 'Cook_County,_Illinois', 'Ford_County,_Illinois', 'Kane_County,_Illinois', 'Knox_County,_Illinois', 'Lake_County,_Illinois', 'Ogle_County,_Illinois', 'Pike_County,_Illinois', 'Pope_County,_Illinois', 'Will_County,_Illinois', 'Adams_County,_Illinois', 'Boone_County,_Illinois', 'Brown_County,_Illinois', 'Clark_County,_Illinois', 'Coles_County,_Illinois', 'Edgar_County,_Illinois', 'Henry_County,_Illinois', 'Logan_County,_Illinois', 'Macon_County,_Illinois', 'Mason_County,_Illinois', 'Perry_County,_Illinois', 'Piatt_County,_Illinois', 'Scott_County,_Illinois', 'Stark_County,_Illinois', 'Union_County,_Illinois', 'Wayne_County,_Illinois', 'White_County,_Illinois', 'Bureau_County,_Illinois', 'DeKalb_County,_Illinois', 'DeWitt_County,_Illinois', 'Fulton_County,_Illinois', 'Greene_County,_Illinois', 'Grundy_County,_Illinois', 'Hardin_County,_Illinois', 'Jasper_County,_Illinois', 'Jersey_County,_Illinois', 'Marion_County,_Illinois', 'Massac_County,_Illinois', 'McLean_County,_Illinois', 'Menard_County,_Illinois', 'Mercer_County,_Illinois', 'Monroe_County,_Illinois', 'Morgan_County,_Illinois', 'Peoria_County,_Illinois', 'Putnam_County,_Illinois', 'Saline_County,_Illinois', 'Shelby_County,_Illinois', 'Wabash_County,_Illinois', 'Warren_County,_Illinois', 'Calhoun_County,_Illinois', 'Carroll_County,_Illinois', 'Clinton_County,_Illinois', 'Douglas_County,_Illinois', 'Edwards_County,_Illinois', 'Fayette_County,_Illinois', 'Hancock_County,_Illinois', 'Jackson_County,_Illinois', 'Johnson_County,_Illinois', 'Kendall_County,_Illinois', 'LaSalle_County,_Illinois', 'Madison_County,_Illinois', 'McHenry_County,_Illinois', 'Pulaski_County,_Illinois', 'Crawford_County,_Illinois', 'Franklin_County,_Illinois', 'Gallatin_County,_Illinois', 'Hamilton_County,_Illinois', 'Iroquois_County,_Illinois', 'Kankakee_County,_Illinois', 'Lawrence_County,_Illinois', 'Macoupin_County,_Illinois', 'Marshall_County,_Illinois', 'Moultrie_County,_Illinois', 'Randolph_County,_Illinois', 'Richland_County,_Illinois', 'Sangamon_County,_Illinois', 'Schuyler_County,_Illinois', 'Tazewell_County,_Illinois', 'Woodford_County,_Illinois', 'Alexander_County,_Illinois', 'Champaign_County,_Illinois', 'Christian_County,_Illinois', 'Effingham_County,_Illinois', 'Henderson_County,_Illinois', 'Jefferson_County,_Illinois', 'McDonough_County,_Illinois', 'St._Clair_County,_Illinois', 'Vermilion_County,_Illinois', 'Whiteside_County,_Illinois', 'Winnebago_County,_Illinois', 'Cumberland_County,_Illinois', 'Jo_Daviess_County,_Illinois', 'Livingston_County,_Illinois', 'Montgomery_County,_Illinois', 'Stephenson_County,_Illinois', 'Washington_County,_Illinois', 'Williamson_County,_Illinois', 'Rock_Island_County,_Illinois', ], }, relationships: { children: { data: [], }, parents: { data: [ { type: 'places', id: 'United_States', }, ], }, }, }, ], }, 'fetch can return data for a request' ); }); test('fetch - search', async function (assert) { const { service } = this; const actualData = await service.fetch.perform('places', { search: { label: ['Denma'] }, }); assert.deepEqual( actualData, { data: [ { type: 'places', id: 'Denmark', attributes: { type: 'places', label: 'Denmark', placeType: 'Country', latitude: 56.27609, longitude: 9.51695, population: 5793636, wikiId: 'Denmark', childrenIds: [], }, relationships: { children: { data: [], }, parents: { data: [ { type: 'places', id: 'Earth', }, ], }, }, }, ], }, 'fetch can return data for a search request' ); }); test('fetch - no options', async function (assert) { const { service } = this; const actualData = await service.fetch.perform('metadata'); assert.deepEqual( actualData, { data: [ { attributes: { healthRecordsEndDate: '2020-04-03T00:00Z', healthRecordsStartDate: '2020-04-03T00:00Z', publishedDate: '2020-04-03T03:00Z', }, id: 'info', type: 'metadata', }, ], }, 'fetch can return data with no request options' ); }); test('fetch - relationship field filter', async function (assert) { const { service } = this; const actualData = await service.fetch.perform('latestHealthRecords', { eq: { 'place.wikiId': 'Italy' }, }); assert.deepEqual( actualData, { data: [ { type: 'latest-health-records', id: 'df1d490f-b313-39af-bcd1-2e747e8765e8', attributes: { dataSource: 'http://www.salute.gov.it/', label: 'Italy', latitude: 42.50382, longitude: 12.57347, numDeaths: null, numRecoveredCases: null, numTested: null, referenceDate: '2020-05-01T00:00Z', totalConfirmedCases: 205463, totalDeaths: 27967, totalRecoveredCases: 75945, totalTestedCases: 1979217, type: 'latestHealthRecords', wikiId: 'Italy', }, relationships: { place: { data: { type: 'places', id: 'Italy', }, }, }, }, ], }, 'fetch can filter on relationship fields' ); }); test('fetch - to many relationship filter', async function (assert) { const { service } = this; const actualData = await service.fetch.perform('latestHealthRecords', { eq: { 'place.parents.id': 'Earth' }, }); assert.deepEqual(actualData.data.length, 23, 'fetch can filter on relationship fields'); assert.deepEqual( actualData.data.find((r) => r.attributes.label === 'United States'), { attributes: { dataSource: 'https://www.ecdc.europa.eu/', label: 'United States', latitude: 37.16793, longitude: -95.84502, numDeaths: null, numRecoveredCases: null, numTested: null, referenceDate: '2020-05-01T00:00Z', totalConfirmedCases: 1069826, totalDeaths: 63006, totalRecoveredCases: null, totalTestedCases: null, type: 'latestHealthRecords', wikiId: 'United_States', }, id: '0a5e3287-5fd4-391e-869c-9096491b5c46', relationships: { place: { data: { id: 'United_States', type: 'places', }, }, }, type: 'latest-health-records', }, 'fetch can filter on relationship fields' ); }); test('fetch - escaped filter values', async function (assert) { const { service } = this; const actualData = await service.fetch.perform('places', { eq: { id: 'Autauga_County,_Alabama' }, }); assert.deepEqual( actualData, { data: [ { type: 'places', id: 'Autauga_County,_Alabama', attributes: { type: 'places', label: 'Autauga County, Alabama', latitude: 32.50771, longitude: -86.66611, placeType: 'CountyAdminArea', population: 55869, wikiId: 'Autauga_County,_Alabama', childrenIds: [], }, relationships: { children: { data: [], }, parents: { data: [ { type: 'places', id: 'Alabama', }, ], }, }, }, ], }, 'fetch can return data with escaped filter values' ); }); test('trace id', async function (assert) { assert.expect(3); const { service } = this; let stateTraceID, countyTraceID; this.server.get('https://covid19.knowledge.yahoo.com/api/json/v1/counties', function (db, req) { countyTraceID = req.requestHeaders['x-trace-id']; assert.ok(countyTraceID, 'A unique id is generated per request'); }); this.server.get('https://covid19.knowledge.yahoo.com/api/json/v1/states', function (db, req) { stateTraceID = req.requestHeaders['x-trace-id']; assert.ok(stateTraceID, 'A unique id is generated per request'); }); await service.fetch.perform('counties', { eq: { wikiId: 'Autauga_County,_Alabama' } }); await service.fetch.perform('states', { eq: { wikiId: 'Alabama' } }); assert.notEqual(stateTraceID, countyTraceID, 'The headers have unique ids'); }); });
33.61039
287
0.510819
36cb6deb0f0bbe1166f7bca4a8a58eedcd739c8c
108
js
JavaScript
test.js
nathan7/concur
8dfe7ef37a42f50bf63db23766f96027fd458080
[ "ISC" ]
1
2016-07-19T21:09:39.000Z
2016-07-19T21:09:39.000Z
test.js
nathan7/concur
8dfe7ef37a42f50bf63db23766f96027fd458080
[ "ISC" ]
null
null
null
test.js
nathan7/concur
8dfe7ef37a42f50bf63db23766f96027fd458080
[ "ISC" ]
null
null
null
'use strict' module.exports = require('has-generators') ? require('./test.es6') : require('./test.es5')
21.6
42
0.648148
36cc37e0662c08f2d51510de75384a84eb8d8c19
3,122
js
JavaScript
build/g-yaxislinear.js
ft-interactive/g-yAxisLinear
3b852fcadd0d88b328549bc12c5cd4ed5b7a64cf
[ "BSD-3-Clause" ]
3
2021-04-18T17:38:50.000Z
2021-04-29T20:00:28.000Z
sankey-2018/local-assets/g-yaxislinear.js
AdrianMayron/visual-vocabulary-templates
d590a50620dbf8a0c88aeaa985ff6a8f76724b91
[ "MIT" ]
null
null
null
sankey-2018/local-assets/g-yaxislinear.js
AdrianMayron/visual-vocabulary-templates
d590a50620dbf8a0c88aeaa985ff6a8f76724b91
[ "MIT" ]
null
null
null
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('d3')) : typeof define === 'function' && define.amd ? define(['exports', 'd3'], factory) : (factory((global.gAxis = global.gAxis || {}),global.d3)); }(this, function (exports,d3) { 'use strict'; function yaxisLinear() { let yScale = d3.scaleLinear() .domain([0,10000]) .range([120,0]) let tickAlign = "right" let labelWidth = 0; let tickSize = 300; let yAxisHighlight = 0; let numTicks = 5 function axis(parent) { const yAxis =getAxis(tickAlign) .ticks(numTicks) .scale(yScale) const yLabel = parent.append("g") .attr("class","axis yAxis") .call(yAxis) //Calculate width of widest .tick text parent.selectAll(".yAxis text").each( function(){ labelWidth=Math.max(this.getBBox().width,labelWidth); }) //Use this to amend the tickSIze and re cal the vAxis yLabel.call(yAxis.tickSize(tickSize-labelWidth)) //position label on right hand axis if(tickAlign=="right") { yLabel.selectAll("text") .attr("dx",labelWidth) } //translate if a left axis if (tickAlign=="left") { yLabel.attr("transform","translate("+(tickSize-labelWidth)+","+0+")") } //identify 0 line if there is one let originValue = 0; let origin = yLabel.selectAll(".tick").filter(function(d, i) { return d==originValue || d==yAxisHighlight; }).classed("baseline",true); } axis.yScale = (d)=>{ yScale = d; return axis; } axis.domain = (d)=>{ yScale.domain(d); return axis; }; axis.range = (d)=>{ yScale.range(d); return axis; }; axis.tickAlign = (d)=>{ tickAlign=d; return axis; } axis.labelWidth = (d)=>{ if(d===undefined) return labelWidth labelWidth=d; return axis; } axis.tickSize = (d)=>{ if(d===undefined) return tickSize tickSize=d; return axis; } axis.yAxisHighlight = (d)=>{ yAxisHighlight = d; return axis; } axis.numTicks = (d)=>{ numTicks = d; return axis; } axis.tickAlign = (d)=>{ if(!d) return tickAlign; tickAlign = d; return axis; } return axis function getAxis(alignment){ return{ "left": d3.axisLeft(), "right":d3.axisRight() }[alignment] } }; exports.yaxisLinear = yaxisLinear; Object.defineProperty(exports, '__esModule', { value: true }); }));
29.45283
100
0.473414
36cd2362ea828b656373a3477020b4f83d9bdfd6
402
js
JavaScript
web-frameworks-exercise5/exercise5_APP/src/components/SearchView.js
Danskutin/Web-frameworks-exercises-return
33f122ae016739d387bfe277d8266c51d7eac792
[ "MIT" ]
null
null
null
web-frameworks-exercise5/exercise5_APP/src/components/SearchView.js
Danskutin/Web-frameworks-exercises-return
33f122ae016739d387bfe277d8266c51d7eac792
[ "MIT" ]
null
null
null
web-frameworks-exercise5/exercise5_APP/src/components/SearchView.js
Danskutin/Web-frameworks-exercises-return
33f122ae016739d387bfe277d8266c51d7eac792
[ "MIT" ]
null
null
null
import React from 'react'; import styles from './SearchView.module.css'; import SearchResult from './SearchResult'; export default function SearchView(props) { console.log("Searchview" + JSON.stringify(props)) return ( <div> <div className={ styles.showProducts }> { props.items.map(item => <SearchResult key={item.id} {...item} />) } </div> </div> ) }
21.157895
73
0.621891
36d1546fc609fd8402479a684a2e39e1a20f29c2
97
js
JavaScript
_moving/runtime/dist/included/skylark-spa/uncompressed/skylark-spa/main.js
skylarkjs/skylark
7b45f1630bd6b7f0bc55cff2d243ec4b7fc121cb
[ "MIT" ]
30
2017-08-26T11:53:18.000Z
2020-03-18T14:39:10.000Z
_moving/runtime/dist/included/skylark-spa/uncompressed/skylark-spa/main.js
skylarkjs/skylark
7b45f1630bd6b7f0bc55cff2d243ec4b7fc121cb
[ "MIT" ]
2
2021-01-28T21:15:39.000Z
2022-03-25T19:09:36.000Z
_moving/runtime/dist/included/skylark-spa/uncompressed/skylark-spa/main.js
skylarkjs/skylark
7b45f1630bd6b7f0bc55cff2d243ec4b7fc121cb
[ "MIT" ]
8
2017-09-04T00:45:40.000Z
2021-06-10T06:04:57.000Z
define([ "skylark-langx/skylark", "./spa" ], function(skylark) { return skylark; });
13.857143
28
0.57732
36d1849ff476c1b49df1ccb6c85c5155aec6afa1
638
js
JavaScript
src/libs/Detector.js
scottdarby/symphony-2
543530903fe19584ed41e063c37caf966c04a79d
[ "Apache-2.0" ]
118
2019-07-03T01:44:01.000Z
2022-02-19T14:16:51.000Z
src/libs/Detector.js
scottdarby/symphony-2
543530903fe19584ed41e063c37caf966c04a79d
[ "Apache-2.0" ]
8
2020-09-07T01:38:50.000Z
2022-03-08T23:05:36.000Z
src/libs/Detector.js
scottdarby/symphony-2
543530903fe19584ed41e063c37caf966c04a79d
[ "Apache-2.0" ]
17
2019-07-11T06:29:52.000Z
2022-03-01T14:59:44.000Z
export default class Detector { constructor () { this.prefixes = 'Webkit Moz O ms'.split(' ') this.ua = (navigator.userAgent || navigator.vendor || window.opera).toLowerCase() this.isRetina = window.devicePixelRatio && window.devicePixelRatio >= 1.5 this.isChrome = this.ua.indexOf('chrome') > -1 this.isFirefox = this.ua.indexOf('firefox') > -1 this.isSafari = this.ua.indexOf('safari') > -1 this.isEdge = this.ua.indexOf('edge') > -1 this.isIE = this.ua.indexOf('msie') > -1 this.isMobile = /(iPad|iPhone|Android)/i.test(this.ua) this.isIOS = /(iPad|iPhone)/i.test(this.ua) } }
42.533333
86
0.637931
36d372622b720de3f57881515c64a5b758dae532
892
js
JavaScript
core/runtime/android/runtime/src/main/assets/app/card.js
jianghai33/hapjs
4c8a53bef25663c139d55beed29783cdfe936088
[ "Apache-2.0" ]
54
2022-01-20T07:38:08.000Z
2022-03-24T06:31:55.000Z
core/runtime/android/runtime/src/main/assets/app/card.js
jianghai33/hapjs
4c8a53bef25663c139d55beed29783cdfe936088
[ "Apache-2.0" ]
12
2022-01-20T09:31:28.000Z
2022-03-31T09:55:39.000Z
core/runtime/android/runtime/src/main/assets/app/card.js
jianghai33/hapjs
4c8a53bef25663c139d55beed29783cdfe936088
[ "Apache-2.0" ]
20
2022-01-20T07:34:05.000Z
2022-03-30T06:18:00.000Z
/* * Copyright (c) 2021, the hapjs-platform Project Contributors * SPDX-License-Identifier: Apache-2.0 */ !function () { if ("undefined" == typeof window) (function (e) { var p = {}; function t (o) { if (p[o])return p[o].exports; var n = p[o] = {exports: {}, id: o, loaded: !1}; return e[o].call(n.exports, n, n.exports, t), n.loaded = !0, n.exports } t.m = e, t.c = p, t.p = "", t(0) })({ 0: function (e, p, t) { var o = t(142); $app_define$("@app-application/app", [], function (e, p, t) { o(t, p, e), p.__esModule && p.default && (t.exports = p.default) }), $app_bootstrap$("@app-application/app", {packagerVersion: "0.0.5"}) }, 142: function (e, p) { e.exports = function (e, p, t) { "use strict"; Object.defineProperty(p, "__esModule", {value: !0}), p.default = {} } } }) }();
30.758621
77
0.516816
36d40a657a5bc6520809aaa0a2f11023f9cb5217
4,923
js
JavaScript
src/containers/NewsList/NewsList.js
QmoGamer/react-front-end-forum
d98494573634c0552fc4d85880bf0d07b126d523
[ "MIT" ]
null
null
null
src/containers/NewsList/NewsList.js
QmoGamer/react-front-end-forum
d98494573634c0552fc4d85880bf0d07b126d523
[ "MIT" ]
null
null
null
src/containers/NewsList/NewsList.js
QmoGamer/react-front-end-forum
d98494573634c0552fc4d85880bf0d07b126d523
[ "MIT" ]
null
null
null
import React, { Component, PropTypes } from 'react' import { connect } from 'react-redux' import { Link } from 'react-router' import styles from './NewsList.css' import { apiGetNewsList } from '../../actions/news' import { isEmpty, yyyymmdd } from '../../utils' import Loader from '../../components/Loader/Loader' const constants = require('../../constants') import IconTitle from '../../components/IconTitle/IconTitle' import BtnPage from '../../components/BtnPage/BtnPage' class NewsList extends Component { static fetchData({ params, store, url }) { // return store.dispatch( fetchPackage(url, params.name) ) } constructor (props) { super(props) this.state = { loading: 1 } } componentDidMount () { let member_cookie = window.sessionStorage.getItem("cookie") || '' let auth_token = window.sessionStorage.getItem("token") || '' this.props.dispatch( apiGetNewsList( location.origin, this.props.params.page, member_cookie, auth_token ) ) } componentWillReceiveProps (nextProps) { // console.log("will"); if( nextProps.params.page != this.props.params.page ) { this.setState({ loading: 1 }) let member_cookie = this.props.member.member_status == 2 ? this.props.member.member_info.member_cookie : '' let auth_token = this.props.member.member_status == 2 ? this.props.member.member_info.token : '' this.props.dispatch( apiGetNewsList( location.origin, nextProps.params.page, member_cookie, auth_token ) ) } } componentDidUpdate (prevProps, prevState) { if( prevProps.news.news_list != this.props.news.news_list && this.state.loading == 1 ) { this.setState({ loading: 0 }) } } renderNewsList ( news ) { let render = <Loader /> if( news != undefined && this.state.loading == 0 ) { if ( news.content != null && news.content.length != 0 ) render = news.content.map((x, y)=>{ // console.log(x); let type = x.issticky == 0 ? <div className="fa fa-home">{ x.type }</div> : <div className="fa fa-home" style={{color: "#f00"}}><font color="#f00">{ x.type }置頂</font></div> let likes = x.type != '公告' ? <span>{x.like_count}<span className={ styles.likes }>讚</span></span> : null let follows = x.type != '公告' ? <span>{x.collected_count}<span className={ styles.follows }>收藏</span></span> : null return ( <div key={"news_"+y} className={ styles.rows }> <div style={{flex: 2}} className={ styles.post_date }> <div>{ yyyymmdd(x.post_time) }</div> { type } </div> <div style={{flex: 10, display: "flex"}}> <div></div> <div style={{flex: 8}} className={ styles.flex_box_1 }> <div style={{ flex: 6 }} className={"ellipsis " + styles.title }> <a href={"/news_detail/" + x.id }>{ x.title }</a> </div> <div style={{ flex: 2 }} className={ styles.likes_row }> <div style={{ flex: 1 }}>{ likes }</div> <div style={{ flex: 1 }}>{ follows }</div> </div> </div> <div style={{flex: 2}}></div> </div> </div> ) }) else { render = <div className={ styles.rows }>{ constants.VIEW_TEXT_NEWS_LIST_1 }</div> } } return render } renderPaging ( news ) { let render = <Loader /> if ( news != undefined ) render = <BtnPage page={parseInt(news.page)} total_page={parseInt(news.total_page)} path="/news_list" /> return render } render() { // console.log(this.props); const { news } = this.props const page = this.props.params.page return ( <div className={ styles.news_list }> <div className="breadcrumb"> <IconTitle icon_classname="fa fa-home" title="首頁 > 新聞與公告" /> </div> <div> <div className={ styles.bg }> <div className={ styles.border }> <div className={ styles.rows + " " + styles.header }> <div style={{flex: 2}}>發文日期</div> <div></div> <div style={{flex: 6}}>標題</div> <div style={{flex: 1, textAlign: "center"}}>讚</div> <div style={{flex: 1, textAlign: "center"}}>收藏</div> <div style={{flex: 2}}></div> </div> { this.renderNewsList( news.news_list ) } <div className={ styles.rows_btn }> { this.renderPaging( news.news_list ) } </div> </div> </div> </div> </div> ) } } function mapStateToProps(state) { // console.log(state) return { member: state.member, news: state.news // news_paging: state.toggleSidebar, } } export default connect(mapStateToProps)(NewsList)
33.951724
182
0.554946
36d43927b451bf739aed1ff0988d5be69c8ce857
994
js
JavaScript
app/js/arethusa.core/services/locator.js
perseids-project/arethusa
17cb98b995d20a163ad26843d984f04b343bb752
[ "MIT" ]
22
2015-07-21T16:47:21.000Z
2021-12-22T02:10:59.000Z
app/js/arethusa.core/services/locator.js
perseids-project/arethusa
17cb98b995d20a163ad26843d984f04b343bb752
[ "MIT" ]
147
2015-07-15T13:53:45.000Z
2022-03-02T12:21:11.000Z
app/js/arethusa.core/services/locator.js
perseids-project/arethusa
17cb98b995d20a163ad26843d984f04b343bb752
[ "MIT" ]
20
2015-07-21T16:49:51.000Z
2021-11-12T20:35:30.000Z
'use strict'; // deprecated for now // but still in use, no? /** * This service wraps url parameters for routed views and * provides a unified access to url- and manually-set parameters */ angular.module('arethusa.core').service('locator', [ '$location', function ($location) { var noUrlParams; var manualParams = {}; /** * Acess parameters by name * @param name * @returns {*} */ this.get = function(name) { return noUrlParams ? manualParams[name] : $location.search()[name]; }; /** * Toggle url- or manually-set parameters * @param bool */ this.watchUrl = function(bool) { noUrlParams = !bool; }; /** * Manually set parameters. * @param paramOrParams * @param value */ this.set = function(paramOrParams, value) { if (value) { manualParams[paramOrParams] = value; } else { angular.extend(manualParams, paramOrParams); } }; } ]);
21.608696
73
0.580483
36d54293aa63cfad18e4ccbbe1ce9ca70f58830b
4,238
js
JavaScript
public/js/customize.js
hieu221096/laravel
b1d5153b94e7848a86f8271431382ac92faee20e
[ "MIT" ]
null
null
null
public/js/customize.js
hieu221096/laravel
b1d5153b94e7848a86f8271431382ac92faee20e
[ "MIT" ]
null
null
null
public/js/customize.js
hieu221096/laravel
b1d5153b94e7848a86f8271431382ac92faee20e
[ "MIT" ]
null
null
null
function initMap() { clearStorage(localStorage.getItem('click')); const myLatlng = { lat: 38.2682, lng: 140.8694 }; let markers = []; var click = 0; const directionsService = new google.maps.DirectionsService(); const directionsRenderer = new google.maps.DirectionsRenderer(); const geocoder = new google.maps.Geocoder(); const map = new google.maps.Map(document.getElementById("map"), { zoom: 6, center: myLatlng, }); // Create the initial InfoWindow. let infoWindow = new google.maps.InfoWindow({ content: '', position: myLatlng, }); infoWindow.open(map); // Configure the click listener. map.addListener("click", (mapsMouseEvent) => { click = click + 1; // Close the current InfoWindow. infoWindow.close(); // Create a new InfoWindow. infoWindow = new google.maps.InfoWindow({ position: mapsMouseEvent.latLng, }); //create maker var marker = new google.maps.Marker({ position: mapsMouseEvent.latLng, map: map, draggable:true, title: click.toString(), }); markers.push(marker); //get lat long from marker const lat = marker.getPosition().lat(); const lng = marker.getPosition().lng(); //handle get address from lat long geocodeLatLng(geocoder, map, infoWindow, lat, lng, click); localStorage.setItem('click',click); //get lat long when dragable maker google.maps.event.addListener(marker, 'dragend', function(evt){ //handle event move maker var marker_rm = this.getTitle(); const new_lat = this.getPosition().lat(); const new_lng = this.getPosition().lng(); geocodeLatLng(geocoder, map, infoWindow, new_lat, new_lng, marker_rm); }); // direction document.getElementById("submit").addEventListener("click", () => { var rs = calculateAndDisplayRoute(directionsService, directionsRenderer, click, markers); if(rs == false){ window.alert("No have any way"); } }); directionsRenderer.setMap(map); }); } function calculateAndDisplayRoute(directionsService, directionsRenderer, click, markers) { const waypts = []; var errors = false; if(click > 2){ for (var i = 2; i < click; i++) { waypts.push({ location: localStorage.getItem('maker'+i+''), stopover: true, }); } } directionsService.route( { origin: localStorage.getItem('maker1'), destination: localStorage.getItem('maker'+click+''), waypoints: waypts, optimizeWaypoints: true, travelMode: google.maps.TravelMode.DRIVING, }, (response, status) => { if (status === "OK" && response) { directionsRenderer.setDirections(response); const route = response.routes[0]; const summaryPanel = document.getElementById("directions-panel"); summaryPanel.innerHTML = ""; // For each route, display summary information. for (let i = 0; i < route.legs.length; i++) { const routeSegment = i + 1; summaryPanel.innerHTML += "<h5><b>Trip : " + routeSegment + "</b></h5> From : "; summaryPanel.innerHTML += route.legs[i].start_address + "<br> To : "; summaryPanel.innerHTML += route.legs[i].end_address + "<br> Distance : "; summaryPanel.innerHTML += route.legs[i].distance.text + "<br><br>"; } for (let i = 0; i < click; i++) { markers[i].setMap(null); } return true ; } else { return false ; } } ); } function geocodeLatLng(geocoder, map, infowindow , lat , lng, click) { var address; const latlng = { lat: parseFloat(lat), lng: parseFloat(lng), }; geocoder.geocode({ location: latlng }, (results, status) => { if (status === "OK") { if (results[0]) { localStorage.setItem('maker'+click+'',results[0].formatted_address); }else{ localStorage.setItem('maker'+click+'',''); } }else{ localStorage.setItem('maker'+click+'',''); } }); } function clearStorage(click){ if(click > 0){ for(var i = 1 ; i <= click ; i++){ localStorage.removeItem('maker'+i+''); } localStorage.removeItem('click'); } }
31.161765
95
0.607362
36d59974ae0e25e8dbdd1a1048a5cbb63c3cbf48
2,415
js
JavaScript
api/policies/auth.policy.js
liudonghua123/mmm_backend
4b91da74e684a2ba5428bc3bf5a77116ad5fd67c
[ "MIT" ]
null
null
null
api/policies/auth.policy.js
liudonghua123/mmm_backend
4b91da74e684a2ba5428bc3bf5a77116ad5fd67c
[ "MIT" ]
null
null
null
api/policies/auth.policy.js
liudonghua123/mmm_backend
4b91da74e684a2ba5428bc3bf5a77116ad5fd67c
[ "MIT" ]
null
null
null
const JWTService = require('../services/auth.service'); const mapping = require('../utils/CodeMessageMapping'); const hasPermission = (req, authority) => { console.info(`check permission for ${req.method}: ${req.path} with authority: ${authority}`); const adminRoutes = [ { method: 'GET', path: '^/api/private/users/$' }, { method: 'POST', path: '^/api/private/users/$' }, { method: 'DELETE', path: '^/api/private/users/$' }, { method: 'POST', path: '^/api/private/notifications/$' }, { method: 'PUT', path: '^/api/private/notifications/\\d+$' }, { method: 'DELETE', path: '^/api/private/notifications/$' }, ]; for (const adminRoute of adminRoutes) { // eg: "/api/private/notifications/1".match(new RegExp('/api/private/notifications/\\d+')) returns // ["/api/private/notifications/1", index: 0, input: "/api/private/notifications/1", groups: undefined] // otherwise return null if (req.method === adminRoute.method && req.path.match(new RegExp(adminRoute.path))) { return authority === 'admin'; } } return true; }; // usually: "Authorization: Bearer [token]" or "<url>?token=token" or "token: [token]" module.exports = (req, res, next) => { let tokenToVerify; if (req.header('Authorization')) { const parts = req.header('Authorization').split(' '); if (parts.length === 2) { const scheme = parts[0]; const credentials = parts[1]; if (/^Bearer$/.test(scheme)) { tokenToVerify = credentials; } else { return res.status(401).json({ ...mapping.authorization_format_error }); } } else { return res.status(401).json({ ...mapping.authorization_format_error }); } } else if (req.query.token) { tokenToVerify = req.query.token; } else if (req.body.token) { tokenToVerify = req.body.token; // delete req.query.token; } else { return res.status(401).json({ ...mapping.authorization_not_found }); } // console.info(`tokenToVerify: ${tokenToVerify}`); return JWTService().verify(tokenToVerify, (err, thisToken) => { if (err) return res.status(401).json({ ...mapping.invalid_token, err }); if (!hasPermission(req, thisToken.authority)) { return res.status(401).json({ ...mapping.authorization_privilege_not_sufficient }); } req.token = thisToken; // console.info(`thisToken: ${JSON.stringify(thisToken)}`); return next(); }); };
38.333333
107
0.631056
36d5d692701341081d97fdf15ac45cd168023be1
1,577
js
JavaScript
controllers/customer.controller.js
nestotusdev02/NodeJS_RestApi_MongoDB
7ab1bb01a385d9b12075db1a0d397c7d5d433147
[ "MIT" ]
null
null
null
controllers/customer.controller.js
nestotusdev02/NodeJS_RestApi_MongoDB
7ab1bb01a385d9b12075db1a0d397c7d5d433147
[ "MIT" ]
null
null
null
controllers/customer.controller.js
nestotusdev02/NodeJS_RestApi_MongoDB
7ab1bb01a385d9b12075db1a0d397c7d5d433147
[ "MIT" ]
null
null
null
const { Customer } = require('../models'); const { to, ReE, ReS } = require('../services/util.service'); const create = async function(req, res){ res.setHeader('Content-Type', 'application/json'); let err, customer; let user = req.user; let customer_info = req.body; customer_info.users = [{user:user._id}]; [err, customer] = await to(Customer.create(customer_info)); if(err) return ReE(res, err, 422); return ReS(res,{customer:customer.toWeb()}, 201); } module.exports.create = create; const getAll = async function(req, res){ res.setHeader('Content-Type', 'application/json'); [err, customers] = await to(Customer.find()); return ReS(res, {customers},201); } module.exports.getAll = getAll; const get = function(req, res){ res.setHeader('Content-Type', 'application/json'); let customer = req.customer; return ReS(res, {customer:customer.toWeb()}); } module.exports.get = get; const update = async function(req, res){ let err, customer, data; customer = req.user; data = req.body; customer.set(data); [err, customer] = await to(customer.save()); if(err){ return ReE(res, err); } return ReS(res, {customer:customer.toWeb()}); } module.exports.update = update; const remove = async function(req, res){ let customer, err; customer = req.customer; [err, customer] = await to(customer.remove()); if(err) return ReE(res, 'error occured trying to delete the customer'); return ReS(res, {message:'Deleted Customer'}, 204); } module.exports.remove = remove;
28.160714
75
0.654407
36d6564582fff835d6686c46cb6053f031c69882
8,780
js
JavaScript
dist/js/main.min.js
cuiyushuang/sort
cc8e5805b33c19644d983006e792f793d138b5e4
[ "Apache-2.0" ]
null
null
null
dist/js/main.min.js
cuiyushuang/sort
cc8e5805b33c19644d983006e792f793d138b5e4
[ "Apache-2.0" ]
null
null
null
dist/js/main.min.js
cuiyushuang/sort
cc8e5805b33c19644d983006e792f793d138b5e4
[ "Apache-2.0" ]
null
null
null
(function(l, i, v, e) { v = l.createElement(i); v.async = 1; v.src = '//' + (location.host || 'localhost').split(':')[0] + ':35729/livereload.js?snipver=1'; e = l.getElementsByTagName(i)[0]; e.parentNode.insertBefore(v, e)})(document, 'script'); (function () { 'use strict'; function __$styleInject(css, ref) { if ( ref === void 0 ) ref = {}; var insertAt = ref.insertAt; if (!css || typeof document === 'undefined') { return; } var head = document.head || document.getElementsByTagName('head')[0]; var style = document.createElement('style'); style.type = 'text/css'; if (insertAt === 'top') { if (head.firstChild) { head.insertBefore(style, head.firstChild); } else { head.appendChild(style); } } else { head.appendChild(style); } if (style.styleSheet) { style.styleSheet.cssText = css; } else { style.appendChild(document.createTextNode(css)); } } //动态生成数组 function num() { return Math.floor(Math.random() * 100 + 1); } function create(n) { var list = []; while (list.length < n) { var a = num(); var Onoff = true; for (var i = 0; i < list.length; i++) { if (list[i] == a) { Onoff = false; break; } else { Onoff = true; } } if (Onoff) { list.push(a); } } return list; } $('createArr').onclick = function () { var val1 = $('in').value; var val2 = $('import').value; if (val2) { var pcs = $('import').value.split(','); var arr = pcs; show(arr); } else { var _pcs = val1; var _arr = create(parseInt(_pcs)); show(_arr); } }; $('bubble').onclick = function () { BubbleSort(); }; //计算最大高度 function getMax(data) { var max = data[0]; for (var i in data) { if (data[i] > max) { max = data[i]; } } return max; } //获取元素 function $(id) { return document.getElementById(id); } function hasClass(elem, cls) { cls = cls || ''; if (cls.replace(/\s/g, '').length == 0) return false; //当cls没有参数时,返回false return new RegExp(' ' + cls + ' ').test(' ' + elem.className + ' '); } function addClass(ele, cls) { if (!hasClass(ele, cls)) { ele.className = ele.className == '' ? cls : ele.className + ' ' + cls; } } function removeClass(elem, cls) { if (hasClass(elem, cls)) { var newClass = ' ' + elem.className.replace(/[\t\r\n]/g, '') + ' '; while (newClass.indexOf(' ' + cls + ' ') >= 0) { newClass = newClass.replace(' ' + cls + ' ', ' '); } elem.className = newClass.replace(/^\s+|\s+$/g, ''); } } function sleep(ms) { return new Promise(function (resolve) { return setTimeout(resolve, ms); }); } //产生柱状图 function show(data) { var maxWidth = 800; var maxHeight = 450; var maxNum = getMax(data); //计算比例 var percent = maxHeight / maxNum; //柱子间隔 var space = maxWidth / (data.length * 2 + 1); var zhuWidth = 800 / (data.length * 2 + 1); var spaceWidth = 20; $('box').innerHTML = ''; //循环数据 for (var i = 0; i < data.length; i++) { var liDom = document.createElement('li'); liDom.style.width = space + 'px'; var left1 = (i + 1) * spaceWidth + i * zhuWidth; liDom.style.height = data[i] * percent + 'px'; liDom.innerHTML = data[i]; liDom.style.left = left1 + 'px'; $("box").appendChild(liDom); } } async function BubbleSort() { var arrC = []; var data = document.getElementsByTagName('li'); data = Array.apply(null, data); data.forEach(function (v, i) { arrC[i] = v.innerHTML; }); for (var i = 0; i < data.length; i++) { var tag = true; for (var j = 0; j < data.length - 1 - i; j++) { addClass(data[j], 'light'); addClass(data[j + 1], 'light'); if (parseInt(arrC[j]) > parseInt(arrC[j + 1])) { swap(data[j], data[j + 1]); var temp = data[j]; data[j] = data[j + 1]; data[j + 1] = temp; //更新数据数组 data.forEach(function (v, i) { arrC[i] = v.innerHTML; }); await sleep(1000); tag = false; } removeClass(data[j], 'light'); removeClass(data[j + 1], 'light'); } addClass(data[data.length - 1 - i], 'end'); if (tag) { for (var _i = 0; _i < data.length; _i++) { addClass(data[_i], 'end'); } break; } } } function swap(ele1, ele2) { var dis1 = ele1.offsetLeft; var dis2 = ele2.offsetLeft; var d1 = dis1; var d2 = dis2; var timer = setInterval(function () { if (dis1 < d2) { ele1.style.left = dis1++ + 'px'; } else { clearInterval(timer); } }, 10); var timer2 = setInterval(function () { if (d1 < dis2) { ele2.style.left = dis2-- + 'px'; } else { clearInterval(timer2); } }, 10); ele2.parentNode.insertBefore(ele2, ele1); } //动态生成数组 function num$1() { return Math.floor(Math.random() * 100 + 1); } function create$1(n) { var list = []; while (list.length < n) { var a = num$1(); var Onoff = true; for (var i = 0; i < list.length; i++) { if (list[i] == a) { Onoff = false; break; } else { Onoff = true; } } if (Onoff) { list.push(a); } } return list; } $$1('createArr').onclick = function () { var val1 = $$1('in').value; var val2 = $$1('import').value; if (val2) { var pcs = $$1('import').value.split(','); var arr = pcs; show$1(arr); } else { var _pcs = val1; var _arr = create$1(parseInt(_pcs)); show$1(_arr); } }; $$1('select').onclick = function () { selectSort(); }; //计算最大高度 function getMax$1(data) { var max = data[0]; for (var i in data) { if (data[i] > max) { max = data[i]; } } return max; } //获取元素 function $$1(id) { return document.getElementById(id); } function hasClass$1(elem, cls) { cls = cls || ''; if (cls.replace(/\s/g, '').length == 0) return false; //当cls没有参数时,返回false return new RegExp(' ' + cls + ' ').test(' ' + elem.className + ' '); } function addClass$1(ele, cls) { if (!hasClass$1(ele, cls)) { ele.className = ele.className == '' ? cls : ele.className + ' ' + cls; } } function sleep$1(ms) { return new Promise(function (resolve) { return setTimeout(resolve, ms); }); } //产生柱状图 function show$1(data) { var maxWidth = 800; var maxHeight = 450; var maxNum = getMax$1(data); //计算比例 var percent = maxHeight / maxNum; //柱子间隔 var space = maxWidth / (data.length * 2 + 1); var zhuWidth = 800 / (data.length * 2 + 1); var spaceWidth = 20; $$1('box').innerHTML = ''; //循环数据 for (var i = 0; i < data.length; i++) { var liDom = document.createElement('li'); liDom.style.width = space + 'px'; var left1 = (i + 1) * spaceWidth + i * zhuWidth; liDom.style.height = data[i] * percent + 'px'; liDom.innerHTML = data[i]; liDom.style.left = left1 + 'px'; $$1("box").appendChild(liDom); } } async function selectSort() { var arrC = []; var data = document.getElementsByTagName('li'); data = Array.apply(null, data); data.forEach(function (v, i) { arrC[i] = v.innerHTML; }); console.log('\u4E4B\u524D\u7684' + arrC); var len = data.length; var minIndex = void 0; for (var i = 0; i < len - 1; i++) { minIndex = i; addClass$1(data[minIndex], 'light'); for (var j = i + 1; j < len; j++) { //addClass(data[j],'end'); if (parseInt(arrC[j]) < parseInt(arrC[minIndex])) { //寻找最小的数 minIndex = j; //将最小数的索引保存 } } swap$1(data[i], data[minIndex]); var _temp = data[i]; data[i] = data[minIndex]; data[minIndex] = _temp; addClass$1(data[i], 'light1'); //橙色 data.forEach(function (v, i) { arrC[i] = v.innerHTML; }); await sleep$1(2000); } for (var _i = 0; _i < data.length; _i++) { addClass$1(data[_i], 'light1'); } } function swap$1(ele1, ele2) { var dis1 = ele1.offsetLeft; var dis2 = ele2.offsetLeft; var d1 = dis1; var d2 = dis2; var timer = setInterval(function () { if (dis1 < d2) { ele1.style.left = dis1++ + 'px'; } else { clearInterval(timer); } }, 10); var timer2 = setInterval(function () { if (d1 < dis2) { ele2.style.left = dis2-- + 'px'; } else { clearInterval(timer2); } }, 10); ele2.parentNode.insertBefore(ele2, ele1); } }());
24.872521
245
0.51549
36d726d5388c1fe4280b736f2a2ec94972d6b1a0
124
js
JavaScript
tests/baselines/reference/infinitelyExpandingTypes2.js
fdecampredon/jsx-typescript-old-version
f84ea6a7881723953a6c38d643de432c17fd5d98
[ "Apache-2.0" ]
3
2018-03-29T12:12:45.000Z
2019-04-16T10:59:34.000Z
tests/baselines/reference/infinitelyExpandingTypes2.js
fdecampredon/jsx-typescript-old-version
f84ea6a7881723953a6c38d643de432c17fd5d98
[ "Apache-2.0" ]
null
null
null
tests/baselines/reference/infinitelyExpandingTypes2.js
fdecampredon/jsx-typescript-old-version
f84ea6a7881723953a6c38d643de432c17fd5d98
[ "Apache-2.0" ]
null
null
null
//// [infinitelyExpandingTypes2.js] function f(p) { console.log(p); } var v = null; f(v); // should not error
13.777778
36
0.580645
36d7861b020d505e20ceaf9ca25ac22f7a249883
7,510
js
JavaScript
src/index.js
MrLoh/schema-converter-gql-json-yup
c2cedc35533a95e57abcee043b97716b457b286b
[ "MIT" ]
2
2019-11-06T00:33:25.000Z
2021-08-24T07:49:03.000Z
src/index.js
MrLoh/gql-to-json-schema
c2cedc35533a95e57abcee043b97716b457b286b
[ "MIT" ]
null
null
null
src/index.js
MrLoh/gql-to-json-schema
c2cedc35533a95e57abcee043b97716b457b286b
[ "MIT" ]
null
null
null
import { buildSchema } from 'graphql'; import kebabCase from 'lodash.kebabcase'; const SCALAR = 'ScalarTypeDefinition'; const ENUM = 'EnumTypeDefinition'; const DEFAULT = 'DefaultTypeDefinition'; const OBJECT = 'ObjectTypeDefinition'; const LIST = 'ListType'; const JSON_FORMAT_TYPES = ['DateTime', 'Date', 'Time', 'Email', 'Url', 'Markdown']; export const libraryScalars = JSON_FORMAT_TYPES.map((type) => `scalar ${type}`).join('\n'); const mockQuery = 'type Query { pass: Int }'; const getTypeName = (def) => { if (def.astNode) { let node = def.astNode; while (node.type) node = node.type; return node.name.value; } else { return def.name; } }; const getKinds = (def) => { if (!def) return []; if (def.astNode) { // the ast contains a nested object structure const kinds = []; let node = def.astNode; do { kinds.push(node.kind); node = node.type; } while (node); return kinds; } else { return [SCALAR, DEFAULT]; } }; const parseArg = (arg) => { switch (arg.kind) { case 'IntValue': return Number.parseInt(arg.value, 10); case 'FloatValue': return Number.parseFloat(arg.value); case 'ObjectValue': return Object.assign(...arg.fields.map(({ name, value }) => ({ [name.value]: value }))); case 'ListValue': return arg.values.map((argItem) => parseArg(argItem)); case 'StringValue': default: return arg.value; } }; const getDirectives = (def) => { if (def && def.astNode) { return def.astNode.directives.map((directive) => ({ name: directive.name.value, args: directive.arguments && directive.arguments.length > 0 && Object.assign( ...directive.arguments.map((arg) => ({ [arg.name.value]: parseArg(arg.value) })) ), })); } else return []; }; const getType = ({ typeName, fieldKinds, typeKinds }) => { if (fieldKinds.includes(LIST)) { return 'array'; } else if ([...typeKinds, ...fieldKinds].includes(OBJECT)) { return 'object'; } else if (typeKinds.includes(ENUM)) { return 'enum'; } else if (typeKinds.includes(DEFAULT)) { return { String: 'string', Boolean: 'boolean', Int: 'integer', Float: 'number' }[typeName]; } else if (typeKinds.includes(SCALAR)) { return 'string'; } else { throw new Error('unhandled type case'); } }; const getConstraints = ({ fieldKinds, typeKinds, typeName, directives }) => { const constraints = {}; // set nullability for field if (fieldKinds.length > 0) { constraints.nullable = fieldKinds[1] !== 'NonNullType'; } // set format for predefined scalar types if (typeKinds.includes(SCALAR) && JSON_FORMAT_TYPES.includes(typeName)) { constraints.format = kebabCase(typeName); } // handle directives if (directives.length > 0) { // assign directives as constraints directives.forEach(({ name, args }) => { // if directtive has single argument named `_` then resolve if directly const hasSingleUnderscoreArg = Object.keys(args).length === 1 && Object.keys(args)[0] === '_'; // if directive has no arguments interprete set to true constraints[name] = args ? (hasSingleUnderscoreArg ? args['_'] : args) : true; }); } return constraints; }; const getFields = (typeDefinition) => typeDefinition.getFields && typeDefinition.getFields(); const getValues = (typeDefinition) => typeDefinition.getValues && typeDefinition.getValues().map(({ description, name, value }) => ({ description, name, value })); const getDescription = ({ typeDefinition, fieldDefinition, typeKinds }) => { if (fieldDefinition && fieldDefinition.description) return fieldDefinition.description; if (!typeKinds.includes(DEFAULT) && typeDefinition.description) return typeDefinition.description; }; export const gql2jsonSchema = (typeDefs, baseType, { noQuery, noDefaultScalars } = {}) => { // if not specified, infer first type to be the base type if (!baseType) baseType = typeDefs.match(/\s*type\s*(\w*)/)[1]; // build gql schema object from type defs and get map of relevant types const gqlSchema = buildSchema( typeDefs + (noQuery ? '' : mockQuery) + (noDefaultScalars ? '' : libraryScalars) ); const typeMap = Object.assign( ...Object.entries(gqlSchema.getTypeMap()) .filter(([key]) => key.substring(0, 2) !== '__' && key !== 'Query') .map(([key, value]) => ({ [key]: value })) ); // const directiveMap = Object.assign( // ...gqlSchema.getDirectives().map((directive) => ({ [directive.name]: directive })) // ); // handles all props that don't depend on fieldKinds, since recursion for arrays alter fieldKinds const getProps = ({ fieldDefinition, typeName, parentTypeName }) => { // use given typeName for initial call, or resolve typeName fron fieldDefinition typeName = typeName ? typeName : getTypeName(fieldDefinition); if (typeName === parentTypeName) throw new Error('recursive schemas are not supported'); const typeDefinition = typeMap[typeName]; const typeKinds = getKinds(typeDefinition); const fieldKinds = getKinds(fieldDefinition); const directives = getDirectives(fieldDefinition); const description = getDescription({ typeDefinition, fieldDefinition, typeKinds }); const fields = getFields(typeDefinition); const values = getValues(typeDefinition); return { typeName, fieldKinds, typeKinds, description, fields, values, directives }; }; // converter function to reduce gql to json type definitions const resolveTypes = (props) => { const { typeName, fieldKinds, typeKinds, directives } = props; // get properties that depend on field types const constraints = getConstraints({ fieldKinds, typeKinds, typeName, directives }); const type = getType({ typeName, fieldKinds, typeKinds }); // build schema object const jsonSchema = { type, ...constraints }; // only set des ription, if it was given if (props.description) jsonSchema.description = props.description; // set type name for objects, enums, and custom scalars if ( (!typeKinds.includes(DEFAULT) && typeKinds.includes(SCALAR)) || ['enum', 'object'].includes(type) ) { jsonSchema.name = typeName; } // handle enums if (type === 'enum') { jsonSchema.type = 'string'; jsonSchema.enum = props.values; } // handle lists if (type === 'array') { // remove first types to handle nullability and type resolution correctly const itemFieldKinds = ['FieldDefinition', ...fieldKinds.slice(jsonSchema.nullable ? 2 : 3)]; // recursively resolve arrays jsonSchema.items = resolveTypes({ ...props, fieldKinds: itemFieldKinds }); } // handle referenced types if (type === 'object') { // recursively resolve objects jsonSchema.properties = Object.assign( ...Object.entries(props.fields).map(([key, fieldDefinition]) => ({ [key]: resolveTypes(getProps({ fieldDefinition, parentTypeName: typeName })), })) ); // set non nullable properties as required jsonSchema.required = Object.keys(jsonSchema.properties).filter( (key) => !jsonSchema.properties[key].nullable ); } return jsonSchema; }; // return nested json schema for base type return { title: baseType, ...resolveTypes(getProps({ typeName: baseType })) }; }; export const gql = (strings, ...values) => strings.reduce((result, str, i) => result + str + (values[i] || ''));
36.995074
100
0.654194
36d7e0cb4071179b1cad372df128ec4536e5654c
96,319
js
JavaScript
node_modules/prettier/parser-graphql.js
Vanshikaa00/Contribute-To-This-Project
6fb2a8512ebfd850167ab4db3cd3eb1bfa61461a
[ "MIT" ]
23
2021-01-25T07:34:05.000Z
2021-06-06T15:01:33.000Z
node_modules/prettier/parser-graphql.js
Vanshikaa00/Contribute-To-This-Project
6fb2a8512ebfd850167ab4db3cd3eb1bfa61461a
[ "MIT" ]
1
2020-08-12T16:00:32.000Z
2020-08-12T16:08:15.000Z
node_modules/prettier/parser-graphql.js
Vanshikaa00/Contribute-To-This-Project
6fb2a8512ebfd850167ab4db3cd3eb1bfa61461a
[ "MIT" ]
3
2021-01-26T14:58:33.000Z
2021-06-28T16:12:36.000Z
!(function(e, n) { 'object' == typeof exports && 'undefined' != typeof module ? (module.exports = n()) : 'function' == typeof define && define.amd ? define(n) : ((e.prettierPlugins = e.prettierPlugins || {}), (e.prettierPlugins.graphql = n())) })(this, function() { 'use strict' function e(n) { return (e = 'function' == typeof Symbol && 'symbol' == typeof Symbol.iterator ? function(e) { return typeof e } : function(e) { return e && 'function' == typeof Symbol && e.constructor === Symbol && e !== Symbol.prototype ? 'symbol' : typeof e })(n) } var n = function(e, n) { var t = new SyntaxError(e + ' (' + n.start.line + ':' + n.start.column + ')') return (t.loc = n), t } var t = function(e) { return /^\s*#[^\n\S]*@(format|prettier)\s*(\n|$)/.test(e) } function r(e) { return e && e.__esModule && Object.prototype.hasOwnProperty.call(e, 'default') ? e.default : e } function i(e, n) { return e((n = { exports: {} }), n.exports), n.exports } var o = i(function(e, n) { Object.defineProperty(n, '__esModule', { value: !0 }), (n.getLocation = function(e, n) { var t, r = /\r\n|[\n\r]/g, i = 1, o = n + 1 for (; (t = r.exec(e.body)) && t.index < n; ) (i += 1), (o = n + 1 - (t.index + t[0].length)) return { line: i, column: o } }) }) r(o) var a = i(function(e, n) { Object.defineProperty(n, '__esModule', { value: !0 }), (n.Kind = void 0) var t = Object.freeze({ NAME: 'Name', DOCUMENT: 'Document', OPERATION_DEFINITION: 'OperationDefinition', VARIABLE_DEFINITION: 'VariableDefinition', SELECTION_SET: 'SelectionSet', FIELD: 'Field', ARGUMENT: 'Argument', FRAGMENT_SPREAD: 'FragmentSpread', INLINE_FRAGMENT: 'InlineFragment', FRAGMENT_DEFINITION: 'FragmentDefinition', VARIABLE: 'Variable', INT: 'IntValue', FLOAT: 'FloatValue', STRING: 'StringValue', BOOLEAN: 'BooleanValue', NULL: 'NullValue', ENUM: 'EnumValue', LIST: 'ListValue', OBJECT: 'ObjectValue', OBJECT_FIELD: 'ObjectField', DIRECTIVE: 'Directive', NAMED_TYPE: 'NamedType', LIST_TYPE: 'ListType', NON_NULL_TYPE: 'NonNullType', SCHEMA_DEFINITION: 'SchemaDefinition', OPERATION_TYPE_DEFINITION: 'OperationTypeDefinition', SCALAR_TYPE_DEFINITION: 'ScalarTypeDefinition', OBJECT_TYPE_DEFINITION: 'ObjectTypeDefinition', FIELD_DEFINITION: 'FieldDefinition', INPUT_VALUE_DEFINITION: 'InputValueDefinition', INTERFACE_TYPE_DEFINITION: 'InterfaceTypeDefinition', UNION_TYPE_DEFINITION: 'UnionTypeDefinition', ENUM_TYPE_DEFINITION: 'EnumTypeDefinition', ENUM_VALUE_DEFINITION: 'EnumValueDefinition', INPUT_OBJECT_TYPE_DEFINITION: 'InputObjectTypeDefinition', DIRECTIVE_DEFINITION: 'DirectiveDefinition', SCHEMA_EXTENSION: 'SchemaExtension', SCALAR_TYPE_EXTENSION: 'ScalarTypeExtension', OBJECT_TYPE_EXTENSION: 'ObjectTypeExtension', INTERFACE_TYPE_EXTENSION: 'InterfaceTypeExtension', UNION_TYPE_EXTENSION: 'UnionTypeExtension', ENUM_TYPE_EXTENSION: 'EnumTypeExtension', INPUT_OBJECT_TYPE_EXTENSION: 'InputObjectTypeExtension', }) n.Kind = t }) r(a) var c = i(function(e, n) { Object.defineProperty(n, '__esModule', { value: !0 }), (n.default = void 0) var t = 'function' == typeof Symbol ? Symbol.for('nodejs.util.inspect.custom') : void 0 n.default = t }) r(c) var u = i(function(e, n) { Object.defineProperty(n, '__esModule', { value: !0 }), (n.default = function(e) { var n = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : e.prototype.toString ;(e.prototype.toJSON = n), (e.prototype.inspect = n), r.default && (e.prototype[r.default] = n) }) var t, r = (t = c) && t.__esModule ? t : { default: t } }) r(u) var d = i(function(e, n) { function t(e, n) { var t = e.locationOffset.column - 1, i = r(t) + e.body, o = n.line - 1, a = e.locationOffset.line - 1, c = n.line + a, u = 1 === n.line ? t : 0, d = n.column + u, s = i.split(/\r\n|[\n\r]/g) return ( '' .concat(e.name, ' (') .concat(c, ':') .concat(d, ')\n') + (function(e) { var n = e.filter(function(e) { e[0] var n = e[1] return void 0 !== n }), t = 0, i = !0, o = !1, a = void 0 try { for (var c, u = n[Symbol.iterator](); !(i = (c = u.next()).done); i = !0) { var d = c.value, s = d[0] t = Math.max(t, s.length) } } catch (e) { ;(o = !0), (a = e) } finally { try { i || null == u.return || u.return() } finally { if (o) throw a } } return n .map(function(e) { var n, i = e[0], o = e[1] return r(t - (n = i).length) + n + o }) .join('\n') })([ [''.concat(c - 1, ': '), s[o - 1]], [''.concat(c, ': '), s[o]], ['', r(d - 1) + '^'], [''.concat(c + 1, ': '), s[o + 1]], ]) ) } function r(e) { return Array(e + 1).join(' ') } Object.defineProperty(n, '__esModule', { value: !0 }), (n.printError = function(e) { var n = [] if (e.nodes) { var r = !0, i = !1, a = void 0 try { for (var c, u = e.nodes[Symbol.iterator](); !(r = (c = u.next()).done); r = !0) { var d = c.value d.loc && n.push(t(d.loc.source, (0, o.getLocation)(d.loc.source, d.loc.start))) } } catch (e) { ;(i = !0), (a = e) } finally { try { r || null == u.return || u.return() } finally { if (i) throw a } } } else if (e.source && e.locations) { var s = e.source, l = !0, f = !1, v = void 0 try { for (var E, T = e.locations[Symbol.iterator](); !(l = (E = T.next()).done); l = !0) { var p = E.value n.push(t(s, p)) } } catch (e) { ;(f = !0), (v = e) } finally { try { l || null == T.return || T.return() } finally { if (f) throw v } } } return 0 === n.length ? e.message : [e.message].concat(n).join('\n\n') + '\n' }) }) r(d) var s = i(function(e, n) { function t(e, n, r, i, a, c, u) { var d = Array.isArray(n) ? (0 !== n.length ? n : void 0) : n ? [n] : void 0, s = r if (!s && d) { var l = d[0] s = l && l.loc && l.loc.source } var f, v = i !v && d && (v = d.reduce(function(e, n) { return n.loc && e.push(n.loc.start), e }, [])), v && 0 === v.length && (v = void 0), i && r ? (f = i.map(function(e) { return (0, o.getLocation)(r, e) })) : d && (f = d.reduce(function(e, n) { return n.loc && e.push((0, o.getLocation)(n.loc.source, n.loc.start)), e }, [])) var E = u || (c && c.extensions) Object.defineProperties(this, { message: { value: e, enumerable: !0, writable: !0 }, locations: { value: f || void 0, enumerable: Boolean(f) }, path: { value: a || void 0, enumerable: Boolean(a) }, nodes: { value: d || void 0 }, source: { value: s || void 0 }, positions: { value: v || void 0 }, originalError: { value: c }, extensions: { value: E || void 0, enumerable: Boolean(E) }, }), c && c.stack ? Object.defineProperty(this, 'stack', { value: c.stack, writable: !0, configurable: !0 }) : Error.captureStackTrace ? Error.captureStackTrace(this, t) : Object.defineProperty(this, 'stack', { value: Error().stack, writable: !0, configurable: !0 }) } Object.defineProperty(n, '__esModule', { value: !0 }), (n.GraphQLError = t), (t.prototype = Object.create(Error.prototype, { constructor: { value: t }, name: { value: 'GraphQLError' }, toString: { value: function() { return (0, d.printError)(this) }, }, })) }) r(s) var l = i(function(e, n) { Object.defineProperty(n, '__esModule', { value: !0 }), (n.syntaxError = function(e, n, t) { return new s.GraphQLError('Syntax Error: '.concat(t), void 0, e, [n]) }) }) r(l) var f = i(function(e, n) { Object.defineProperty(n, '__esModule', { value: !0 }), (n.locatedError = function(e, n, t) { if (e && Array.isArray(e.path)) return e return new s.GraphQLError(e && e.message, (e && e.nodes) || n, e && e.source, e && e.positions, t, e) }) }) r(f) var v = i(function(e, n) { Object.defineProperty(n, '__esModule', { value: !0 }), (n.default = function(e, n) { if (!e) throw new Error(n) }) }) r(v) var E = i(function(e, n) { Object.defineProperty(n, '__esModule', { value: !0 }), (n.formatError = function(e) { e || (0, r.default)(0, 'Received null or undefined error.') var n = e.message || 'An unknown error occurred.', t = e.locations, i = e.path, o = e.extensions return o ? { message: n, locations: t, path: i, extensions: o } : { message: n, locations: t, path: i } }) var t, r = (t = v) && t.__esModule ? t : { default: t } }) r(E) var T = i(function(e, n) { Object.defineProperty(n, '__esModule', { value: !0 }), Object.defineProperty(n, 'GraphQLError', { enumerable: !0, get: function() { return s.GraphQLError }, }), Object.defineProperty(n, 'syntaxError', { enumerable: !0, get: function() { return l.syntaxError }, }), Object.defineProperty(n, 'locatedError', { enumerable: !0, get: function() { return f.locatedError }, }), Object.defineProperty(n, 'printError', { enumerable: !0, get: function() { return d.printError }, }), Object.defineProperty(n, 'formatError', { enumerable: !0, get: function() { return E.formatError }, }) }) r(T) var p = i(function(e, n) { function t(e) { for (var n = 0; n < e.length && (' ' === e[n] || '\t' === e[n]); ) n++ return n } function r(e) { return t(e) === e.length } Object.defineProperty(n, '__esModule', { value: !0 }), (n.dedentBlockStringValue = function(e) { for (var n = e.split(/\r\n|[\n\r]/g), i = null, o = 1; o < n.length; o++) { var a = n[o], c = t(a) if (c < a.length && (null === i || c < i) && 0 === (i = c)) break } if (i) for (var u = 1; u < n.length; u++) n[u] = n[u].slice(i) for (; n.length > 0 && r(n[0]); ) n.shift() for (; n.length > 0 && r(n[n.length - 1]); ) n.pop() return n.join('\n') }), (n.printBlockString = function(e) { var n = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : '', t = arguments.length > 2 && void 0 !== arguments[2] && arguments[2], r = -1 === e.indexOf('\n'), i = ' ' === e[0] || '\t' === e[0], o = '"' === e[e.length - 1], a = !r || o || t, c = '' !a || (r && i) || (c += '\n' + n) ;(c += n ? e.replace(/\n/g, '\n' + n) : e), a && (c += '\n') return '"""' + c.replace(/"""/g, '\\"""') + '"""' }) }) r(p) var N = i(function(e, n) { Object.defineProperty(n, '__esModule', { value: !0 }), (n.createLexer = function(e, n) { var t = new c(a.SOF, 0, 0, 0, 0, null) return { source: e, options: n, lastToken: t, token: t, line: 1, lineStart: 0, advance: i, lookahead: o, } }), (n.getTokenDesc = function(e) { var n = e.value return n ? ''.concat(e.kind, ' "').concat(n, '"') : e.kind }), (n.TokenKind = void 0) var t, r = (t = u) && t.__esModule ? t : { default: t } function i() { return (this.lastToken = this.token), (this.token = this.lookahead()) } function o() { var e = this.token if (e.kind !== a.EOF) do { e = e.next || (e.next = s(this, e)) } while (e.kind === a.COMMENT) return e } var a = Object.freeze({ SOF: '<SOF>', EOF: '<EOF>', BANG: '!', DOLLAR: '$', AMP: '&', PAREN_L: '(', PAREN_R: ')', SPREAD: '...', COLON: ':', EQUALS: '=', AT: '@', BRACKET_L: '[', BRACKET_R: ']', BRACE_L: '{', PIPE: '|', BRACE_R: '}', NAME: 'Name', INT: 'Int', FLOAT: 'Float', STRING: 'String', BLOCK_STRING: 'BlockString', COMMENT: 'Comment', }) function c(e, n, t, r, i, o, a) { ;(this.kind = e), (this.start = n), (this.end = t), (this.line = r), (this.column = i), (this.value = a), (this.prev = o), (this.next = null) } function d(e) { return isNaN(e) ? a.EOF : e < 127 ? JSON.stringify(String.fromCharCode(e)) : '"\\u'.concat(('00' + e.toString(16).toUpperCase()).slice(-4), '"') } function s(e, n) { var t = e.source, r = t.body, i = r.length, o = (function(e, n, t) { var r = e.length, i = n for (; i < r; ) { var o = e.charCodeAt(i) if (9 === o || 32 === o || 44 === o || 65279 === o) ++i else if (10 === o) ++i, ++t.line, (t.lineStart = i) else { if (13 !== o) break 10 === e.charCodeAt(i + 1) ? (i += 2) : ++i, ++t.line, (t.lineStart = i) } } return i })(r, n.end, e), u = e.line, s = 1 + o - e.lineStart if (o >= i) return new c(a.EOF, i, i, u, s, n) var v = r.charCodeAt(o) switch (v) { case 33: return new c(a.BANG, o, o + 1, u, s, n) case 35: return (function(e, n, t, r, i) { var o, u = e.body, d = n do { o = u.charCodeAt(++d) } while (!isNaN(o) && (o > 31 || 9 === o)) return new c(a.COMMENT, n, d, t, r, i, u.slice(n + 1, d)) })(t, o, u, s, n) case 36: return new c(a.DOLLAR, o, o + 1, u, s, n) case 38: return new c(a.AMP, o, o + 1, u, s, n) case 40: return new c(a.PAREN_L, o, o + 1, u, s, n) case 41: return new c(a.PAREN_R, o, o + 1, u, s, n) case 46: if (46 === r.charCodeAt(o + 1) && 46 === r.charCodeAt(o + 2)) return new c(a.SPREAD, o, o + 3, u, s, n) break case 58: return new c(a.COLON, o, o + 1, u, s, n) case 61: return new c(a.EQUALS, o, o + 1, u, s, n) case 64: return new c(a.AT, o, o + 1, u, s, n) case 91: return new c(a.BRACKET_L, o, o + 1, u, s, n) case 93: return new c(a.BRACKET_R, o, o + 1, u, s, n) case 123: return new c(a.BRACE_L, o, o + 1, u, s, n) case 124: return new c(a.PIPE, o, o + 1, u, s, n) case 125: return new c(a.BRACE_R, o, o + 1, u, s, n) case 65: case 66: case 67: case 68: case 69: case 70: case 71: case 72: case 73: case 74: case 75: case 76: case 77: case 78: case 79: case 80: case 81: case 82: case 83: case 84: case 85: case 86: case 87: case 88: case 89: case 90: case 95: case 97: case 98: case 99: case 100: case 101: case 102: case 103: case 104: case 105: case 106: case 107: case 108: case 109: case 110: case 111: case 112: case 113: case 114: case 115: case 116: case 117: case 118: case 119: case 120: case 121: case 122: return (function(e, n, t, r, i) { var o = e.body, u = o.length, d = n + 1, s = 0 for ( ; d !== u && !isNaN((s = o.charCodeAt(d))) && (95 === s || (s >= 48 && s <= 57) || (s >= 65 && s <= 90) || (s >= 97 && s <= 122)); ) ++d return new c(a.NAME, n, d, t, r, i, o.slice(n, d)) })(t, o, u, s, n) case 45: case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: return (function(e, n, t, r, i, o) { var u = e.body, s = t, f = n, v = !1 45 === s && (s = u.charCodeAt(++f)) if (48 === s) { if ((s = u.charCodeAt(++f)) >= 48 && s <= 57) throw (0, T.syntaxError)( e, f, 'Invalid number, unexpected digit after 0: '.concat(d(s), '.') ) } else (f = l(e, f, s)), (s = u.charCodeAt(f)) 46 === s && ((v = !0), (s = u.charCodeAt(++f)), (f = l(e, f, s)), (s = u.charCodeAt(f))) ;(69 !== s && 101 !== s) || ((v = !0), (43 !== (s = u.charCodeAt(++f)) && 45 !== s) || (s = u.charCodeAt(++f)), (f = l(e, f, s))) return new c(v ? a.FLOAT : a.INT, n, f, r, i, o, u.slice(n, f)) })(t, o, v, u, s, n) case 34: return 34 === r.charCodeAt(o + 1) && 34 === r.charCodeAt(o + 2) ? (function(e, n, t, r, i, o) { var u = e.body, s = n + 3, l = s, f = 0, v = '' for (; s < u.length && !isNaN((f = u.charCodeAt(s))); ) { if (34 === f && 34 === u.charCodeAt(s + 1) && 34 === u.charCodeAt(s + 2)) return ( (v += u.slice(l, s)), new c(a.BLOCK_STRING, n, s + 3, t, r, i, (0, p.dedentBlockStringValue)(v)) ) if (f < 32 && 9 !== f && 10 !== f && 13 !== f) throw (0, T.syntaxError)( e, s, 'Invalid character within String: '.concat(d(f), '.') ) 10 === f ? (++s, ++o.line, (o.lineStart = s)) : 13 === f ? (10 === u.charCodeAt(s + 1) ? (s += 2) : ++s, ++o.line, (o.lineStart = s)) : 92 === f && 34 === u.charCodeAt(s + 1) && 34 === u.charCodeAt(s + 2) && 34 === u.charCodeAt(s + 3) ? ((v += u.slice(l, s) + '"""'), (l = s += 4)) : ++s } throw (0, T.syntaxError)(e, s, 'Unterminated string.') })(t, o, u, s, n, e) : (function(e, n, t, r, i) { var o = e.body, u = n + 1, s = u, l = 0, v = '' for (; u < o.length && !isNaN((l = o.charCodeAt(u))) && 10 !== l && 13 !== l; ) { if (34 === l) return (v += o.slice(s, u)), new c(a.STRING, n, u + 1, t, r, i, v) if (l < 32 && 9 !== l) throw (0, T.syntaxError)( e, u, 'Invalid character within String: '.concat(d(l), '.') ) if ((++u, 92 === l)) { switch (((v += o.slice(s, u - 1)), (l = o.charCodeAt(u)))) { case 34: v += '"' break case 47: v += '/' break case 92: v += '\\' break case 98: v += '\b' break case 102: v += '\f' break case 110: v += '\n' break case 114: v += '\r' break case 116: v += '\t' break case 117: var E = ((p = o.charCodeAt(u + 1)), (N = o.charCodeAt(u + 2)), (I = o.charCodeAt(u + 3)), (y = o.charCodeAt(u + 4)), (f(p) << 12) | (f(N) << 8) | (f(I) << 4) | f(y)) if (E < 0) throw (0, T.syntaxError)( e, u, 'Invalid character escape sequence: ' + '\\u'.concat(o.slice(u + 1, u + 5), '.') ) ;(v += String.fromCharCode(E)), (u += 4) break default: throw (0, T.syntaxError)( e, u, 'Invalid character escape sequence: \\'.concat( String.fromCharCode(l), '.' ) ) } s = ++u } } var p, N, I, y throw (0, T.syntaxError)(e, u, 'Unterminated string.') })(t, o, u, s, n) } throw (0, T.syntaxError)( t, o, (function(e) { if (e < 32 && 9 !== e && 10 !== e && 13 !== e) return 'Cannot contain the invalid character '.concat(d(e), '.') if (39 === e) return 'Unexpected single quote character (\'), did you mean to use a double quote (")?' return 'Cannot parse the unexpected character '.concat(d(e), '.') })(v) ) } function l(e, n, t) { var r = e.body, i = n, o = t if (o >= 48 && o <= 57) { do { o = r.charCodeAt(++i) } while (o >= 48 && o <= 57) return i } throw (0, T.syntaxError)(e, i, 'Invalid number, expected digit but got: '.concat(d(o), '.')) } function f(e) { return e >= 48 && e <= 57 ? e - 48 : e >= 65 && e <= 70 ? e - 55 : e >= 97 && e <= 102 ? e - 87 : -1 } ;(n.TokenKind = a), (0, r.default)(c, function() { return { kind: this.kind, value: this.value, line: this.line, column: this.column } }) }) r(N) var I = i(function(n, t) { Object.defineProperty(t, '__esModule', { value: !0 }), (t.default = function(e) { return d(e, []) }) var r, i = (r = c) && r.__esModule ? r : { default: r } function o(n) { return (o = 'function' == typeof Symbol && 'symbol' === e(Symbol.iterator) ? function(n) { return e(n) } : function(n) { return n && 'function' == typeof Symbol && n.constructor === Symbol && n !== Symbol.prototype ? 'symbol' : e(n) })(n) } var a = 10, u = 2 function d(e, n) { switch (o(e)) { case 'string': return JSON.stringify(e) case 'function': return e.name ? '[function '.concat(e.name, ']') : '[function]' case 'object': return (function(e, n) { if (-1 !== n.indexOf(e)) return '[Circular]' var t = [].concat(n, [e]) if (e) { var r = (function(e) { var n = e[String(i.default)] if ('function' == typeof n) return n if ('function' == typeof e.inspect) return e.inspect })(e) if (r) { var o = r.call(e) if (o !== e) return 'string' == typeof o ? o : d(o, t) } else if (Array.isArray(e)) return (function(e, n) { if (0 === e.length) return '[]' if (n.length > u) return '[Array]' for (var t = Math.min(a, e.length), r = e.length - t, i = [], o = 0; o < t; ++o) i.push(d(e[o], n)) 1 === r ? i.push('... 1 more item') : r > 1 && i.push('... '.concat(r, ' more items')) return '[' + i.join(', ') + ']' })(e, t) return (function(e, n) { var t = Object.keys(e) if (0 === t.length) return '{}' if (n.length > u) return ( '[' + (function(e) { var n = Object.prototype.toString .call(e) .replace(/^\[object /, '') .replace(/]$/, '') if ('Object' === n && 'function' == typeof e.constructor) { var t = e.constructor.name if ('string' == typeof t) return t } return n })(e) + ']' ) return ( '{ ' + t .map(function(t) { var r = d(e[t], n) return t + ': ' + r }) .join(', ') + ' }' ) })(e, t) } return String(e) })(e, n) default: return String(e) } } }) r(I) var y = i(function(e, n) { Object.defineProperty(n, '__esModule', { value: !0 }), (n.default = function(e) { 'function' == typeof Symbol && Symbol.toStringTag && Object.defineProperty(e.prototype, Symbol.toStringTag, { get: function() { return this.constructor.name }, }) }) }) r(y) var m = i(function(e, n) { Object.defineProperty(n, '__esModule', { value: !0 }), (n.Source = void 0) var t = i(v), r = i(y) function i(e) { return e && e.__esModule ? e : { default: e } } var o = function(e, n, r) { ;(this.body = e), (this.name = n || 'GraphQL request'), (this.locationOffset = r || { line: 1, column: 1 }), this.locationOffset.line > 0 || (0, t.default)(0, 'line in locationOffset is 1-indexed and must be positive'), this.locationOffset.column > 0 || (0, t.default)(0, 'column in locationOffset is 1-indexed and must be positive') } ;(n.Source = o), (0, r.default)(o) }) r(m) var k = i(function(e, n) { Object.defineProperty(n, '__esModule', { value: !0 }), (n.DirectiveLocation = void 0) var t = Object.freeze({ QUERY: 'QUERY', MUTATION: 'MUTATION', SUBSCRIPTION: 'SUBSCRIPTION', FIELD: 'FIELD', FRAGMENT_DEFINITION: 'FRAGMENT_DEFINITION', FRAGMENT_SPREAD: 'FRAGMENT_SPREAD', INLINE_FRAGMENT: 'INLINE_FRAGMENT', VARIABLE_DEFINITION: 'VARIABLE_DEFINITION', SCHEMA: 'SCHEMA', SCALAR: 'SCALAR', OBJECT: 'OBJECT', FIELD_DEFINITION: 'FIELD_DEFINITION', ARGUMENT_DEFINITION: 'ARGUMENT_DEFINITION', INTERFACE: 'INTERFACE', UNION: 'UNION', ENUM: 'ENUM', ENUM_VALUE: 'ENUM_VALUE', INPUT_OBJECT: 'INPUT_OBJECT', INPUT_FIELD_DEFINITION: 'INPUT_FIELD_DEFINITION', }) n.DirectiveLocation = t }) r(k) var O = i(function(e, n) { Object.defineProperty(n, '__esModule', { value: !0 }), (n.parse = function(e, n) { var r = 'string' == typeof e ? new m.Source(e) : e if (!(r instanceof m.Source)) throw new TypeError('Must provide Source. Received: '.concat((0, t.default)(r))) return (function(e) { var n = e.token return { kind: a.Kind.DOCUMENT, definitions: te(e, N.TokenKind.SOF, o, N.TokenKind.EOF), loc: Q(e, n), } })((0, N.createLexer)(r, n || {})) }), (n.parseValue = function(e, n) { var t = 'string' == typeof e ? new m.Source(e) : e, r = (0, N.createLexer)(t, n || {}) $(r, N.TokenKind.SOF) var i = A(r, !1) return $(r, N.TokenKind.EOF), i }), (n.parseType = function(e, n) { var t = 'string' == typeof e ? new m.Source(e) : e, r = (0, N.createLexer)(t, n || {}) $(r, N.TokenKind.SOF) var i = P(r) return $(r, N.TokenKind.EOF), i }), (n.parseConstValue = g), (n.parseTypeReference = P), (n.parseNamedType = L) var t = r(I) function r(e) { return e && e.__esModule ? e : { default: e } } function i(e) { var n = $(e, N.TokenKind.NAME) return { kind: a.Kind.NAME, value: n.value, loc: Q(e, n) } } function o(e) { if (H(e, N.TokenKind.NAME)) switch (e.token.value) { case 'query': case 'mutation': case 'subscription': case 'fragment': return c(e) case 'schema': case 'scalar': case 'type': case 'interface': case 'union': case 'enum': case 'input': case 'directive': return C(e) case 'extend': return (function(e) { var n = e.lookahead() if (n.kind === N.TokenKind.NAME) switch (n.value) { case 'schema': return (function(e) { var n = e.token W(e, 'extend'), W(e, 'schema') var t = K(e, !0), r = H(e, N.TokenKind.BRACE_L) ? te(e, N.TokenKind.BRACE_L, M, N.TokenKind.BRACE_R) : [] if (0 === t.length && 0 === r.length) throw ee(e) return { kind: a.Kind.SCHEMA_EXTENSION, directives: t, operationTypes: r, loc: Q(e, n), } })(e) case 'scalar': return (function(e) { var n = e.token W(e, 'extend'), W(e, 'scalar') var t = i(e), r = K(e, !0) if (0 === r.length) throw ee(e) return { kind: a.Kind.SCALAR_TYPE_EXTENSION, name: t, directives: r, loc: Q(e, n), } })(e) case 'type': return (function(e) { var n = e.token W(e, 'extend'), W(e, 'type') var t = i(e), r = x(e), o = K(e, !0), c = j(e) if (0 === r.length && 0 === o.length && 0 === c.length) throw ee(e) return { kind: a.Kind.OBJECT_TYPE_EXTENSION, name: t, interfaces: r, directives: o, fields: c, loc: Q(e, n), } })(e) case 'interface': return (function(e) { var n = e.token W(e, 'extend'), W(e, 'interface') var t = i(e), r = K(e, !0), o = j(e) if (0 === r.length && 0 === o.length) throw ee(e) return { kind: a.Kind.INTERFACE_TYPE_EXTENSION, name: t, directives: r, fields: o, loc: Q(e, n), } })(e) case 'union': return (function(e) { var n = e.token W(e, 'extend'), W(e, 'union') var t = i(e), r = K(e, !0), o = V(e) if (0 === r.length && 0 === o.length) throw ee(e) return { kind: a.Kind.UNION_TYPE_EXTENSION, name: t, directives: r, types: o, loc: Q(e, n), } })(e) case 'enum': return (function(e) { var n = e.token W(e, 'extend'), W(e, 'enum') var t = i(e), r = K(e, !0), o = Y(e) if (0 === r.length && 0 === o.length) throw ee(e) return { kind: a.Kind.ENUM_TYPE_EXTENSION, name: t, directives: r, values: o, loc: Q(e, n), } })(e) case 'input': return (function(e) { var n = e.token W(e, 'extend'), W(e, 'input') var t = i(e), r = K(e, !0), o = J(e) if (0 === r.length && 0 === o.length) throw ee(e) return { kind: a.Kind.INPUT_OBJECT_TYPE_EXTENSION, name: t, directives: r, fields: o, loc: Q(e, n), } })(e) } throw ee(e, n) })(e) } else { if (H(e, N.TokenKind.BRACE_L)) return c(e) if (R(e)) return C(e) } throw ee(e) } function c(e) { if (H(e, N.TokenKind.NAME)) switch (e.token.value) { case 'query': case 'mutation': case 'subscription': return d(e) case 'fragment': return (function(e) { var n = e.token if ((W(e, 'fragment'), e.options.experimentalFragmentVariables)) return { kind: a.Kind.FRAGMENT_DEFINITION, name: h(e), variableDefinitions: l(e), typeCondition: (W(e, 'on'), L(e)), directives: K(e, !1), selectionSet: E(e), loc: Q(e, n), } return { kind: a.Kind.FRAGMENT_DEFINITION, name: h(e), typeCondition: (W(e, 'on'), L(e)), directives: K(e, !1), selectionSet: E(e), loc: Q(e, n), } })(e) } else if (H(e, N.TokenKind.BRACE_L)) return d(e) throw ee(e) } function d(e) { var n = e.token if (H(e, N.TokenKind.BRACE_L)) return { kind: a.Kind.OPERATION_DEFINITION, operation: 'query', name: void 0, variableDefinitions: [], directives: [], selectionSet: E(e), loc: Q(e, n), } var t, r = s(e) return ( H(e, N.TokenKind.NAME) && (t = i(e)), { kind: a.Kind.OPERATION_DEFINITION, operation: r, name: t, variableDefinitions: l(e), directives: K(e, !1), selectionSet: E(e), loc: Q(e, n), } ) } function s(e) { var n = $(e, N.TokenKind.NAME) switch (n.value) { case 'query': return 'query' case 'mutation': return 'mutation' case 'subscription': return 'subscription' } throw ee(e, n) } function l(e) { return H(e, N.TokenKind.PAREN_L) ? te(e, N.TokenKind.PAREN_L, f, N.TokenKind.PAREN_R) : [] } function f(e) { var n = e.token return { kind: a.Kind.VARIABLE_DEFINITION, variable: v(e), type: ($(e, N.TokenKind.COLON), P(e)), defaultValue: z(e, N.TokenKind.EQUALS) ? A(e, !0) : void 0, directives: K(e, !0), loc: Q(e, n), } } function v(e) { var n = e.token return $(e, N.TokenKind.DOLLAR), { kind: a.Kind.VARIABLE, name: i(e), loc: Q(e, n) } } function E(e) { var n = e.token return { kind: a.Kind.SELECTION_SET, selections: te(e, N.TokenKind.BRACE_L, p, N.TokenKind.BRACE_R), loc: Q(e, n), } } function p(e) { return H(e, N.TokenKind.SPREAD) ? (function(e) { var n = e.token $(e, N.TokenKind.SPREAD) var t = Z(e, 'on') if (!t && H(e, N.TokenKind.NAME)) return { kind: a.Kind.FRAGMENT_SPREAD, name: h(e), directives: K(e, !1), loc: Q(e, n) } return { kind: a.Kind.INLINE_FRAGMENT, typeCondition: t ? L(e) : void 0, directives: K(e, !1), selectionSet: E(e), loc: Q(e, n), } })(e) : (function(e) { var n, t, r = e.token, o = i(e) z(e, N.TokenKind.COLON) ? ((n = o), (t = i(e))) : (t = o) return { kind: a.Kind.FIELD, alias: n, name: t, arguments: y(e, !1), directives: K(e, !1), selectionSet: H(e, N.TokenKind.BRACE_L) ? E(e) : void 0, loc: Q(e, r), } })(e) } function y(e, n) { var t = n ? _ : O return H(e, N.TokenKind.PAREN_L) ? te(e, N.TokenKind.PAREN_L, t, N.TokenKind.PAREN_R) : [] } function O(e) { var n = e.token, t = i(e) return $(e, N.TokenKind.COLON), { kind: a.Kind.ARGUMENT, name: t, value: A(e, !1), loc: Q(e, n) } } function _(e) { var n = e.token return { kind: a.Kind.ARGUMENT, name: i(e), value: ($(e, N.TokenKind.COLON), g(e)), loc: Q(e, n) } } function h(e) { if ('on' === e.token.value) throw ee(e) return i(e) } function A(e, n) { var t = e.token switch (t.kind) { case N.TokenKind.BRACKET_L: return (function(e, n) { var t = e.token, r = n ? g : S return { kind: a.Kind.LIST, values: ne(e, N.TokenKind.BRACKET_L, r, N.TokenKind.BRACKET_R), loc: Q(e, t), } })(e, n) case N.TokenKind.BRACE_L: return (function(e, n) { var t = e.token return { kind: a.Kind.OBJECT, fields: ne( e, N.TokenKind.BRACE_L, function() { return (function(e, n) { var t = e.token, r = i(e) return ( $(e, N.TokenKind.COLON), { kind: a.Kind.OBJECT_FIELD, name: r, value: A(e, n), loc: Q(e, t) } ) })(e, n) }, N.TokenKind.BRACE_R ), loc: Q(e, t), } })(e, n) case N.TokenKind.INT: return e.advance(), { kind: a.Kind.INT, value: t.value, loc: Q(e, t) } case N.TokenKind.FLOAT: return e.advance(), { kind: a.Kind.FLOAT, value: t.value, loc: Q(e, t) } case N.TokenKind.STRING: case N.TokenKind.BLOCK_STRING: return b(e) case N.TokenKind.NAME: return 'true' === t.value || 'false' === t.value ? (e.advance(), { kind: a.Kind.BOOLEAN, value: 'true' === t.value, loc: Q(e, t) }) : 'null' === t.value ? (e.advance(), { kind: a.Kind.NULL, loc: Q(e, t) }) : (e.advance(), { kind: a.Kind.ENUM, value: t.value, loc: Q(e, t) }) case N.TokenKind.DOLLAR: if (!n) return v(e) } throw ee(e) } function b(e) { var n = e.token return ( e.advance(), { kind: a.Kind.STRING, value: n.value, block: n.kind === N.TokenKind.BLOCK_STRING, loc: Q(e, n) } ) } function g(e) { return A(e, !0) } function S(e) { return A(e, !1) } function K(e, n) { for (var t = []; H(e, N.TokenKind.AT); ) t.push(D(e, n)) return t } function D(e, n) { var t = e.token return $(e, N.TokenKind.AT), { kind: a.Kind.DIRECTIVE, name: i(e), arguments: y(e, n), loc: Q(e, t) } } function P(e) { var n, t = e.token return ( z(e, N.TokenKind.BRACKET_L) ? ((n = P(e)), $(e, N.TokenKind.BRACKET_R), (n = { kind: a.Kind.LIST_TYPE, type: n, loc: Q(e, t) })) : (n = L(e)), z(e, N.TokenKind.BANG) ? { kind: a.Kind.NON_NULL_TYPE, type: n, loc: Q(e, t) } : n ) } function L(e) { var n = e.token return { kind: a.Kind.NAMED_TYPE, name: i(e), loc: Q(e, n) } } function C(e) { var n = R(e) ? e.lookahead() : e.token if (n.kind === N.TokenKind.NAME) switch (n.value) { case 'schema': return (function(e) { var n = e.token W(e, 'schema') var t = K(e, !0), r = te(e, N.TokenKind.BRACE_L, M, N.TokenKind.BRACE_R) return { kind: a.Kind.SCHEMA_DEFINITION, directives: t, operationTypes: r, loc: Q(e, n) } })(e) case 'scalar': return (function(e) { var n = e.token, t = F(e) W(e, 'scalar') var r = i(e), o = K(e, !0) return { kind: a.Kind.SCALAR_TYPE_DEFINITION, description: t, name: r, directives: o, loc: Q(e, n), } })(e) case 'type': return (function(e) { var n = e.token, t = F(e) W(e, 'type') var r = i(e), o = x(e), c = K(e, !0), u = j(e) return { kind: a.Kind.OBJECT_TYPE_DEFINITION, description: t, name: r, interfaces: o, directives: c, fields: u, loc: Q(e, n), } })(e) case 'interface': return (function(e) { var n = e.token, t = F(e) W(e, 'interface') var r = i(e), o = K(e, !0), c = j(e) return { kind: a.Kind.INTERFACE_TYPE_DEFINITION, description: t, name: r, directives: o, fields: c, loc: Q(e, n), } })(e) case 'union': return (function(e) { var n = e.token, t = F(e) W(e, 'union') var r = i(e), o = K(e, !0), c = V(e) return { kind: a.Kind.UNION_TYPE_DEFINITION, description: t, name: r, directives: o, types: c, loc: Q(e, n), } })(e) case 'enum': return (function(e) { var n = e.token, t = F(e) W(e, 'enum') var r = i(e), o = K(e, !0), c = Y(e) return { kind: a.Kind.ENUM_TYPE_DEFINITION, description: t, name: r, directives: o, values: c, loc: Q(e, n), } })(e) case 'input': return (function(e) { var n = e.token, t = F(e) W(e, 'input') var r = i(e), o = K(e, !0), c = J(e) return { kind: a.Kind.INPUT_OBJECT_TYPE_DEFINITION, description: t, name: r, directives: o, fields: c, loc: Q(e, n), } })(e) case 'directive': return (function(e) { var n = e.token, t = F(e) W(e, 'directive'), $(e, N.TokenKind.AT) var r = i(e), o = w(e) W(e, 'on') var c = (function(e) { z(e, N.TokenKind.PIPE) var n = [] do { n.push(X(e)) } while (z(e, N.TokenKind.PIPE)) return n })(e) return { kind: a.Kind.DIRECTIVE_DEFINITION, description: t, name: r, arguments: o, locations: c, loc: Q(e, n), } })(e) } throw ee(e, n) } function R(e) { return H(e, N.TokenKind.STRING) || H(e, N.TokenKind.BLOCK_STRING) } function F(e) { if (R(e)) return b(e) } function M(e) { var n = e.token, t = s(e) $(e, N.TokenKind.COLON) var r = L(e) return { kind: a.Kind.OPERATION_TYPE_DEFINITION, operation: t, type: r, loc: Q(e, n) } } function x(e) { var n = [] if (Z(e, 'implements')) { z(e, N.TokenKind.AMP) do { n.push(L(e)) } while ( z(e, N.TokenKind.AMP) || (e.options.allowLegacySDLImplementsInterfaces && H(e, N.TokenKind.NAME)) ) } return n } function j(e) { return e.options.allowLegacySDLEmptyFields && H(e, N.TokenKind.BRACE_L) && e.lookahead().kind === N.TokenKind.BRACE_R ? (e.advance(), e.advance(), []) : H(e, N.TokenKind.BRACE_L) ? te(e, N.TokenKind.BRACE_L, B, N.TokenKind.BRACE_R) : [] } function B(e) { var n = e.token, t = F(e), r = i(e), o = w(e) $(e, N.TokenKind.COLON) var c = P(e), u = K(e, !0) return { kind: a.Kind.FIELD_DEFINITION, description: t, name: r, arguments: o, type: c, directives: u, loc: Q(e, n), } } function w(e) { return H(e, N.TokenKind.PAREN_L) ? te(e, N.TokenKind.PAREN_L, U, N.TokenKind.PAREN_R) : [] } function U(e) { var n = e.token, t = F(e), r = i(e) $(e, N.TokenKind.COLON) var o, c = P(e) z(e, N.TokenKind.EQUALS) && (o = g(e)) var u = K(e, !0) return { kind: a.Kind.INPUT_VALUE_DEFINITION, description: t, name: r, type: c, defaultValue: o, directives: u, loc: Q(e, n), } } function V(e) { var n = [] if (z(e, N.TokenKind.EQUALS)) { z(e, N.TokenKind.PIPE) do { n.push(L(e)) } while (z(e, N.TokenKind.PIPE)) } return n } function Y(e) { return H(e, N.TokenKind.BRACE_L) ? te(e, N.TokenKind.BRACE_L, G, N.TokenKind.BRACE_R) : [] } function G(e) { var n = e.token, t = F(e), r = i(e), o = K(e, !0) return { kind: a.Kind.ENUM_VALUE_DEFINITION, description: t, name: r, directives: o, loc: Q(e, n) } } function J(e) { return H(e, N.TokenKind.BRACE_L) ? te(e, N.TokenKind.BRACE_L, U, N.TokenKind.BRACE_R) : [] } function X(e) { var n = e.token, t = i(e) if (k.DirectiveLocation.hasOwnProperty(t.value)) return t throw ee(e, n) } function Q(e, n) { if (!e.options.noLocation) return new q(n, e.lastToken, e.source) } function q(e, n, t) { ;(this.start = e.start), (this.end = n.end), (this.startToken = e), (this.endToken = n), (this.source = t) } function H(e, n) { return e.token.kind === n } function $(e, n) { var t = e.token if (t.kind === n) return e.advance(), t throw (0, T.syntaxError)(e.source, t.start, 'Expected '.concat(n, ', found ').concat((0, N.getTokenDesc)(t))) } function z(e, n) { var t = e.token if (t.kind === n) return e.advance(), t } function W(e, n) { var t = e.token if (t.kind === N.TokenKind.NAME && t.value === n) return e.advance(), t throw (0, T.syntaxError)(e.source, t.start, 'Expected "'.concat(n, '", found ').concat((0, N.getTokenDesc)(t))) } function Z(e, n) { var t = e.token if (t.kind === N.TokenKind.NAME && t.value === n) return e.advance(), t } function ee(e, n) { var t = n || e.token return (0, T.syntaxError)(e.source, t.start, 'Unexpected '.concat((0, N.getTokenDesc)(t))) } function ne(e, n, t, r) { $(e, n) for (var i = []; !z(e, r); ) i.push(t(e)) return i } function te(e, n, t, r) { $(e, n) for (var i = [t(e)]; !z(e, r); ) i.push(t(e)) return i } ;(0, r(u).default)(q, function() { return { start: this.start, end: this.end } }) }) r(O) var _ = i(function(e, n) { Object.defineProperty(n, '__esModule', { value: !0 }), (n.visit = function(e, n) { var t = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : i, u = void 0, d = Array.isArray(e), s = [e], l = -1, f = [], v = void 0, E = void 0, T = void 0, p = [], N = [], I = e do { var y = ++l === s.length, m = y && 0 !== f.length if (y) { if (((E = 0 === N.length ? void 0 : p[p.length - 1]), (v = T), (T = N.pop()), m)) { if (d) v = v.slice() else { for (var k = {}, O = Object.keys(v), _ = 0; _ < O.length; _++) { var h = O[_] k[h] = v[h] } v = k } for (var A = 0, b = 0; b < f.length; b++) { var g = f[b][0], S = f[b][1] d && (g -= A), d && null === S ? (v.splice(g, 1), A++) : (v[g] = S) } } ;(l = u.index), (s = u.keys), (f = u.edits), (d = u.inArray), (u = u.prev) } else { if (((E = T ? (d ? l : s[l]) : void 0), null === (v = T ? T[E] : I) || void 0 === v)) continue T && p.push(E) } var K = void 0 if (!Array.isArray(v)) { if (!a(v)) throw new Error('Invalid AST Node: ' + (0, r.default)(v)) var D = c(n, v.kind, y) if (D) { if ((K = D.call(n, v, E, T, p, N)) === o) break if (!1 === K) { if (!y) { p.pop() continue } } else if (void 0 !== K && (f.push([E, K]), !y)) { if (!a(K)) { p.pop() continue } v = K } } } void 0 === K && m && f.push([E, v]), y ? p.pop() : ((u = { inArray: d, index: l, keys: s, edits: f, prev: u }), (d = Array.isArray(v)), (s = d ? v : t[v.kind] || []), (l = -1), (f = []), T && N.push(T), (T = v)) } while (void 0 !== u) 0 !== f.length && (I = f[f.length - 1][1]) return I }), (n.visitInParallel = function(e) { var n = new Array(e.length) return { enter: function(t) { for (var r = 0; r < e.length; r++) if (!n[r]) { var i = c(e[r], t.kind, !1) if (i) { var a = i.apply(e[r], arguments) if (!1 === a) n[r] = t else if (a === o) n[r] = o else if (void 0 !== a) return a } } }, leave: function(t) { for (var r = 0; r < e.length; r++) if (n[r]) n[r] === t && (n[r] = null) else { var i = c(e[r], t.kind, !0) if (i) { var a = i.apply(e[r], arguments) if (a === o) n[r] = o else if (void 0 !== a && !1 !== a) return a } } }, } }), (n.visitWithTypeInfo = function(e, n) { return { enter: function(t) { e.enter(t) var r = c(n, t.kind, !1) if (r) { var i = r.apply(n, arguments) return void 0 !== i && (e.leave(t), a(i) && e.enter(i)), i } }, leave: function(t) { var r, i = c(n, t.kind, !0) return i && (r = i.apply(n, arguments)), e.leave(t), r }, } }), (n.getVisitFn = c), (n.BREAK = n.QueryDocumentKeys = void 0) var t, r = (t = I) && t.__esModule ? t : { default: t } var i = { Name: [], Document: ['definitions'], OperationDefinition: ['name', 'variableDefinitions', 'directives', 'selectionSet'], VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'], Variable: ['name'], SelectionSet: ['selections'], Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'], Argument: ['name', 'value'], FragmentSpread: ['name', 'directives'], InlineFragment: ['typeCondition', 'directives', 'selectionSet'], FragmentDefinition: ['name', 'variableDefinitions', 'typeCondition', 'directives', 'selectionSet'], IntValue: [], FloatValue: [], StringValue: [], BooleanValue: [], NullValue: [], EnumValue: [], ListValue: ['values'], ObjectValue: ['fields'], ObjectField: ['name', 'value'], Directive: ['name', 'arguments'], NamedType: ['name'], ListType: ['type'], NonNullType: ['type'], SchemaDefinition: ['directives', 'operationTypes'], OperationTypeDefinition: ['type'], ScalarTypeDefinition: ['description', 'name', 'directives'], ObjectTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'], FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'], InputValueDefinition: ['description', 'name', 'type', 'defaultValue', 'directives'], InterfaceTypeDefinition: ['description', 'name', 'directives', 'fields'], UnionTypeDefinition: ['description', 'name', 'directives', 'types'], EnumTypeDefinition: ['description', 'name', 'directives', 'values'], EnumValueDefinition: ['description', 'name', 'directives'], InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'], DirectiveDefinition: ['description', 'name', 'arguments', 'locations'], SchemaExtension: ['directives', 'operationTypes'], ScalarTypeExtension: ['name', 'directives'], ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'], InterfaceTypeExtension: ['name', 'directives', 'fields'], UnionTypeExtension: ['name', 'directives', 'types'], EnumTypeExtension: ['name', 'directives', 'values'], InputObjectTypeExtension: ['name', 'directives', 'fields'], } n.QueryDocumentKeys = i var o = {} function a(e) { return Boolean(e && 'string' == typeof e.kind) } function c(e, n, t) { var r = e[n] if (r) { if (!t && 'function' == typeof r) return r var i = t ? r.leave : r.enter if ('function' == typeof i) return i } else { var o = t ? e.leave : e.enter if (o) { if ('function' == typeof o) return o var a = o[n] if ('function' == typeof a) return a } } } n.BREAK = o }) r(_) var h = i(function(e, n) { Object.defineProperty(n, '__esModule', { value: !0 }), (n.print = function(e) { return (0, _.visit)(e, { leave: t }) }) var t = { Name: function(e) { return e.value }, Variable: function(e) { return '$' + e.name }, Document: function(e) { return i(e.definitions, '\n\n') + '\n' }, OperationDefinition: function(e) { var n = e.operation, t = e.name, r = a('(', i(e.variableDefinitions, ', '), ')'), o = i(e.directives, ' '), c = e.selectionSet return t || o || r || 'query' !== n ? i([n, i([t, r]), o, c], ' ') : c }, VariableDefinition: function(e) { var n = e.variable, t = e.type, r = e.defaultValue, o = e.directives return n + ': ' + t + a(' = ', r) + a(' ', i(o, ' ')) }, SelectionSet: function(e) { return o(e.selections) }, Field: function(e) { var n = e.alias, t = e.name, r = e.arguments, o = e.directives, c = e.selectionSet return i([a('', n, ': ') + t + a('(', i(r, ', '), ')'), i(o, ' '), c], ' ') }, Argument: function(e) { return e.name + ': ' + e.value }, FragmentSpread: function(e) { return '...' + e.name + a(' ', i(e.directives, ' ')) }, InlineFragment: function(e) { var n = e.typeCondition, t = e.directives, r = e.selectionSet return i(['...', a('on ', n), i(t, ' '), r], ' ') }, FragmentDefinition: function(e) { var n = e.name, t = e.typeCondition, r = e.variableDefinitions, o = e.directives, c = e.selectionSet return ( 'fragment '.concat(n).concat(a('(', i(r, ', '), ')'), ' ') + 'on '.concat(t, ' ').concat(a('', i(o, ' '), ' ')) + c ) }, IntValue: function(e) { return e.value }, FloatValue: function(e) { return e.value }, StringValue: function(e, n) { var t = e.value return e.block ? (0, p.printBlockString)(t, 'description' === n ? '' : ' ') : JSON.stringify(t) }, BooleanValue: function(e) { return e.value ? 'true' : 'false' }, NullValue: function() { return 'null' }, EnumValue: function(e) { return e.value }, ListValue: function(e) { return '[' + i(e.values, ', ') + ']' }, ObjectValue: function(e) { return '{' + i(e.fields, ', ') + '}' }, ObjectField: function(e) { return e.name + ': ' + e.value }, Directive: function(e) { return '@' + e.name + a('(', i(e.arguments, ', '), ')') }, NamedType: function(e) { return e.name }, ListType: function(e) { return '[' + e.type + ']' }, NonNullType: function(e) { return e.type + '!' }, SchemaDefinition: function(e) { var n = e.directives, t = e.operationTypes return i(['schema', i(n, ' '), o(t)], ' ') }, OperationTypeDefinition: function(e) { return e.operation + ': ' + e.type }, ScalarTypeDefinition: r(function(e) { return i(['scalar', e.name, i(e.directives, ' ')], ' ') }), ObjectTypeDefinition: r(function(e) { var n = e.name, t = e.interfaces, r = e.directives, c = e.fields return i(['type', n, a('implements ', i(t, ' & ')), i(r, ' '), o(c)], ' ') }), FieldDefinition: r(function(e) { var n = e.name, t = e.arguments, r = e.type, o = e.directives return ( n + (d(t) ? a('(\n', c(i(t, '\n')), '\n)') : a('(', i(t, ', '), ')')) + ': ' + r + a(' ', i(o, ' ')) ) }), InputValueDefinition: r(function(e) { var n = e.name, t = e.type, r = e.defaultValue, o = e.directives return i([n + ': ' + t, a('= ', r), i(o, ' ')], ' ') }), InterfaceTypeDefinition: r(function(e) { var n = e.name, t = e.directives, r = e.fields return i(['interface', n, i(t, ' '), o(r)], ' ') }), UnionTypeDefinition: r(function(e) { var n = e.name, t = e.directives, r = e.types return i(['union', n, i(t, ' '), r && 0 !== r.length ? '= ' + i(r, ' | ') : ''], ' ') }), EnumTypeDefinition: r(function(e) { var n = e.name, t = e.directives, r = e.values return i(['enum', n, i(t, ' '), o(r)], ' ') }), EnumValueDefinition: r(function(e) { return i([e.name, i(e.directives, ' ')], ' ') }), InputObjectTypeDefinition: r(function(e) { var n = e.name, t = e.directives, r = e.fields return i(['input', n, i(t, ' '), o(r)], ' ') }), DirectiveDefinition: r(function(e) { var n = e.name, t = e.arguments, r = e.locations return ( 'directive @' + n + (d(t) ? a('(\n', c(i(t, '\n')), '\n)') : a('(', i(t, ', '), ')')) + ' on ' + i(r, ' | ') ) }), SchemaExtension: function(e) { var n = e.directives, t = e.operationTypes return i(['extend schema', i(n, ' '), o(t)], ' ') }, ScalarTypeExtension: function(e) { return i(['extend scalar', e.name, i(e.directives, ' ')], ' ') }, ObjectTypeExtension: function(e) { var n = e.name, t = e.interfaces, r = e.directives, c = e.fields return i(['extend type', n, a('implements ', i(t, ' & ')), i(r, ' '), o(c)], ' ') }, InterfaceTypeExtension: function(e) { var n = e.name, t = e.directives, r = e.fields return i(['extend interface', n, i(t, ' '), o(r)], ' ') }, UnionTypeExtension: function(e) { var n = e.name, t = e.directives, r = e.types return i(['extend union', n, i(t, ' '), r && 0 !== r.length ? '= ' + i(r, ' | ') : ''], ' ') }, EnumTypeExtension: function(e) { var n = e.name, t = e.directives, r = e.values return i(['extend enum', n, i(t, ' '), o(r)], ' ') }, InputObjectTypeExtension: function(e) { var n = e.name, t = e.directives, r = e.fields return i(['extend input', n, i(t, ' '), o(r)], ' ') }, } function r(e) { return function(n) { return i([n.description, e(n)], '\n') } } function i(e, n) { return e ? e .filter(function(e) { return e }) .join(n || '') : '' } function o(e) { return e && 0 !== e.length ? '{\n' + c(i(e, '\n')) + '\n}' : '' } function a(e, n, t) { return n ? e + n + (t || '') : '' } function c(e) { return e && ' ' + e.replace(/\n/g, '\n ') } function u(e) { return -1 !== e.indexOf('\n') } function d(e) { return e && e.some(u) } }) r(h) var A = i(function(e, n) { function t(e) { return e.kind === a.Kind.OPERATION_DEFINITION || e.kind === a.Kind.FRAGMENT_DEFINITION } function r(e) { return e.kind === a.Kind.SCHEMA_DEFINITION || i(e) || e.kind === a.Kind.DIRECTIVE_DEFINITION } function i(e) { return ( e.kind === a.Kind.SCALAR_TYPE_DEFINITION || e.kind === a.Kind.OBJECT_TYPE_DEFINITION || e.kind === a.Kind.INTERFACE_TYPE_DEFINITION || e.kind === a.Kind.UNION_TYPE_DEFINITION || e.kind === a.Kind.ENUM_TYPE_DEFINITION || e.kind === a.Kind.INPUT_OBJECT_TYPE_DEFINITION ) } function o(e) { return e.kind === a.Kind.SCHEMA_EXTENSION || c(e) } function c(e) { return ( e.kind === a.Kind.SCALAR_TYPE_EXTENSION || e.kind === a.Kind.OBJECT_TYPE_EXTENSION || e.kind === a.Kind.INTERFACE_TYPE_EXTENSION || e.kind === a.Kind.UNION_TYPE_EXTENSION || e.kind === a.Kind.ENUM_TYPE_EXTENSION || e.kind === a.Kind.INPUT_OBJECT_TYPE_EXTENSION ) } Object.defineProperty(n, '__esModule', { value: !0 }), (n.isDefinitionNode = function(e) { return t(e) || r(e) || o(e) }), (n.isExecutableDefinitionNode = t), (n.isSelectionNode = function(e) { return e.kind === a.Kind.FIELD || e.kind === a.Kind.FRAGMENT_SPREAD || e.kind === a.Kind.INLINE_FRAGMENT }), (n.isValueNode = function(e) { return ( e.kind === a.Kind.VARIABLE || e.kind === a.Kind.INT || e.kind === a.Kind.FLOAT || e.kind === a.Kind.STRING || e.kind === a.Kind.BOOLEAN || e.kind === a.Kind.NULL || e.kind === a.Kind.ENUM || e.kind === a.Kind.LIST || e.kind === a.Kind.OBJECT ) }), (n.isTypeNode = function(e) { return e.kind === a.Kind.NAMED_TYPE || e.kind === a.Kind.LIST_TYPE || e.kind === a.Kind.NON_NULL_TYPE }), (n.isTypeSystemDefinitionNode = r), (n.isTypeDefinitionNode = i), (n.isTypeSystemExtensionNode = o), (n.isTypeExtensionNode = c) }) r(A) var b = i(function(e, n) { Object.defineProperty(n, '__esModule', { value: !0 }), Object.defineProperty(n, 'getLocation', { enumerable: !0, get: function() { return o.getLocation }, }), Object.defineProperty(n, 'Kind', { enumerable: !0, get: function() { return a.Kind }, }), Object.defineProperty(n, 'createLexer', { enumerable: !0, get: function() { return N.createLexer }, }), Object.defineProperty(n, 'TokenKind', { enumerable: !0, get: function() { return N.TokenKind }, }), Object.defineProperty(n, 'parse', { enumerable: !0, get: function() { return O.parse }, }), Object.defineProperty(n, 'parseValue', { enumerable: !0, get: function() { return O.parseValue }, }), Object.defineProperty(n, 'parseType', { enumerable: !0, get: function() { return O.parseType }, }), Object.defineProperty(n, 'print', { enumerable: !0, get: function() { return h.print }, }), Object.defineProperty(n, 'Source', { enumerable: !0, get: function() { return m.Source }, }), Object.defineProperty(n, 'visit', { enumerable: !0, get: function() { return _.visit }, }), Object.defineProperty(n, 'visitInParallel', { enumerable: !0, get: function() { return _.visitInParallel }, }), Object.defineProperty(n, 'visitWithTypeInfo', { enumerable: !0, get: function() { return _.visitWithTypeInfo }, }), Object.defineProperty(n, 'getVisitFn', { enumerable: !0, get: function() { return _.getVisitFn }, }), Object.defineProperty(n, 'BREAK', { enumerable: !0, get: function() { return _.BREAK }, }), Object.defineProperty(n, 'isDefinitionNode', { enumerable: !0, get: function() { return A.isDefinitionNode }, }), Object.defineProperty(n, 'isExecutableDefinitionNode', { enumerable: !0, get: function() { return A.isExecutableDefinitionNode }, }), Object.defineProperty(n, 'isSelectionNode', { enumerable: !0, get: function() { return A.isSelectionNode }, }), Object.defineProperty(n, 'isValueNode', { enumerable: !0, get: function() { return A.isValueNode }, }), Object.defineProperty(n, 'isTypeNode', { enumerable: !0, get: function() { return A.isTypeNode }, }), Object.defineProperty(n, 'isTypeSystemDefinitionNode', { enumerable: !0, get: function() { return A.isTypeSystemDefinitionNode }, }), Object.defineProperty(n, 'isTypeDefinitionNode', { enumerable: !0, get: function() { return A.isTypeDefinitionNode }, }), Object.defineProperty(n, 'isTypeSystemExtensionNode', { enumerable: !0, get: function() { return A.isTypeSystemExtensionNode }, }), Object.defineProperty(n, 'isTypeExtensionNode', { enumerable: !0, get: function() { return A.isTypeExtensionNode }, }), Object.defineProperty(n, 'DirectiveLocation', { enumerable: !0, get: function() { return k.DirectiveLocation }, }) }) return ( r(b), { parsers: { graphql: { parse: function(t) { var r = b try { var i = (function(e, n) { var t = { allowLegacySDLImplementsInterfaces: !1, experimentalFragmentVariables: !0 } try { return e(n, t) } catch (r) { return (t.allowLegacySDLImplementsInterfaces = !0), e(n, t) } })(r.parse, t) return ( (i.comments = (function(e) { for (var n = [], t = e.loc.startToken.next; '<EOF>' !== t.kind; ) 'Comment' === t.kind && (Object.assign(t, { column: t.column - 1 }), n.push(t)), (t = t.next) return n })(i)), (function n(t) { if (t && 'object' === e(t)) for (var r in (delete t.startToken, delete t.endToken, delete t.prev, delete t.next, t)) n(t[r]) return t })(i), i ) } catch (e) { throw e instanceof T.GraphQLError ? n(e.message, { start: { line: e.locations[0].line, column: e.locations[0].column } }) : e } }, astFormat: 'graphql', hasPragma: t, locStart: function(e) { return 'number' == typeof e.start ? e.start : e.loc && e.loc.start }, locEnd: function(e) { return 'number' == typeof e.end ? e.end : e.loc && e.loc.end }, }, }, } ) })
41.62446
120
0.31105
36da05f0ba4412e7bf15a53540b29f5b7256f164
552
js
JavaScript
app/utilities/Api.js
yaswanthsvist/altimetrik-assessment
1089ba47f167964306ee64a71598feada2c57282
[ "MIT" ]
null
null
null
app/utilities/Api.js
yaswanthsvist/altimetrik-assessment
1089ba47f167964306ee64a71598feada2c57282
[ "MIT" ]
null
null
null
app/utilities/Api.js
yaswanthsvist/altimetrik-assessment
1089ba47f167964306ee64a71598feada2c57282
[ "MIT" ]
null
null
null
export const loginUserApi = (username, password) => fetch( `http://localhost:4001/login/?username=${username}&password=${password}` ) export const signupUserApi = userDetails => fetch(`http://localhost:4001/signup`, { method: 'POST', // *GET, POST, PUT, DELETE, etc. headers: { Accept: 'application/json, text/plain, */*', 'Content-Type': 'application/json', }, body: JSON.stringify({ ...userDetails }), }) export const getUserDataApi = username => fetch(`http://localhost:4001/getData/?username=${username}`)
34.5
76
0.650362
36dac97fda5f1335221e1e5b01942d0c165edccc
1,827
js
JavaScript
events/app.js
brianokanga/modern-javascript
b54f65d0f3ac34f3f804e7bba22196a751204b34
[ "MIT" ]
null
null
null
events/app.js
brianokanga/modern-javascript
b54f65d0f3ac34f3f804e7bba22196a751204b34
[ "MIT" ]
null
null
null
events/app.js
brianokanga/modern-javascript
b54f65d0f3ac34f3f804e7bba22196a751204b34
[ "MIT" ]
null
null
null
// // document.getElementById() // console.log(document.getElementById('task-title')); // console.log(document.getElementById('task-title').id); // console.log(document.getElementById('task-title').className); // // change styling // document.getElementById('task-title').style.background = '#333'; // document.getElementById('task-title').style.color = '#fff'; // document.getElementById('task-title').style.background = '#5px'; // // document.querySelector // console.log(document.querySelector('#task-title')); // console.log(document.querySelector('.card-title')); // console.log(document.querySelector('#h5')); // const listItems = document.querySelector('li'); // listItems.style.color = 'red'; // listItems.textContent = 'wagwan'; // const listItems = document.querySelector('ul').getElementsByClassName('collection-item'); // const liOdd = document.querySelectorAll('li:nth-child(odd)'); // const liEven = document.querySelectorAll('li:nth-child(even)'); // liOdd.forEach(function(li, index){ // li.style.background = '#ccc'; // }); // for(let i = 0; i < liEven.length; i++){ // liEven[i].style.background = 'red'; // } // // Create element // const li = document.createElement('li'); // //add class // li.className = 'collection-item'; // //add id // li.id = 'new-item'; // //add attributes // li.setAttribute('title', 'new item'); // //create text node // li.appendChild(document.createTextNode('hello world')); // //append li as achild to the ul // document.querySelector('ul.collection').appendChild(li); // console.log(li); // Event listeners // document.querySelector('.clear-tasks').addEventListener('click', function (e) { // console.log('Hello World'); // }); //set local storage localStorage.setItem('name', 'John'); //set session storage sessionStorage.setItem('name', 'Maria');
28.107692
92
0.683087
36db0c75673ed7a70d4fe5e6e634b2754c38529f
1,593
js
JavaScript
lib/dynamic.js
ematipico/poolifier
f687ef06cc17c012525d693729ddc3197957b6fa
[ "MIT" ]
null
null
null
lib/dynamic.js
ematipico/poolifier
f687ef06cc17c012525d693729ddc3197957b6fa
[ "MIT" ]
null
null
null
lib/dynamic.js
ematipico/poolifier
f687ef06cc17c012525d693729ddc3197957b6fa
[ "MIT" ]
null
null
null
'use strict' const FixedThreadPool = require('./fixed') const EventEmitter = require('events') class MyEmitter extends EventEmitter {} /** * A thread pool with a min/max number of threads , is possible to execute tasks in sync or async mode as you prefer. <br> * This thread pool will create new workers when the other ones are busy, until the max number of threads, * when the max number of threads is reached, an event will be emitted , if you want to listen this event use the emitter method. * @author Alessandro Pio Ardizio * @since 0.0.1 */ class DynamicThreadPool extends FixedThreadPool { /** * * @param {Number} min Min number of threads that will be always active * @param {Number} max Max number of threads that will be active */ constructor (min, max, filename, opts) { super(min, filename, opts) this.max = max this.emitter = new MyEmitter() } _chooseWorker () { let worker for (const entry of this.tasks) { if (entry[1] === 0) { worker = entry[0] break } } if (worker) { // a worker is free, use it return worker } else { if (this.workers.length === this.max) { this.emitter.emit('FullPool') return super._chooseWorker() } // all workers are busy create a new worker const worker = this._newWorker() worker.port2.on('message', (message) => { if (message.kill) { worker.postMessage({ kill: 1 }) worker.terminate() } }) return worker } } } module.exports = DynamicThreadPool
28.446429
129
0.62963
36db12dafe6d43a5e9038307d97821950653a1d2
1,553
js
JavaScript
src/main/webapp/js/registervalidate.js
vietduc01100001/test-english-website
267a92e71c3d2b62664cbb1b0dbd6497f1f57682
[ "MIT" ]
1
2018-04-19T00:59:14.000Z
2018-04-19T00:59:14.000Z
src/main/webapp/js/registervalidate.js
vietduc01100001/test-english-website
267a92e71c3d2b62664cbb1b0dbd6497f1f57682
[ "MIT" ]
null
null
null
src/main/webapp/js/registervalidate.js
vietduc01100001/test-english-website
267a92e71c3d2b62664cbb1b0dbd6497f1f57682
[ "MIT" ]
null
null
null
function validateForm() { var spanNotice = document.getElementById("notice"); var error = ""; var inputEmail = document.getElementById("email"); var inputPassword = document.getElementById("password"); var inputRePassword = document.getElementById("rePassword"); var inputName = document.getElementById("name"); var email = inputEmail.value; var password = inputPassword.value.replace(/\s/g, ""); var rePassword = inputRePassword.value.replace(/\s/g, ""); var name = inputName.value; if (!isEmailValid(email)) { error = "Vui lòng nhập email."; inputEmail.focus(); } else if (email.length > 50) { error = "Email không được dài quá 50 kí tự."; inputEmail.focus(); } else if (password.length < 6) { error = "Mật khẩu phải dài tối thiểu 6 kí tự."; inputPassword.focus(); } else if (rePassword == "") { error = "Vui lòng nhập lại mật khẩu."; inputRePassword.focus(); } else if (password != rePassword) { error = "Mật khẩu không trùng khớp."; inputRePassword.focus(); } else if (name.replace(/\s/g, "") == "") { error = "Vui lòng nhập họ và tên."; inputName.focus(); } else if (name.length > 50) { error = "Họ và tên không được dài quá 50 kí tự."; inputName.focus(); } function isEmailValid(email) { var regex = /(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/; return regex.test(email); } if (error == "") return true; else { spanNotice.innerHTML = error; return false; } }
27.732143
168
0.611075
36db92dce133ca83d219445fc0ced7dfb23d33dd
1,503
js
JavaScript
utils.js
QinWentian/anteran
fac415a2106dbd003ab8e9fb7efdc7fae2f9dc86
[ "MIT" ]
null
null
null
utils.js
QinWentian/anteran
fac415a2106dbd003ab8e9fb7efdc7fae2f9dc86
[ "MIT" ]
null
null
null
utils.js
QinWentian/anteran
fac415a2106dbd003ab8e9fb7efdc7fae2f9dc86
[ "MIT" ]
null
null
null
/* eslint-disable no-throw-literal */ const Util = {} module.exports = Util Util.responseError = async (res, err) => { res.setHeader('content-type', 'application/vnd.api+json') res.status(err.status || 400) const errorJSON = { errors: [] } if (err instanceof Array) { const adjustErr = err.map(r => { errorJSON.errors.push(r) return r }) await Promise.all(adjustErr).then(errData => { res.json(errorJSON) return errData }) return } console.error('capture error ===>', err) console.error('capture error MESSAGE ===>', err.message) const newError = { status: err.status || 400, code: err.code || undefined, title: err.title || undefined, detail: err.detail || 'Bad request.', source: err.source || undefined, message: err.message || err.sqlMessage } errorJSON.errors.push(newError) res.json(errorJSON) } Util.responseSuccess = async (res, response) => { return res.send({ success: true, data: response }) } Util.responseNotFound = async (res, response) => { return res.send({ success: true, data: response, message: 'data not found' }) } Util.globalLogging = async (req) => { const logStatus = { type: 'GLOBAL_LOG', path: req ? `${req.originalUrl}` : null, date: new Date(), body: req ? JSON.stringify(req.body) : null, query: req ? JSON.stringify(req.query) : null, routes: req ? JSON.stringify(req.route) : null } console.log(logStatus) }
22.432836
59
0.622089
36dba89db3600d5dfe2bac69d82be2f3168177d2
2,495
js
JavaScript
routes/prototype/photo-checker/steps.js
versatil56/passports-prototype-v2
4ea4db05b5fec05418ef6e45c7576f304326ac74
[ "MIT" ]
2
2018-03-31T10:51:27.000Z
2019-01-14T16:57:13.000Z
routes/prototype/photo-checker/steps.js
versatil56/passports-prototype-v2
4ea4db05b5fec05418ef6e45c7576f304326ac74
[ "MIT" ]
9
2018-07-18T10:49:50.000Z
2019-02-07T15:03:39.000Z
routes/prototype/photo-checker/steps.js
versatil56/passports-prototype-v2
4ea4db05b5fec05418ef6e45c7576f304326ac74
[ "MIT" ]
2
2019-11-12T08:44:51.000Z
2021-04-11T09:04:40.000Z
module.exports = { '/': { next: '/dob' }, '/dob': { controller: require('../../../controllers/check-age-group'), next: '/upload', backLink: './', fields: [ 'age-group' ] }, // '/how-to-get-a-digital-photo': { // next: '/photo-guidance' // }, // '/choose-photo-method': { // next: '/photo-guidance', // fields: [ // 'choose-photo' // ], // forks: [{ // target: '/photo-guidance', // condition: function (req, res) { // return req.session['hmpo-wizard-common']['choose-photo'] == 'upload'; // } // }, { // target: '/retrieve', // condition: function (req, res) { // return req.session['hmpo-wizard-common']['choose-photo'] == 'code'; // } // }] // }, '/photo-guidance': { backLink: './upload' // next: '/upload', }, '/upload': { controller: require('../../../controllers/check-photo-file-name'), next: '/processing-or-retrieving-image', forks: [{ // For prototype purpose, set choose-photo method var to upload condition: function (req, res) { req.session['hmpo-wizard-common']['choose-photo'] = 'upload' } }] }, '/processing-or-retrieving-image': {}, '/retrieve': { next: '/processing-or-retrieving-image', fields: [ 'photo-code-path' ] }, '/fetch-photo-result': { controller: require('../../../controllers/fetch-photo-result') }, '/check-and-submit-passed-photo': { next: '/../photo-checker' }, '/check-and-submit-photo': { next: '/../photo-checker' }, '/check-and-submit-photo-variation-1': { next: '/../photo-checker' }, '/check-and-submit-photo-variation-2': { next: '/../photo-checker' }, '/check-and-submit-photo-variation-3': { next: '/../photo-checker' }, '/check-and-submit-photo-variation-4': { next: '/../photo-checker' }, '/check-and-submit-photo-variation-5': { next: '/../photo-checker' }, '/check-and-submit-photo-variation-6': { next: '/../photo-checker' }, '/not-accepted': { next: '/../photo-checker' }, '/code-error': { next: '/choose-photo-method', backLink: './retrieve' } };
28.678161
88
0.468938
36dc6beb4fc417e2d79163889f05219ed961da20
3,952
js
JavaScript
Gruntfile.js
roperzh/roperzh.github.io
8720ba67b5661f155f9146e3d5450ba6cc2c3b81
[ "MIT" ]
null
null
null
Gruntfile.js
roperzh/roperzh.github.io
8720ba67b5661f155f9146e3d5450ba6cc2c3b81
[ "MIT" ]
3
2015-11-03T21:34:43.000Z
2015-11-16T18:34:06.000Z
Gruntfile.js
roperzh/roperzh.github.io
8720ba67b5661f155f9146e3d5450ba6cc2c3b81
[ "MIT" ]
null
null
null
'use strict'; module.exports = function(grunt) { // Load all tasks require('jit-grunt')(grunt); // Show elapsed time require('time-grunt')(grunt); var jsFileList = [ 'static/js/vendor/*.js', 'static/js/_global-definitions.js', 'static/js/services/_*.js', 'static/js/behaviors/_*.js', 'static/js/main.js' ]; grunt.initConfig({ critical: { options: { base: './public', css: [ 'public/build/css/main.css' ], width: 320, height: 480, minify: true }, home: { src: 'public/index.html', dest: 'public/index.html' }, about: { src: 'public/about/index.html', dest: 'public/about/index.html' }, work: { src: 'public/work/index.html', dest: 'public/work/index.html' } }, jshint: { options: { jshintrc: '.jshintrc' }, all: [ 'Gruntfile.js', 'static/js/*.js', '!static/build/js/main.js' ] }, sass: { options: { sourceMap: false }, dev: { files: { 'static/build/css/main.css': 'static/scss/main.scss' } }, build: { files: { 'static/build/css/main.css': 'static/scss/main.scss' } } }, concat: { options: { separator: ';', }, dist: { src: [jsFileList], dest: 'static/build/js/main.js', }, }, uglify: { dist: { files: { 'static/build/js/main.js': [jsFileList] } } }, cssmin: { options: { // shorthandCompacting: false, // roundingPrecision: -1 }, build: { files: { 'static/build/css/main.css': ['static/build/css/main.css'] } } }, autoprefixer: { options: { browsers: ['last 2 versions', 'ie 8', 'ie 9', 'android 2.3', 'android 4', 'opera 12'] }, dev: { options: { map: { prev: 'static/build/css/' } }, src: 'static/build/css/main.css' }, build: { src: 'static/build/css/main.css' } }, modernizr: { build: { devFile: 'static/vendor/modernizr/modernizr.js', outputFile: 'static/js/vendor/modernizr.js', files: { 'src': [ ['static/build/js/main.js'], ['static/build/css/main.css'] ] }, extra: { shiv: false }, uglify: true, parseFiles: true } }, grunticon: { myIcons: { files: [{ expand: true, cwd: 'static/img/icons', src: ['*.svg', '*.png'], dest: "static/build/css/icons" }], options: { enhanceSVG: true } } }, imagemin: { build: { files: [{ expand: true, cwd: 'static/img/', src: ['**/*.{png,jpg,gif}'], dest: 'static/build/img/' }] } }, watch: { sass: { files: [ 'static/scss/*.scss', 'static/scss/**/*.scss' ], tasks: ['sass:dev', 'autoprefixer:dev'], options: { spawn: false } }, js: { files: [ jsFileList ], tasks: ['newer:concat'], options: { spawn: false } }, images: { files: [ 'static/img/*.*', 'static/img/**/*.*' ], tasks: ['imagemin'], options: { spawn: false } } } }); // Register tasks grunt.registerTask('default', [ "watch" ]); grunt.registerTask('build', [ 'sass:build', 'autoprefixer:build', 'cssmin:build', // 'critical:home', // 'critical:about', // 'critical:work', 'uglify', ]); };
20.163265
93
0.427632
36dcc65012676ad62c4dcc42f8bfbe11d0d50cb2
811
js
JavaScript
config/webpack.js
pivotal-cf-experimental/xray
83f174aabb405a2cc54e7720080bf9207ba19ba3
[ "BSD-3-Clause" ]
20
2015-04-27T06:12:13.000Z
2021-08-19T08:30:59.000Z
config/webpack.js
pivotal-cf-experimental/xray
83f174aabb405a2cc54e7720080bf9207ba19ba3
[ "BSD-3-Clause" ]
7
2015-04-27T15:31:43.000Z
2015-11-19T21:04:56.000Z
config/webpack.js
pivotal-cf-experimental/xray
83f174aabb405a2cc54e7720080bf9207ba19ba3
[ "BSD-3-Clause" ]
7
2015-04-30T17:25:38.000Z
2015-11-19T21:01:06.000Z
var CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin'); var commonsChunkPlugin = new CommonsChunkPlugin({ name: 'common', filename: 'common.js' }); module.exports = function(env = null) { return Object.assign({}, { entry: { application: './app/components/application.js', setup: './app/components/setup.js' }, externals: { react: 'React', 'react/addons': 'React' }, module: { loaders: [ {test: /\.js$/, exclude: [/node_modules/], loader: 'babel-loader'}, {test: /\.svg$/, exclude: [/node_modules/], loader: 'svg-loader'} ] }, output: { filename: '[name].js', chunkFilename: '[id].js', pathinfo: true }, plugins: [commonsChunkPlugin] }, env && require(`./webpack/${env}`)); };
27.033333
76
0.579531
36dcd2fd70756251dc046706ef292f140d4ff013
594
js
JavaScript
public/js/app/rewind.js
asmilen/opensea
497e8cd18a547c08007262ec782f377ea3ce5c02
[ "MIT" ]
null
null
null
public/js/app/rewind.js
asmilen/opensea
497e8cd18a547c08007262ec782f377ea3ce5c02
[ "MIT" ]
null
null
null
public/js/app/rewind.js
asmilen/opensea
497e8cd18a547c08007262ec782f377ea3ce5c02
[ "MIT" ]
null
null
null
// CSS import 'bootstrap/dist/css/bootstrap.min.css'; import '@fortawesome/fontawesome-free/css/all.css'; import 'owl.carousel/dist/assets/owl.carousel.css'; import 'owl.carousel/dist/assets/owl.theme.default.min.css'; import '../../css/main.css'; import '../../css/header.css'; import '../../css/rewind-header.css'; import '../../css/nav.css'; import '../../css/rewind-nav.css'; import '../../css/footer.css'; import '../../css/rewind.css'; import '../../css/rewind-popup.css'; import'../../css/fonts.css'; // JS import 'bootstrap'; window.$ = $; import 'owl.carousel'; import '../rewind.js';
29.7
60
0.6633
36ddbb53c9be35f102605e7bd6b2c1e6d8e017cd
3,544
js
JavaScript
lib/transform.js
SimonJang/csv-to-json
2d140ada8592238b52c4ca3f03c479bf6da3dd22
[ "MIT" ]
null
null
null
lib/transform.js
SimonJang/csv-to-json
2d140ada8592238b52c4ca3f03c479bf6da3dd22
[ "MIT" ]
null
null
null
lib/transform.js
SimonJang/csv-to-json
2d140ada8592238b52c4ca3f03c479bf6da3dd22
[ "MIT" ]
null
null
null
'use strict'; const SINGLE = 'SINGLE'; const DOUBLE = 'DOUBLE'; exports.transform = (chunks, headers) => { const dict = Object.create(null); if (headers) { chunks.forEach((value, index) => { const header = headers[index] ? headers[index] : index; dict[header] = value; }); } else { chunks.forEach((value, index) => { dict[index] = value; }); } return JSON.stringify(dict, null, '\t'); }; const findQuoteType = (sentence, delimiter) => { const doubleCommaPattern = /,"+(.*?)"+,{0,1}/g; const doubleSemiPattern = /;"+(.*?)"+;{0,1}/g; if (delimiter === ',') { const double = doubleCommaPattern.test(sentence); return double ? DOUBLE : SINGLE; } const double = doubleSemiPattern.test(sentence); return double ? DOUBLE : SINGLE; }; const getPattern = quoteType => { switch (quoteType) { case SINGLE: return new RegExp(/'(.*?)'/); case DOUBLE: return new RegExp(/"(.*?)"/); default: throw new Error('Unknown quote type'); } }; const clean = (chunk, delimiter) => { let newChunk = chunk; if (chunk[0] === delimiter && chunk.length > 2) { newChunk = newChunk.slice(1); } if (chunk[chunk.length - 1] === delimiter && chunk.length > 2) { newChunk = newChunk.slice(0, newChunk.length - 1); } return newChunk; }; const lazySplit = (sentence, delimiter) => { return sentence.split(delimiter); }; const intelligentSplit = (sentence, quote, delimiter) => { let rootSentence = sentence; const pattern = getPattern(quote); const results = []; let flag = true; let skip = false; let lastPattern; while (flag) { const patternResult = lastPattern ? lastPattern : pattern.exec(rootSentence); skip = (patternResult && patternResult.index !== 0) && !skip; if (!patternResult) { const cleaned = clean(rootSentence, delimiter); const simpleSplits = lazySplit(cleaned, delimiter); for (const split of simpleSplits) { results.push(split); } flag = false; } if ((patternResult && !lastPattern) && !skip) { results.push(patternResult[1]); rootSentence = clean(rootSentence.substring(patternResult[1].length + 2), delimiter); skip = false; lastPattern = undefined; } else if (lastPattern && !skip) { results.push(patternResult[1]); rootSentence = clean(rootSentence.substring(patternResult[1].length + 2), delimiter); skip = false; lastPattern = undefined; } if (skip) { lastPattern = patternResult; const sentenceWithNoQuotes = rootSentence.substring(0, lastPattern.index).trim(); const cleaned = clean(sentenceWithNoQuotes, delimiter); const splitResult = lazySplit(cleaned, delimiter); for (const result of splitResult) { results.push(result); } rootSentence = clean(rootSentence.substring(lastPattern.index), delimiter); } if (pattern.lastIndex === rootSentence.length || rootSentence.trim().length === 0) { flag = false; } } return results; }; const replaceEmptyWithNull = (sentence, delimiter, quoteType) => { const newSentence = quoteType === SINGLE ? sentence.replace(/\s{0,}'{1}\s+'{1}\s{0,1}/g, 'null') : sentence.replace(/\s{0,}"{1}\s+"{1}\s{0,1}/g, 'null'); return delimiter === ',' ? newSentence.replace(/,{1}\s+,/g, ',null,') : newSentence.replace(/;{1}\s+;/g, ';null;'); }; exports.splitter = (chunk, delimiter) => { const quoteType = findQuoteType(chunk, delimiter); const transformedChunk = replaceEmptyWithNull(chunk, delimiter, quoteType); const transformations = intelligentSplit(transformedChunk, quoteType, delimiter); return transformations; };
25.314286
88
0.660553
36de0bccf8d4731903293a2232901f8fe14f7c04
250
js
JavaScript
handlers/batcave.js
pf-msi/watchtower_vuln_webapp
4d355af0675f16a396e33ddb88f93839340c63b8
[ "MIT" ]
5
2020-07-05T05:48:11.000Z
2021-03-22T12:57:21.000Z
handlers/batcave.js
pf-msi/watchtower_vuln_webapp
4d355af0675f16a396e33ddb88f93839340c63b8
[ "MIT" ]
14
2020-07-21T09:59:52.000Z
2022-03-27T01:43:08.000Z
handlers/batcave.js
pf-msi/watchtower_vuln_webapp
4d355af0675f16a396e33ddb88f93839340c63b8
[ "MIT" ]
3
2020-09-29T09:08:49.000Z
2022-03-26T22:41:37.000Z
function batcavePage(req, res) { res.render('batcave') } function authorize(req, res) { const {username} = req.session; const isBatman = username == "Batman" res.json({isBatman: isBatman}) } module.exports = {batcavePage, authorize}
22.727273
41
0.68
36dea4820a01936a2dfe7bf865d19eda723dc0aa
541
js
JavaScript
Test/redis/redis.js
shawflying/porject-manager
d935e435d6fa4bed3ea5863f208dc637991e523f
[ "Apache-2.0" ]
null
null
null
Test/redis/redis.js
shawflying/porject-manager
d935e435d6fa4bed3ea5863f208dc637991e523f
[ "Apache-2.0" ]
null
null
null
Test/redis/redis.js
shawflying/porject-manager
d935e435d6fa4bed3ea5863f208dc637991e523f
[ "Apache-2.0" ]
null
null
null
var redis = require("redis"); var client = redis.createClient(); client.on("error", function (err) { console.log("Error " + err); }); //设置值 redis.print 返回值 client.set("admin", "yanxxit", redis.print); //获取值 client.get("admin", function (err, data) { console.log(err); console.log(data) }); //写入JavaScript(JSON)对象 client.hmset('sessionid', { username: 'kris', password: 'password' }, function(err) { console.log(err) }) //读取JavaScript(JSON)对象 client.hgetall('sessionid', function(err, object) { console.log(object) })
21.64
85
0.659889
36deaf6e0596f237cc3516d52568d9cae7d11e8f
5,799
js
JavaScript
incubator/libs/spazmenu.js
jmanav2002/spazcore
f9923c28e45279daac7951c1ab9f8dfd26950176
[ "BSD-3-Clause" ]
7
2015-04-24T14:06:45.000Z
2019-06-12T20:17:52.000Z
incubator/libs/spazmenu.js
jmanav2002/spazcore
f9923c28e45279daac7951c1ab9f8dfd26950176
[ "BSD-3-Clause" ]
1
2015-05-15T19:22:33.000Z
2015-05-15T19:22:33.000Z
incubator/libs/spazmenu.js
jmanav2002/spazcore
f9923c28e45279daac7951c1ab9f8dfd26950176
[ "BSD-3-Clause" ]
1
2020-09-30T19:55:34.000Z
2020-09-30T19:55:34.000Z
/** * A class for dynamically generating menus. * * hash structure: * var hash = [ * { * 'label':"Menu label", * 'id':"a_unique_id", // optional, not used if not present * 'class':"menu_label", // optional, generated if not present * 'handler':function(e, data) {}, // a handler. will be listening via delegation * 'data':{} // some data, passed as second param to onClick handler * } * * ]; * * * @param {object} trigger_event the event that is triggering the creation of this menu. needed for positioning * * @param {object} opts options * * @param {array} opts.items_func a function that generates a hash of item objects. takes one parameter "data" * @param {string} [opts.base_id] the id attribute for the menu's base element. default is 'spaz_menu' * @param {string} [opts.base_class] the class attribute for the menu's base element. default is 'spaz_menu' * @param {string} [opts.li_class] the class attribute for the menu's base element. default is 'spaz_menu_li' * @param {string} [opts.show_immediately] whether or not to immediately show the menu on creation. Default is TRUE */ SpazMenu = function(opts) { this.opts = sch.defaults({ 'items_func':function(data){ return null; }, 'base_id' :'spaz_menu', 'base_class':'spaz_menu', 'li_class' :'spaz_menu_li', 'show_immediately':true }, opts); // close on ANY clicks jQuery(document).bind('click', {'spazmenu':this}, this.hide); /** * dismiss with escape */ jQuery(document).bind('keydown', {'spazmenu':this}, this.keypressHide); // just in case, we need to destroy any existing menus before creating new ones // with the same settings jQuery('div.'+this.opts.base_class).remove(); }; /** * Creates the menu, but doesn't show * @param {object} trigger_event the event that triggered the show * @param {object} itemsdata a data structure that will be passed to the items_func */ SpazMenu.prototype.show = function(trigger_event, itemsdata) { sch.debug('creating'); var that = this; // map the triggering event this.trigger_event = trigger_event; // create items with items_func this.items = this.opts.items_func(itemsdata); // create base DOM elements if (jQuery('#'+this.opts.base_id).length < 1) { jQuery('body').append(this._tplBase()); } else { // if exists, empty it jQuery('#'+this.opts.base_id + ' ul').empty(); } // iterate over items var item, itemhtml = ''; for (var i=0; i < this.items.length; i++) { item = this.items[i]; if (!item['class']) { item['class'] = this._generateItemClass(item); } // create the item HTML itemhtml = this._tplItem(item); // -- add item DOM element jQuery('#'+this.opts.base_id + ' ul').append(itemhtml); // -- remove any existing handlers (in case this menu was shown before) jQuery('#'+this.opts.base_id + ' ul').undelegate('.'+item['class'], 'click'); // -- add delegated handler jQuery('#'+this.opts.base_id + ' ul').delegate('.'+item['class'], 'click', {'item':item, 'spazmenu':this}, function(e, data) { e.data.item.handler.call(this, e, e.data.item.data||itemsdata); that.hide(); }); } sch.debug('show'); this._postionBeforeShow(trigger_event); jQuery('#'+this.opts.base_id).show(); this._reposition(trigger_event); }; /** * hides a created menu */ SpazMenu.prototype.hide = function(e) { sch.debug('hide'); var that; if (e && e.data && e.data.spazmenu) { that = e.data.spazmenu; } else { that = this; } jQuery('#'+that.opts.base_id).hide(); }; /** * handler if esc is hit */ SpazMenu.prototype.keypressHide = function(e) { if (e.keyCode == 27) { e.data.spazmenu.hide(); } // escape }; /** * destroys a menu completely (DOM and JS object) */ SpazMenu.prototype.destroy = function() { sch.debug('destroy'); // close on ANY clicks jQuery(document).unbind('click', {'spazmenu':this}, this.hide); jQuery(document).unbind('keydown', {'spazmenu':this}, this.keypressHide); // remove base DOM element jQuery('#'+this.opts.base_id).remove(); }; /** * hides AND destroys */ SpazMenu.prototype.hideAndDestroy = function(e) { if (this.hide && this.destroy) { this.hide(); this.destroy(); } else if (e && e.data && e.data.spazmenu) { e.data.spazmenu.hide(); e.data.spazmenu.destroy(); } else { sch.error('couldn\'t hide and destroy'); } }; /** * sets the position of the menu right before we show it */ SpazMenu.prototype._postionBeforeShow = function(e, data) { sch.debug('_postionBeforeShow'); var jqtrigger = jQuery(e.target); // var top = jqtrigger.position().top + jqtrigger.height(); // var left = jqtrigger.position().left+ jqtrigger.width(); var top = e.clientY; var left = e.clientX; jQuery('#'+this.opts.base_id).css('top', top); jQuery('#'+this.opts.base_id).css('left', left); }; /** * Repositions the menu after showing in case we're outside the viewport boundaries */ SpazMenu.prototype._reposition = function(e, data) { sch.debug('_reposition'); }; /** * this generates the item class if one has not been provided */ SpazMenu.prototype._generateItemClass = function(item) { return item.label.replace(/[^a-z]/gi, '_').toLowerCase(); }; /** * generates the html for the base DOM elements */ SpazMenu.prototype._tplBase = function() { var html = ''; html += '<div id="'+(this.opts.base_id||'')+'" class="'+this.opts.base_class+'">'; html += ' <ul>'; html += ' </ul>'; html += '</div>'; sch.debug(html); return html; }; /** * generates the HTML for a menu item * @param {object} i the item object */ SpazMenu.prototype._tplItem = function(i) { var html = ''; html += '<li class="'+this.opts.li_class+' '+i['class']+'" id="'+(i.id||'')+'">'+i.label+'</li>'; sch.debug(html); return html; };
25.323144
128
0.650457
36df409258e36bf59fa8d15d819def9408dcd333
2,159
js
JavaScript
routes/usersRouter.js
TomHessburg/mongodb-practice-api
d596e0484bfb2598a8b5b14213e254b16dc71f86
[ "MIT" ]
null
null
null
routes/usersRouter.js
TomHessburg/mongodb-practice-api
d596e0484bfb2598a8b5b14213e254b16dc71f86
[ "MIT" ]
3
2020-07-17T16:46:57.000Z
2021-09-01T18:35:36.000Z
routes/usersRouter.js
TomHessburg/mongodb-practice-api
d596e0484bfb2598a8b5b14213e254b16dc71f86
[ "MIT" ]
null
null
null
const router = require("express").Router(); const User = require("../schemas/UserSchema.js"); const Post = require("../schemas/PostSchema.js"); // get all users router.get("/", async (req, res) => { try { const users = await User.find({}).exec(); if (!users.length) { res.status(404).json({ message: "Sorry, no users!" }); } else { res.status(200).json(users); } } catch (err) { res.status(500).json(err); } }); // get a single user router.get("/:id", async (req, res) => { const userId = req.params.id; try { // returns user and all posts related to that user const user = await User.findById(userId).exec(); const posts = await Post.find({ user: userId }).exec(); if (!user) { res.status(404).json({ message: "Sorry, cant find that user!" }); } else { res.status(200).json({ user, posts }); } } catch (err) { res.status(500).json(err); } }); // post a user // moved this route to auth // router.post("/", async (req, res) => { // try { // const newUser = await User.create(req.body); // if (newUser) { // res.status(201).json(newUser); // } else { // res // .status(404) // .json({ message: "Invalid user. Please provide all required fields." }); // } // } catch (err) { // res.status(500).json(err); // } // }); // delete a user by id router.delete("/:id", async (req, res) => { try { const deletedUser = await User.findByIdAndDelete(req.params.id).exec(); // deletes all posts related to the user const deletePosts = await Post.deleteMany({ user: deletedUser._id }).exec(); res .status(203) .json({ message: `successfulyl deleted user: ${deletedUser._id}` }); } catch (err) { res.status(500).json(err); } }); // update a user by id router.put("/:id", async (req, res) => { try { const updatedUser = await Post.findByIdAndUpdate(req.params.id, req.body, { new: true, useFindAndModify: false }).exec(); res.status(201).json(updatedUser); } catch (err) { res.status(500).json(err); } }); module.exports = router;
24.258427
83
0.572024
36dff6b8d97cf0f6b8adba0332740911197682dd
19
js
JavaScript
public/javascripts/frontScripts.js
rongallant/event-signup
ef6c24a55947301d3108893ae2a7c2aed6af4d5f
[ "MIT" ]
1
2016-03-06T00:09:45.000Z
2016-03-06T00:09:45.000Z
public/javascripts/frontScripts.js
rongallant/event-signup
ef6c24a55947301d3108893ae2a7c2aed6af4d5f
[ "MIT" ]
4
2016-02-16T11:49:06.000Z
2016-03-25T03:02:53.000Z
public/javascripts/frontScripts.js
rongallant/event-signup
ef6c24a55947301d3108893ae2a7c2aed6af4d5f
[ "MIT" ]
null
null
null
/* Front Scripts */
19
19
0.631579
36e030ae7b306d07475250612bd63f6e55bcd4fc
150
js
JavaScript
src/components/styled/Title.css.js
alarivan/sport_consulting
4e9111f8ad931a0a0a79409495410a0bb03a059c
[ "MIT" ]
null
null
null
src/components/styled/Title.css.js
alarivan/sport_consulting
4e9111f8ad931a0a0a79409495410a0bb03a059c
[ "MIT" ]
null
null
null
src/components/styled/Title.css.js
alarivan/sport_consulting
4e9111f8ad931a0a0a79409495410a0bb03a059c
[ "MIT" ]
null
null
null
import styled from "styled-components" const Title = styled.h1` width: 100%; text-align: center; margin: 0 0 1.5rem 0; ` export default Title
15
38
0.7