max_stars_repo_path
stringlengths
3
961
max_stars_repo_name
stringlengths
5
122
max_stars_count
int64
0
224k
id
stringlengths
1
8
content
stringlengths
2
1.07M
score
float64
-0.95
3.88
int_score
int64
0
4
packages/styles/src/theme/createTheme.js
sirreal/g2
0
7
import { get } from '@wp-g2/create-styles'; import { colorize, getComputedColor, is, noop } from '@wp-g2/utils'; import { space } from '../mixins/space'; import { config } from './config'; import { generateColorAdminColors } from './utils'; const baseTheme = Object.freeze(Object.assign({}, config)); export function createTheme(callback = noop) { if (!is.function(callback)) return {}; const props = { get, theme: baseTheme, color: colorize, space, }; const customConfig = callback(props); if (!is.plainObject(customConfig)) return {}; let colorAdminColors = {}; if (customConfig.colorAdmin) { const colorAdminValue = getComputedColor(customConfig.colorAdmin); colorAdminColors = generateColorAdminColors(colorAdminValue); } return { ...customConfig, ...colorAdminColors, }; }
1.273438
1
src/components/NavBar/index.js
lfernandez79/reactPortfolio
0
15
import React from "react"; import { Wave } from "react-animated-text"; import { Link } from "react-scroll"; import TravisCI from "../../pages/images/TravisCI-Mascot-2.png"; import "./style.css"; const style = { removeUnderline: { textDecoration: "none", }, }; function NavBar() { return ( <header className="row align-items-center py-3"> <div className="col-sm-12 col-md-6"> <a className="d-flex justify-content-center" href="https://travis-ci.com/github/lfernandez79/reactPortfolio" style={style.removeUnderline}> <img id="radius" src={TravisCI} style={{ width: "5%", height: "5%" }} alt="TravisCI" /> <span> &nbsp; CI/CD! </span> </a> </div> <nav className="col-sm-12 col-md-6"> <ul className="nav d-flex justify-content-around"> <li className="nav-item"> <Link to="About" duration={500} smooth className="nav-link" href="/"><Wave text="About" effect="stretch" effectChange={2.0} /></Link> </li> <li className="nav-item"> <Link to="Projtcs" duration={500} smooth className="nav-link" href="/"><Wave text="Portfolio" effect="stretch" effectChange={2.0} /></Link> </li> <li className="nav-item"> <Link to="Contact" duration={500} smooth className="nav-link" href="/"><Wave text="Contact" effect="stretch" effectChange={2.0} /></Link> </li> </ul> </nav> </header> ); } export default NavBar;
1.257813
1
packages/node_modules/@webex/internal-plugin-search/src/index.js
antti2000/spark-js-sdk
0
23
/*! * Copyright (c) 2015-2017 Cisco Systems, Inc. See LICENSE file. */ import {registerInternalPlugin} from '@webex/webex-core'; import Search from './search'; import config from './config'; import {has} from 'lodash'; import '@webex/internal-plugin-encryption'; registerInternalPlugin('search', Search, { config, payloadTransformer: { predicates: [ { name: 'encryptSearchQuery', direction: 'outbound', test(ctx, options) { if (!has(options, 'body.query')) { return Promise.resolve(false); } if (!has(options, 'body.searchEncryptionKeyUrl')) { return Promise.resolve(false); } return ctx.spark.internal.device.isSpecificService('argonaut', options.service || options.url); }, extract(options) { return Promise.resolve(options.body); } }, { name: 'transformObjectArray', direction: 'inbound', test(ctx, response) { return Promise.resolve(has(response, 'body.activities.items[0].objectType')) .then((res) => res && ctx.spark.internal.device.isSpecificService('argonaut', response.options.service || response.options.uri)); }, extract(response) { return Promise.resolve(response.body.activities.items); } } ], transforms: [ { name: 'encryptSearchQuery', direction: 'outbound', fn(ctx, object) { return ctx.spark.internal.encryption.encryptText(object.searchEncryptionKeyUrl, object.query) .then((q) => { object.query = q; }); } } ] } }); export {default} from './search';
1.148438
1
client/templates/gamesession/gamesession_edit.js
pfritsch/bandedejoueurs
1
31
Template.gamesessionEdit.helpers({ gamesession: function() { var gamesessionId = FlowRouter.getParam('gamesessionId'); var gamesession = Gamesessions.findOne(gamesessionId) || {}; if(gamesession.boardgameTags) gamesession.category = 'boardgame'; if(gamesession.videogameTags) gamesession.category = 'videogame'; Session.set('newGamesession', gamesession); return gamesession; }, meetingDateValue: function() { var date = moment(this.meetingDate, 'X'); return moment(date).format('DD/MM/YYYY HH:mm'); }, meetingTypeOptions: function() { var options = new Array( {label: TAPi18n.__('schemas.gamesession.meetingType.options.irl'), value: "irl"}, {label: TAPi18n.__('schemas.gamesession.meetingType.options.online'), value: "online"} ); return options; }, meetingServiceOptions: function() { var options = new Array( {label: TAPi18n.__('schemas.gamesession.meetingPlace.service.title.options.other'), value: "other"}, {label: TAPi18n.__('schemas.gamesession.meetingPlace.service.title.options.skype'), value: "skype"}, {label: TAPi18n.__('schemas.gamesession.meetingPlace.service.title.options.steam'), value: "steam"}, {label: TAPi18n.__('schemas.gamesession.meetingPlace.service.title.options.teamspeak'), value: "teamspeak"}, {label: TAPi18n.__('schemas.gamesession.meetingPlace.service.title.options.psn'), value: "psn"}, {label: TAPi18n.__('schemas.gamesession.meetingPlace.service.title.options.xlive'), value: "xlive"} ); return options; }, meetingTypeIsIRL: function() { var isIrl = (Session.get('newGamesession').meetingType === 'irl'); if (!isIrl) { $('[name="meetingType"]').filter('[value=online]').prop('checked', true); } else if(Session.get('newGamesession').meetingType === 'online') { $('[name="meetingType"]').filter('[value=irl]').prop('checked', true); } return isIrl; }, gamesTitlePlaceholder: function() { return TAPi18n.__('schemas.gamesession.games.$.title.placeholder') }, newGames: function (){ return Session.get('newGamesession').games; }, gamesSuggests: function() { return Session.get('suggests'); }, beforeRemove: function () { return function (collection, id) { var doc = collection.findOne(id); if (confirm(TAPi18n.__('gamesessionRemoveConfirm'))) { this.remove(); } }; }, onRemoveSuccess: function () { return function (result) { FlowRouter.go('gamesessionList'); }; } }); Template.gamesessionEdit.events({ 'change [name="meetingType"]:checked': function(e) { var form = Session.get('newGamesession'); form.meetingType = $(e.target).val(); Session.set('newGamesession', form); }, 'change [name="boardgameTags"]': function(e, tpl) { if($(e.target).is(":checked")) { var form = Session.get('newGamesession'); form.category = 'boardgame'; Session.set('newGamesession', form); tpl.$('[name="videogameTags"]').attr('checked', false); } }, 'change [name="videogameTags"]': function(e, tpl) { if($(e.target).is(":checked")) { var form = Session.get('newGamesession'); form.category = 'videogame'; Session.set('newGamesession', form); tpl.$('[name="boardgameTags"]').attr('checked', false); } }, 'change [name="games.$.title"]': function(e, tpl) { var value = $(e.target).val(); var newGamesession = Session.get('newGamesession'); if(value) { var newGame = Games.findOne(value); if(newGame) { if(!newGamesession.games) newGamesession.games = []; newGamesession.games.push(newGame); Session.set('newGamesession', newGamesession); } else { getGamesSuggestByTitle(value, newGamesession.category); } } }, 'click .game-remove': function(e, tpl) { var form = Session.get('newGamesession'); form.games.contains('title', this.title); var index = form.games.contains('title', this.title); form.games.splice(index, 1); Session.set('newGamesession', form); }, 'click [data-toggle="boardgameTags"]': function(e, tpl) { e.preventDefault(); var showGame = Session.get('showGame'); showGame.boardgameTags ++; if(showGame.boardgameTags > 1) showGame.boardgameTags = 0; Session.set('showGame', showGame); }, 'click [data-toggle="videogameTags"]': function(e, tpl) { e.preventDefault(); var showGame = Session.get('showGame'); showGame.videogameTags ++; if(showGame.videogameTags > 1) showGame.videogameTags = 0; Session.set('showGame', showGame); } }); Template.gamesessionCreate.onCreated(function() { Tracker.autorun(function() { Meteor.subscribe('someGames', {}); }); }); Template.gamesessionEdit.rendered = function() { var self = this; Tracker.autorun(function () { var lang = Session.get('lang'); self.$('.datetimepicker').datetimepicker({ format: 'DD/MM/YYYY HH:mm', formatDate: 'DD/MM/YYYY', formatTime: 'HH:mm', minDate: 0, step: 15, use24hours: true, pick12HourFormat: false, dayOfWeekStart: 1, lang: lang }); }); Session.set('suggests', null); }; AutoForm.hooks({ gamesessionUpdate: { before: { update: function(doc) { form = Session.get('newGamesession'); // Format the date time var meetingDate = moment(doc.$set.meetingDate, "DD/MM/YYYY HH:mm"); doc.$set.meetingDate = moment(meetingDate).unix(); // Choose a cover var newCover = (form.category === 'videogame')? Meteor.absoluteUrl()+'/images/cover_video.svg' : Meteor.absoluteUrl()+'/images/cover_board.svg'; if(form.games && form.games.length > 0) newCover = form.games[0].cover; doc.$set.cover = newCover; // Generate a title var newTitle = { what: TAPi18n.__('gamesessionCreateGames'), where: '', when: ''}; // Where if(doc.$set.meetingType) { if(doc.$set.meetingType === 'irl') { if(doc.$set['meetingPlace.address.city']) { newTitle.where = TAPi18n.__('helper.inCity', doc.$set['meetingPlace.address.city']); if(doc.$set['meetingPlace.address.zipCode']) { newTitle.where += ' ('+doc.$set['meetingPlace.address.zipCode']+')'; } } else if(doc.$set['meetingPlace.address.zipCode']) { newTitle.where = TAPi18n.__('helper.inZipCode', doc.$set['meetingPlace.address.zipCode']); } } else if (doc.$set.meetingType === 'online') { if(doc.$set['meetingPlace.service.title'] != 'other') { var key = TAPi18n.__('schemas.gamesession.meetingPlace.service.title.options.'+doc.$set['meetingPlace.service.title']); newTitle.where = TAPi18n.__('helper.onPlatform', key); } } } // What if(form.category === 'boardgame') { newTitle.what = TAPi18n.__('gamesessionCreateBoardGames'); } else if(form.category === 'videogame') { newTitle.what = TAPi18n.__('gamesessionCreateVideoGames'); } if(form.games.length === 1) { newTitle.what = form.games[0].title; } else { newTitle.when = splitDay(moment(doc.$set.meetingDate, 'X').hour()); } doc.$set.title = newTitle.when + ' ' + newTitle.what + ' ' + newTitle.where; // Add games doc.$set.games = form.games.map(function(item,index){ if(!item.gameId) item.gameId = item._id; return item; }); delete doc.$set['games.$.title']; delete doc.$unset['games.$']; return doc; } }, onSuccess: function(t, result) { FlowRouter.go('gamesessionList'); }, onError: function(formType, error) { console.log(error); } } });
0.867188
1
src/Services/Air/AirFormat.js
digital230/uapi-json
0
39
const parsers = require('../../utils/parsers'); const { AirParsingError } = require('./AirErrors'); function ProviderSegmentOrderReducer(acc, { ProviderSegmentOrder }) { const x = parseInt(ProviderSegmentOrder, 10); if (x > acc) { return x; } return acc; } /** * getBaggage -- get baggage information from LFS search * @param baggageAllowance * @returns {{amount: number, units: string}} */ function getBaggage(baggageAllowance) { // Checking for allowance if ( !baggageAllowance || ( !baggageAllowance['air:NumberOfPieces'] && !baggageAllowance['air:MaxWeight'] ) ) { console.warn('Baggage information is not number and is not weight!', JSON.stringify(baggageAllowance)); return { units: 'piece', amount: 0 }; } // Checking for max weight if (baggageAllowance['air:MaxWeight']) { return { units: baggageAllowance['air:MaxWeight'].Unit.toLowerCase(), amount: Number(baggageAllowance['air:MaxWeight'].Value), }; } // Returning pieces return { units: 'piece', amount: Number(baggageAllowance['air:NumberOfPieces']), }; } /** * getBaggageInfo -- get baggage information from airPrice * @param info * @returns {{amount: number, units: string}} */ function getBaggageInfo(info) { // Checking for allowance let baggageInfo = { units: 'piece', amount: 0 }; if (typeof info === 'undefined' || info == null) { return baggageInfo; } if (Object.prototype.hasOwnProperty.call(info, 'air:BagDetails')) { baggageInfo.detail = info['air:BagDetails'].map((detail) => { return { applicableBags: detail.ApplicableBags, basePrice: detail.BasePrice, totalPrice: detail.TotalPrice, approximateBasePrice: detail.ApproximateBasePrice, approximateTotalPrice: detail.ApproximateTotalPrice, restrictionText: detail['air:BaggageRestriction']['air:TextInfo'], }; }); } if (Object.prototype.hasOwnProperty.call(info, 'air:TextInfo')) { const match = info['air:TextInfo'][0].match(/^(\d+)([KP]+)$/); if (match) { if (match[2] === 'P') { baggageInfo = Object.assign(baggageInfo, { units: 'piece', amount: match[1] }); } else if (match[2] === 'K') { baggageInfo = Object.assign(baggageInfo, { units: 'kilograms', amount: match[1] }); } } else { console.warn('Baggage information is not number and is not weight!', JSON.stringify(info)); } } else { console.warn('Unknown', JSON.stringify(info)); } return baggageInfo; } function formatSegment(segment) { return { from: segment.Origin, to: segment.Destination, group: Number(segment.Group), departure: segment.DepartureTime, arrival: segment.ArrivalTime, airline: segment.Carrier, flightNumber: segment.FlightNumber, uapi_segment_ref: segment.Key, }; } function formatServiceSegment(segment, remark) { return { ...parsers.serviceSegment(remark['passive:Text']), carrier: segment.SupplierCode, airport: segment.Origin, date: segment.StartDate, index: segment.index, }; } function formatPrices(prices) { return { basePrice: prices.BasePrice, taxes: prices.Taxes, equivalentBasePrice: prices.EquivalentBasePrice, totalPrice: prices.TotalPrice, }; } function formatTrip(segment, flightDetails) { const flightInfo = flightDetails ? Object.keys(flightDetails).map( detailsKey => flightDetails[detailsKey] ) : []; const plane = flightInfo.map(details => details.Equipment || 'Unknown'); const duration = flightInfo.map(details => details.FlightTime || 0); const techStops = flightInfo.slice(1).map(details => details.Origin); return { ...formatSegment(segment), serviceClass: segment.CabinClass, plane, duration, techStops, }; } function formatAirExchangeBundle(bundle) { return { addCollection: bundle.AddCollection, changeFee: bundle.ChangeFee, exchangeAmount: bundle.ExchangeAmount, refund: bundle.Refund, }; } function formatPassengerCategories(pricingInfo) { const passengerCounts = {}; const passengerCategories = Object.keys(pricingInfo) .reduce((acc, key) => { const passengerFare = pricingInfo[key]; let code = passengerFare['air:PassengerType']; if (Object.prototype.toString.call(code) === '[object String]') { // air:PassengerType in fullCollapseList_obj ParserUapi param passengerCounts[code] = 1; // air:PassengerType in noCollapseList } else if (Array.isArray(code) && code.constructor === Array) { // ParserUapi param const count = code.length; const list = Array.from(new Set((code.map((item) => { if (Object.prototype.toString.call(item) === '[object String]') { return item; } if (Object.prototype.toString.call(item) === '[object Object]' && item.Code) { // air:PassengerType in fullCollapseList_obj like above, // but there is Age or other info, except Code return item.Code; } throw new AirParsingError.PTCIsNotSet(); })))); [code] = list; if (!list[0] || list.length !== 1) { // TODO throw error console.log('Warning: different categories ' + list.join() + ' in single fare calculation ' + key + ' in fare ' + key); } passengerCounts[code] = count; } else { throw new AirParsingError.PTCTypeInvalid(); } return { ...acc, [code]: passengerFare }; }, {}); const passengerFares = Object.keys(passengerCategories) .reduce( (memo, ptc) => Object.assign(memo, { [ptc]: { totalPrice: passengerCategories[ptc].TotalPrice, basePrice: passengerCategories[ptc].BasePrice, equivalentBasePrice: passengerCategories[ptc].EquivalentBasePrice, taxes: passengerCategories[ptc].Taxes, fareCalc: passengerCategories[ptc].FareCalc, }, }), {} ); return { passengerCounts, passengerCategories, passengerFares, }; } function formatFarePricingInfo(fare) { const changePenalty = {}; const cancelPenalty = {}; if (Object.prototype.hasOwnProperty.call(fare, 'air:ChangePenalty')) { const fareChangePenalty = fare['air:ChangePenalty']; if (typeof fareChangePenalty['air:Amount'] !== 'undefined') { changePenalty.amount = fareChangePenalty['air:Amount']; } if (typeof fareChangePenalty['air:Percentage'] !== 'undefined') { changePenalty.percentage = fareChangePenalty['air:Percentage']; } if (typeof fareChangePenalty.PenaltyApplies !== 'undefined') { changePenalty.penaltyApplies = fareChangePenalty.PenaltyApplies; } } if (Object.prototype.hasOwnProperty.call(fare, 'air:CancelPenalty')) { const fareCancelPenalty = fare['air:CancelPenalty']; if (typeof fareCancelPenalty['air:Amount'] !== 'undefined') { cancelPenalty.amount = fareCancelPenalty['air:Amount']; } if (typeof fareCancelPenalty['air:Percentage'] !== 'undefined') { cancelPenalty.percentage = fareCancelPenalty['air:Percentage']; } if (typeof fareCancelPenalty.PenaltyApplies !== 'undefined') { cancelPenalty.penaltyApplies = fareCancelPenalty.PenaltyApplies; } if (typeof fareCancelPenalty.NoShow !== 'undefined') { cancelPenalty.noShow = fareCancelPenalty.NoShow; } } let refundable = false; if (Object.prototype.hasOwnProperty.call(fare, 'Refundable')) { refundable = fare.Refundable; } let latestTicketingTime = null; if (Object.prototype.hasOwnProperty.call(fare, 'LatestTicketingTime')) { latestTicketingTime = fare.LatestTicketingTime; } let eTicketability = false; if (Object.prototype.hasOwnProperty.call(fare, 'eTicketability')) { // eslint-disable-next-line prefer-destructuring eTicketability = fare.eTicketability; } return { latestTicketingTime, eTicketability, refundable, changePenalty, cancelPenalty, }; } function formatLowFaresSearch(searchRequest, searchResult) { const pricesList = searchResult['air:AirPricePointList']; const solutionsList = searchResult['air:AirPricingSolution']; const fareInfos = searchResult['air:FareInfoList']; const segments = searchResult['air:AirSegmentList']; const flightDetails = searchResult['air:FlightDetailsList']; const { provider } = searchRequest; // const legs = _.first(_.toArray(searchResult['air:RouteList']))['air:Leg']; // TODO filter pricesList by CompleteItinerary=true & ETicketability = Yes, etc const fares = []; const isSolutionResult = typeof solutionsList !== 'undefined'; const results = isSolutionResult ? solutionsList : pricesList; Object.entries(results).forEach(([fareKey, price]) => { const [firstKey] = Object.keys(price['air:AirPricingInfo']); const thisFare = price['air:AirPricingInfo'][firstKey]; // get trips from first reservation if (!thisFare.PlatingCarrier) { return; } let directions = []; if (isSolutionResult) { if (Object.prototype.toString.call(price['air:Journey']) === '[object Object]') { price['air:Journey'] = [price['air:Journey']]; } directions = price['air:Journey'].map((leg) => { const trips = leg['air:AirSegmentRef'].map((segmentRef) => { const segment = segments[segmentRef]; const tripFlightDetails = segment['air:FlightDetailsRef'].map(flightDetailsRef => flightDetails[flightDetailsRef]); const [bookingInfo] = thisFare['air:BookingInfo'].filter(info => info.SegmentRef === segmentRef); const fareInfo = fareInfos[bookingInfo.FareInfoRef]; const seatsAvailable = Number(bookingInfo.BookingCount); return Object.assign( formatTrip(segment, tripFlightDetails), { serviceClass: bookingInfo.CabinClass, bookingClass: bookingInfo.BookingCode, baggage: [getBaggage(fareInfo['air:BaggageAllowance'])], fareBasisCode: fareInfo.FareBasis, }, seatsAvailable ? { seatsAvailable } : null ); }); return [{ from: trips[0].from, to: trips[trips.length - 1].to, duration: leg.TravelTime, // TODO get overnight stops, etc from connection platingCarrier: thisFare.PlatingCarrier, segments: trips, }]; }); } else { directions = thisFare['air:FlightOptionsList'].map(direction => Object.values(direction['air:Option']).map((option) => { const trips = option['air:BookingInfo'].map( (segmentInfo) => { const fareInfo = fareInfos[segmentInfo.FareInfoRef]; const segment = segments[segmentInfo.SegmentRef]; const tripFlightDetails = segment['air:FlightDetailsRef'].map( flightDetailsRef => flightDetails[flightDetailsRef] ); const seatsAvailable = ( segment['air:AirAvailInfo'] && segment['air:AirAvailInfo'].ProviderCode === provider) ? (Number( segment['air:AirAvailInfo']['air:BookingCodeInfo'].BookingCounts .match(new RegExp(`${segmentInfo.BookingCode}(\\d+)`))[1] )) : null; return Object.assign( formatTrip(segment, tripFlightDetails), { serviceClass: segmentInfo.CabinClass, bookingClass: segmentInfo.BookingCode, baggage: [getBaggage(fareInfo['air:BaggageAllowance'])], fareBasisCode: fareInfo.FareBasis, }, seatsAvailable ? { seatsAvailable } : null ); } ); return { from: direction.Origin, to: direction.Destination, // duration // TODO get overnight stops, etc from connection platingCarrier: thisFare.PlatingCarrier, segments: trips, }; })); } const { passengerCounts, passengerFares } = this.formatPassengerCategories(price['air:AirPricingInfo']); const result = { totalPrice: price.TotalPrice, basePrice: price.BasePrice, taxes: price.Taxes, platingCarrier: thisFare.PlatingCarrier, directions, bookingComponents: [ { totalPrice: price.TotalPrice, basePrice: price.BasePrice, taxes: price.Taxes, uapi_fare_reference: fareKey, // TODO }, ], passengerFares, passengerCounts, }; fares.push(result); }); fares.sort((a, b) => parseFloat(a.totalPrice.substr(3)) - parseFloat(b.totalPrice.substr(3))); if (searchRequest.faresOnly === false) { const result = { fares }; if ({}.hasOwnProperty.call(searchResult, 'TransactionId')) { result.transactionId = searchResult.TransactionId; } if ({}.hasOwnProperty.call(searchResult, 'SearchId')) { result.searchId = searchResult.SearchId; } if ({}.hasOwnProperty.call(searchResult, 'air:AsyncProviderSpecificResponse')) { result.hasMoreResults = searchResult['air:AsyncProviderSpecificResponse'].MoreResults; result.providerCode = searchResult['air:AsyncProviderSpecificResponse'].ProviderCode; } return result; } return fares; } /** * This function used to transform segments and service segments objects * to arrays. After that this function try to set indexes with same as in * terminal response order. So it needs to check `ProviderSegmentOrder` field for that. * * @param segmentsObject * @param serviceSegmentsObject * @return {*} */ function setIndexesForSegments( segmentsObject = null, serviceSegmentsObject = null ) { const segments = segmentsObject ? Object.keys(segmentsObject).map(k => segmentsObject[k]) : null; const serviceSegments = serviceSegmentsObject ? Object.keys(serviceSegmentsObject).map(k => serviceSegmentsObject[k]) : null; if (segments === null && serviceSegments === null) { return { segments, serviceSegments }; } if (segments !== null && serviceSegments === null) { const segmentsNew = segments.map((segment, key) => ({ ...segment, index: key + 1, })); return { segments: segmentsNew, serviceSegments }; } if (segments === null && serviceSegments !== null) { const serviceSegmentsNew = serviceSegments.map( (segment, key) => ({ ...segment, index: key + 1, }) ); return { segments, serviceSegments: serviceSegmentsNew }; } const maxSegmentsSegmentOrder = segments.reduce(ProviderSegmentOrderReducer, 0); const maxServiceSegmentsSegmentOrder = serviceSegments.reduce(ProviderSegmentOrderReducer, 0); const maxOrder = Math.max( maxSegmentsSegmentOrder, maxServiceSegmentsSegmentOrder ); const allSegments = []; for (let i = 1; i <= maxOrder; i += 1) { segments.forEach(s => (Number(s.ProviderSegmentOrder) === i ? allSegments.push(s) : null)); serviceSegments.forEach(s => ( Number(s.ProviderSegmentOrder) === i ? allSegments.push(s) : null )); } const indexedSegments = allSegments.map((s, k) => ({ ...s, index: k + 1 })); return { segments: indexedSegments.filter(s => s.SegmentType === undefined), serviceSegments: indexedSegments.filter(s => s.SegmentType === 'Service'), }; } module.exports = { formatLowFaresSearch, formatFarePricingInfo, formatPassengerCategories, formatTrip, formatSegment, formatServiceSegment, formatAirExchangeBundle, formatPrices, setIndexesForSegments, getBaggage, getBaggageInfo, };
1.945313
2
Portal de noticias/Introducao/noticias.js
juniorBM/Curso-Nodejs
0
47
var http = require('http'); var server = http.createServer(function(req, res) { var categoria = req.url; if(categoria == '/tecnologia') { res.end("<html><body>Noticias de tecnologia</body></html>"); }else if(categoria == '/moda') { res.end("<html><body>Noticias de moda</body></html>"); }else { res.end("<html><body>Portal de noticias</body></html>"); } }); server.listen(3000);
1.125
1
src/components/EngageClient/ui/buttons/ButtonD.js
xpertana/engage-demo
0
55
import style from "./ButtonA.module.css"; import React from "react"; export default function Round1(props) { return ( <button type="button" class={style.btn}> {props.text} </button> ); }
0.820313
1
node_modules/@loaders.gl/core/dist/esm/utils/globals.js
calebperelini/nzbikeaccidents
5
63
import _typeof from "@babel/runtime/helpers/esm/typeof"; var isBrowser = (typeof process === "undefined" ? "undefined" : _typeof(process)) !== 'object' || String(process) !== '[object process]' || process.browser; var globals = { self: typeof self !== 'undefined' && self, window: typeof window !== 'undefined' && window, global: typeof global !== 'undefined' && global, document: typeof document !== 'undefined' && document }; var self_ = globals.self || globals.window || globals.global; var window_ = globals.window || globals.self || globals.global; var global_ = globals.global || globals.self || globals.window; var document_ = globals.document || {}; export { isBrowser, self_ as self, window_ as window, global_ as global, document_ as document }; var matches = typeof process !== 'undefined' && process.version && process.version.match(/v([0-9]*)/); export var nodeVersion = matches && parseFloat(matches[1]) || 0; //# sourceMappingURL=globals.js.map
1.296875
1
assets/scripts/store/__tests__/street.integration.test.js
pkuzmickas/streetmix
0
71
/* eslint-env jest */ import MockAdapter from 'axios-mock-adapter' import { createStore } from '../../../../test/helpers/store' import { addSegment, clearSegments, incrementSegmentWidth, getLastStreet } from '../actions/street' // ToDo: Remove this once refactoring of redux action saveStreetToServerIfNecessary is complete import { saveStreetToServerIfNecessary } from '../../streets/data_model' import apiClient from '../../util/api' import { ERRORS } from '../../app/errors' jest.mock('../../app/load_resources') jest.mock('../../streets/data_model', () => { const actual = jest.requireActual('../../streets/data_model') return { ...actual, saveStreetToServerIfNecessary: jest.fn() } }) describe('street integration test', () => { beforeEach(() => { jest.clearAllMocks() }) describe('#addSegment', () => { it('adds the new segment at the index', () => { const initialState = { street: { segments: [1, 2] } } const store = createStore(initialState) store.dispatch(addSegment(1, 3)) const { street } = store.getState() expect(street.segments.length).toEqual(3) expect(street.segments[1]).toEqual(3) }) }) describe('#clearSegments', () => { it('clears all segments', () => { const initialState = { street: { segments: [1, 2] } } const store = createStore(initialState) store.dispatch(clearSegments()) const { street } = store.getState() expect(street.segments.length).toEqual(0) }) }) describe('#incrementSegmentWidth', () => { describe('decrease segment width by 1', () => { it('by resolution', async () => { const initialState = { street: { segments: [{ width: 200 }, { width: 200 }], units: 1 } } const store = createStore(initialState) await store.dispatch(incrementSegmentWidth(1, false, true, 200)) const { street } = store.getState() expect(street.segments[1].width).toEqual(199.75) }) it('by clickIncrement', async () => { const initialState = { street: { segments: [{ width: 200 }, { width: 200 }], units: 1 } } const store = createStore(initialState) await store.dispatch(incrementSegmentWidth(1, false, false, 200)) const { street } = store.getState() expect(street.segments[1].width).toEqual(199.5) }) it('has a remaining width of 0.25', async () => { const initialState = { street: { width: 400, segments: [{ width: 200 }, { width: 200 }], units: 1 } } const store = createStore(initialState) await store.dispatch(incrementSegmentWidth(1, false, true, 200)) const { street } = store.getState() expect(street.segments[1].width).toEqual(199.75) expect(street.occupiedWidth).toEqual(399.75) expect(street.remainingWidth).toEqual(0.25) }) }) describe('increase segment width by 1', () => { it('by resolution', async () => { const initialState = { street: { segments: [{ width: 200 }, { width: 200 }], units: 1 } } const store = createStore(initialState) await store.dispatch(incrementSegmentWidth(1, true, true, 200)) const { street } = store.getState() expect(street.segments[1].width).toEqual(200.25) }) it('by clickIncrement', async () => { const initialState = { street: { segments: [{ width: 200 }, { width: 200 }], units: 1 } } const store = createStore(initialState) await store.dispatch(incrementSegmentWidth(1, true, false, 200)) const { street } = store.getState() expect(street.segments[1].width).toEqual(200.5) }) }) // ToDo: Remove this once refactoring of redux action saveStreetToServerIfNecessary is complete it('saves to server', async () => { const initialState = { street: { segments: [{ width: 200 }, { width: 200 }] } } const store = createStore(initialState) await store.dispatch(incrementSegmentWidth(1, true, false, 200)) expect(saveStreetToServerIfNecessary).toHaveBeenCalledTimes(1) }) }) describe('#getLastStreet', () => { let apiMock const type = 'streetcar' const variantString = 'inbound|regular' const segment = { variantString, id: '1', width: 400, randSeed: 1, type } const street = { segments: [segment], width: 100 } const apiResponse = { id: '3', originalStreetId: '1', updatedAt: '', name: 'StreetName', data: { street } } beforeEach(() => { apiMock = new MockAdapter(apiClient.client) }) afterEach(() => { apiMock.restore() }) it('updates the street', async () => { const store = createStore({ settings: { priorLastStreetId: '1' } }) apiMock.onAny().reply(200, apiResponse) await store.dispatch(getLastStreet()) const { street } = store.getState() expect(street.segments.length).toEqual(1) }) it('sets lastStreetId', async () => { const store = createStore({ settings: { priorLastStreetId: '1' } }) apiMock.onAny().reply(200, apiResponse) await store.dispatch(getLastStreet()) const { settings } = store.getState() expect(settings.lastStreetId).toEqual('3') }) it('sets lastStreetId', async () => { const store = createStore({ street: { id: '50', namespaceId: '45' }, settings: { priorLastStreetId: '1' } }) apiMock.onAny().reply(200, apiResponse) await store.dispatch(getLastStreet()) const { street } = store.getState() expect(street.id).toEqual('50') expect(street.namespaceId).toEqual('45') }) describe('response failure', () => { it('does not set lastStreetId', async () => { const store = createStore({ settings: { priorLastStreetId: '1' } }) apiMock.onAny().networkError() await store.dispatch(getLastStreet()) const { errors } = store.getState() expect(errors.errorType).toEqual(ERRORS.NEW_STREET_SERVER_FAILURE) }) }) }) })
1.648438
2
packages/adminjs-e2e/cypress/integration/external-employees/create-external-employee.spec.js
NeobilitySRL/adminjs
3,821
79
/// <reference types="cypress" /> /// <reference types="../../support" /> context('resources/ExternalEmployees/actions/new', () => { before(() => { cy.abLoginAPI({ password: Cypress.env('ADMIN_PASSWORD'), email: Cypress.env('ADMIN_EMAIL') }) }) beforeEach(() => { cy.abKeepLoggedIn({ cookie: Cypress.env('COOKIE_NAME') }) cy.visit('resources/ExternalEmployees/actions/new') }) it('shows required mark (*) by email', () => { cy.get('[data-testid="property-edit-email"] label') .then(($label) => { const win = $label[0].ownerDocument.defaultView const before = win.getComputedStyle($label[0], 'before') const contentValue = before.getPropertyValue('content') expect(contentValue).to.eq('"*"') }) }) it('format date (only) in datepicker without time', () => { const hiredAt = new Date().toISOString().slice(0, 10) cy.get('[data-testid="property-edit-hiredAt"] button').click() cy.get('.react-datepicker__day--today').click() cy.get('[data-testid="property-edit-hiredAt"] input').should('have.value', hiredAt) }) })
1.445313
1
src/main/config/env.js
kelwinap/clean-node-api
0
87
module.exports = { mongoUrl: process.env.MONGO_URL || 'mongodb://localhost:27017/clean-node-api', tokenSecret: process.env.TOKEN_SECRET || 'token_secret', port: process.env.PORT || 5858 }
0.507813
1
node_modules/markdownlint/lib/markdownlint.js
TreySchmidt/MagicMirror
0
95
// @ts-check "use strict"; const fs = require("fs"); const path = require("path"); const { URL } = require("url"); const markdownIt = require("markdown-it"); const rules = require("./rules"); const helpers = require("../helpers"); const cache = require("./cache"); const deprecatedRuleNames = [ "MD002" ]; // Validates the list of rules for structure and reuse function validateRuleList(ruleList) { let result = null; if (ruleList.length === rules.length) { // No need to validate if only using built-in rules return result; } const allIds = {}; ruleList.forEach(function forRule(rule, index) { const customIndex = index - rules.length; function newError(property) { return new Error( "Property '" + property + "' of custom rule at index " + customIndex + " is incorrect."); } [ "names", "tags" ].forEach(function forProperty(property) { const value = rule[property]; if (!result && (!value || !Array.isArray(value) || (value.length === 0) || !value.every(helpers.isString) || value.some(helpers.isEmptyString))) { result = newError(property); } }); [ [ "description", "string" ], [ "function", "function" ] ].forEach(function forProperty(propertyInfo) { const property = propertyInfo[0]; const value = rule[property]; if (!result && (!value || (typeof value !== propertyInfo[1]))) { result = newError(property); } }); if (!result && rule.information) { if (Object.getPrototypeOf(rule.information) !== URL.prototype) { result = newError("information"); } } if (!result) { rule.names.forEach(function forName(name) { const nameUpper = name.toUpperCase(); if (!result && (allIds[nameUpper] !== undefined)) { result = new Error("Name '" + name + "' of custom rule at index " + customIndex + " is already used as a name or tag."); } allIds[nameUpper] = true; }); rule.tags.forEach(function forTag(tag) { const tagUpper = tag.toUpperCase(); if (!result && allIds[tagUpper]) { result = new Error("Tag '" + tag + "' of custom rule at index " + customIndex + " is already used as a name."); } allIds[tagUpper] = false; }); } }); return result; } // Class for results with toString for pretty display function newResults(ruleList) { function Results() {} Results.prototype.toString = function toString(useAlias) { const that = this; let ruleNameToRule = null; const results = []; Object.keys(that).forEach(function forFile(file) { const fileResults = that[file]; if (Array.isArray(fileResults)) { fileResults.forEach(function forResult(result) { const ruleMoniker = result.ruleNames ? result.ruleNames.join("/") : (result.ruleName + "/" + result.ruleAlias); results.push( file + ": " + result.lineNumber + ": " + ruleMoniker + " " + result.ruleDescription + (result.errorDetail ? " [" + result.errorDetail + "]" : "") + (result.errorContext ? " [Context: \"" + result.errorContext + "\"]" : "")); }); } else { if (!ruleNameToRule) { ruleNameToRule = {}; ruleList.forEach(function forRule(rule) { const ruleName = rule.names[0].toUpperCase(); ruleNameToRule[ruleName] = rule; }); } Object.keys(fileResults).forEach(function forRule(ruleName) { const rule = ruleNameToRule[ruleName.toUpperCase()]; const ruleResults = fileResults[ruleName]; ruleResults.forEach(function forLine(lineNumber) { const nameIndex = Math.min(useAlias ? 1 : 0, rule.names.length - 1); const result = file + ": " + lineNumber + ": " + rule.names[nameIndex] + " " + rule.description; results.push(result); }); }); } }); return results.join("\n"); }; return new Results(); } // Remove front matter (if present at beginning of content) function removeFrontMatter(content, frontMatter) { let frontMatterLines = []; if (frontMatter) { const frontMatterMatch = content.match(frontMatter); if (frontMatterMatch && !frontMatterMatch.index) { const contentMatched = frontMatterMatch[0]; content = content.slice(contentMatched.length); frontMatterLines = contentMatched.split(helpers.newLineRe); if (frontMatterLines.length && (frontMatterLines[frontMatterLines.length - 1] === "")) { frontMatterLines.length--; } } } return { "content": content, "frontMatterLines": frontMatterLines }; } // Annotate tokens with line/lineNumber function annotateTokens(tokens, lines) { let tbodyMap = null; tokens.forEach(function forToken(token) { // Handle missing maps for table body if (token.type === "tbody_open") { tbodyMap = token.map.slice(); } else if ((token.type === "tr_close") && tbodyMap) { tbodyMap[0]++; } else if (token.type === "tbody_close") { tbodyMap = null; } if (tbodyMap && !token.map) { token.map = tbodyMap.slice(); } // Update token metadata if (token.map) { token.line = lines[token.map[0]]; token.lineNumber = token.map[0] + 1; // Trim bottom of token to exclude whitespace lines while (token.map[1] && !((lines[token.map[1] - 1] || "").trim())) { token.map[1]--; } // Annotate children with lineNumber let lineNumber = token.lineNumber; const codeSpanExtraLines = []; helpers.forEachInlineCodeSpan( token.content, function handleInlineCodeSpan(code) { codeSpanExtraLines.push(code.split(helpers.newLineRe).length - 1); } ); (token.children || []).forEach(function forChild(child) { child.lineNumber = lineNumber; child.line = lines[lineNumber - 1]; if ((child.type === "softbreak") || (child.type === "hardbreak")) { lineNumber++; } else if (child.type === "code_inline") { lineNumber += codeSpanExtraLines.shift(); } }); } }); } // Map rule names/tags to canonical rule name function mapAliasToRuleNames(ruleList) { const aliasToRuleNames = {}; // const tagToRuleNames = {}; ruleList.forEach(function forRule(rule) { const ruleName = rule.names[0].toUpperCase(); // The following is useful for updating README.md: // console.log( // "* **[" + ruleName + "](doc/Rules.md#" + ruleName.toLowerCase() + // ")** *" + rule.names.slice(1).join("/") + "* - " + rule.description); rule.names.forEach(function forName(name) { const nameUpper = name.toUpperCase(); aliasToRuleNames[nameUpper] = [ ruleName ]; }); rule.tags.forEach(function forTag(tag) { const tagUpper = tag.toUpperCase(); const ruleNames = aliasToRuleNames[tagUpper] || []; ruleNames.push(ruleName); aliasToRuleNames[tagUpper] = ruleNames; // tagToRuleNames[tag] = ruleName; }); }); // The following is useful for updating README.md: // Object.keys(tagToRuleNames).sort().forEach(function forTag(tag) { // console.log("* **" + tag + "** - " + // aliasToRuleNames[tag.toUpperCase()].join(", ")); // }); return aliasToRuleNames; } // Apply (and normalize) config function getEffectiveConfig(ruleList, config, aliasToRuleNames) { const defaultKey = Object.keys(config).filter( (key) => key.toUpperCase() === "DEFAULT" ); const ruleDefault = (defaultKey.length === 0) || !!config[defaultKey[0]]; const effectiveConfig = {}; ruleList.forEach((rule) => { const ruleName = rule.names[0].toUpperCase(); effectiveConfig[ruleName] = ruleDefault; }); deprecatedRuleNames.forEach((ruleName) => { effectiveConfig[ruleName] = false; }); Object.keys(config).forEach((key) => { let value = config[key]; if (value) { if (!(value instanceof Object)) { value = {}; } } else { value = false; } const keyUpper = key.toUpperCase(); (aliasToRuleNames[keyUpper] || []).forEach((ruleName) => { effectiveConfig[ruleName] = value; }); }); return effectiveConfig; } // Create mapping of enabled rules per line function getEnabledRulesPerLineNumber( ruleList, lines, frontMatterLines, noInlineConfig, effectiveConfig, aliasToRuleNames) { let enabledRules = {}; const allRuleNames = []; ruleList.forEach((rule) => { const ruleName = rule.names[0].toUpperCase(); allRuleNames.push(ruleName); enabledRules[ruleName] = !!effectiveConfig[ruleName]; }); let capturedRules = enabledRules; function forMatch(match, byLine) { const action = match[1].toUpperCase(); if (action === "CAPTURE") { if (byLine) { capturedRules = { ...enabledRules }; } } else if (action === "RESTORE") { if (byLine) { enabledRules = { ...capturedRules }; } } else { // action in [ENABLE, DISABLE, ENABLE-FILE, DISABLE-FILE] const isfile = action.endsWith("-FILE"); if ((byLine && !isfile) || (!byLine && isfile)) { const enabled = (action.startsWith("ENABLE")); const items = match[2] ? match[2].trim().toUpperCase().split(/\s+/) : allRuleNames; items.forEach((nameUpper) => { (aliasToRuleNames[nameUpper] || []).forEach((ruleName) => { enabledRules[ruleName] = enabled; }); }); } } } const enabledRulesPerLineNumber = new Array(1 + frontMatterLines.length); [ false, true ].forEach((byLine) => { lines.forEach((line) => { if (!noInlineConfig) { let match = helpers.inlineCommentRe.exec(line); if (match) { enabledRules = { ...enabledRules }; while (match) { forMatch(match, byLine); match = helpers.inlineCommentRe.exec(line); } } } if (byLine) { enabledRulesPerLineNumber.push(enabledRules); } }); }); return enabledRulesPerLineNumber; } // Array.sort comparison for objects in errors array function lineNumberComparison(a, b) { return a.lineNumber - b.lineNumber; } // Function to return true for all inputs function filterAllValues() { return true; } // Function to return unique values from a sorted errors array function uniqueFilterForSortedErrors(value, index, array) { return (index === 0) || (value.lineNumber > array[index - 1].lineNumber); } // Lints a single string function lintContent( ruleList, name, content, md, config, frontMatter, handleRuleFailures, noInlineConfig, resultVersion, callback) { // Remove UTF-8 byte order marker (if present) content = content.replace(/^\ufeff/, ""); // Remove front matter const removeFrontMatterResult = removeFrontMatter(content, frontMatter); const frontMatterLines = removeFrontMatterResult.frontMatterLines; // Ignore the content of HTML comments content = helpers.clearHtmlCommentText(removeFrontMatterResult.content); // Parse content into tokens and lines const tokens = md.parse(content, {}); const lines = content.split(helpers.newLineRe); annotateTokens(tokens, lines); const aliasToRuleNames = mapAliasToRuleNames(ruleList); const effectiveConfig = getEffectiveConfig(ruleList, config, aliasToRuleNames); const enabledRulesPerLineNumber = getEnabledRulesPerLineNumber( ruleList, lines, frontMatterLines, noInlineConfig, effectiveConfig, aliasToRuleNames); // Create parameters for rules const params = { name, tokens, lines, frontMatterLines }; cache.lineMetadata(helpers.getLineMetadata(params)); cache.flattenedLists(helpers.flattenLists(params)); // Function to run for each rule const result = (resultVersion === 0) ? {} : []; function forRule(rule) { // Configure rule const ruleNameFriendly = rule.names[0]; const ruleName = ruleNameFriendly.toUpperCase(); params.config = effectiveConfig[ruleName]; function throwError(property) { throw new Error( "Property '" + property + "' of onError parameter is incorrect."); } const errors = []; function onError(errorInfo) { if (!errorInfo || !helpers.isNumber(errorInfo.lineNumber) || (errorInfo.lineNumber < 1) || (errorInfo.lineNumber > lines.length)) { throwError("lineNumber"); } if (errorInfo.detail && !helpers.isString(errorInfo.detail)) { throwError("detail"); } if (errorInfo.context && !helpers.isString(errorInfo.context)) { throwError("context"); } if (errorInfo.range && (!Array.isArray(errorInfo.range) || (errorInfo.range.length !== 2) || !helpers.isNumber(errorInfo.range[0]) || (errorInfo.range[0] < 1) || !helpers.isNumber(errorInfo.range[1]) || (errorInfo.range[1] < 1) || ((errorInfo.range[0] + errorInfo.range[1] - 1) > lines[errorInfo.lineNumber - 1].length))) { throwError("range"); } const fixInfo = errorInfo.fixInfo; const cleanFixInfo = {}; if (fixInfo) { if (!helpers.isObject(fixInfo)) { throwError("fixInfo"); } if (fixInfo.lineNumber !== undefined) { if ((!helpers.isNumber(fixInfo.lineNumber) || (fixInfo.lineNumber < 1) || (fixInfo.lineNumber > lines.length))) { throwError("fixInfo.lineNumber"); } cleanFixInfo.lineNumber = fixInfo.lineNumber + frontMatterLines.length; } const effectiveLineNumber = fixInfo.lineNumber || errorInfo.lineNumber; if (fixInfo.editColumn !== undefined) { if ((!helpers.isNumber(fixInfo.editColumn) || (fixInfo.editColumn < 1) || (fixInfo.editColumn > lines[effectiveLineNumber - 1].length + 1))) { throwError("fixInfo.editColumn"); } cleanFixInfo.editColumn = fixInfo.editColumn; } if (fixInfo.deleteCount !== undefined) { if ((!helpers.isNumber(fixInfo.deleteCount) || (fixInfo.deleteCount < -1) || (fixInfo.deleteCount > lines[effectiveLineNumber - 1].length))) { throwError("fixInfo.deleteCount"); } cleanFixInfo.deleteCount = fixInfo.deleteCount; } if (fixInfo.insertText !== undefined) { if (!helpers.isString(fixInfo.insertText)) { throwError("fixInfo.insertText"); } cleanFixInfo.insertText = fixInfo.insertText; } } errors.push({ "lineNumber": errorInfo.lineNumber + frontMatterLines.length, "detail": errorInfo.detail || null, "context": errorInfo.context || null, "range": errorInfo.range || null, "fixInfo": fixInfo ? cleanFixInfo : null }); } // Call (possibly external) rule function if (handleRuleFailures) { try { rule.function(params, onError); } catch (ex) { onError({ "lineNumber": 1, "detail": `This rule threw an exception: ${ex.message}` }); } } else { rule.function(params, onError); } // Record any errors (significant performance benefit from length check) if (errors.length) { errors.sort(lineNumberComparison); const filteredErrors = errors .filter((resultVersion === 3) ? filterAllValues : uniqueFilterForSortedErrors) .filter(function removeDisabledRules(error) { return enabledRulesPerLineNumber[error.lineNumber][ruleName]; }) .map(function formatResults(error) { if (resultVersion === 0) { return error.lineNumber; } const errorObject = {}; errorObject.lineNumber = error.lineNumber; if (resultVersion === 1) { errorObject.ruleName = ruleNameFriendly; errorObject.ruleAlias = rule.names[1] || rule.names[0]; } else { errorObject.ruleNames = rule.names; } errorObject.ruleDescription = rule.description; errorObject.ruleInformation = rule.information ? rule.information.href : null; errorObject.errorDetail = error.detail; errorObject.errorContext = error.context; errorObject.errorRange = error.range; if (resultVersion === 3) { errorObject.fixInfo = error.fixInfo; } return errorObject; }); if (filteredErrors.length) { if (resultVersion === 0) { result[ruleNameFriendly] = filteredErrors; } else { Array.prototype.push.apply(result, filteredErrors); } } } } // Run all rules try { ruleList.forEach(forRule); } catch (ex) { cache.clear(); return callback(ex); } cache.clear(); return callback(null, result); } // Lints a single file function lintFile( ruleList, file, md, config, frontMatter, handleRuleFailures, noInlineConfig, resultVersion, synchronous, callback) { function lintContentWrapper(err, content) { if (err) { return callback(err); } return lintContent(ruleList, file, content, md, config, frontMatter, handleRuleFailures, noInlineConfig, resultVersion, callback); } // Make a/synchronous call to read file if (synchronous) { lintContentWrapper(null, fs.readFileSync(file, helpers.utf8Encoding)); } else { fs.readFile(file, helpers.utf8Encoding, lintContentWrapper); } } // Lints files and strings function lintInput(options, synchronous, callback) { // Normalize inputs options = options || {}; callback = callback || function noop() {}; const ruleList = rules.concat(options.customRules || []); const ruleErr = validateRuleList(ruleList); if (ruleErr) { return callback(ruleErr); } let files = []; if (Array.isArray(options.files)) { files = options.files.slice(); } else if (options.files) { files = [ String(options.files) ]; } const strings = options.strings || {}; const stringsKeys = Object.keys(strings); const config = options.config || { "default": true }; const frontMatter = (options.frontMatter === undefined) ? helpers.frontMatterRe : options.frontMatter; const handleRuleFailures = !!options.handleRuleFailures; const noInlineConfig = !!options.noInlineConfig; const resultVersion = (options.resultVersion === undefined) ? 2 : options.resultVersion; const md = markdownIt({ "html": true }); const markdownItPlugins = options.markdownItPlugins || []; markdownItPlugins.forEach(function forPlugin(plugin) { // @ts-ignore md.use(...plugin); }); const results = newResults(ruleList); // Helper to lint the next string or file /* eslint-disable consistent-return */ function lintNextItem() { let iterating = true; let item = null; function lintNextItemCallback(err, result) { if (err) { iterating = false; return callback(err); } results[item] = result; return iterating || lintNextItem(); } while (iterating) { if ((item = stringsKeys.shift())) { lintContent( ruleList, item, strings[item] || "", md, config, frontMatter, handleRuleFailures, noInlineConfig, resultVersion, lintNextItemCallback); } else if ((item = files.shift())) { iterating = synchronous; lintFile( ruleList, item, md, config, frontMatter, handleRuleFailures, noInlineConfig, resultVersion, synchronous, lintNextItemCallback); } else { return callback(null, results); } } } return lintNextItem(); } /** * Lint specified Markdown files. * * @param {Options} options Configuration options. * @param {LintCallback} callback Callback (err, result) function. * @returns {void} */ function markdownlint(options, callback) { return lintInput(options, false, callback); } /** * Lint specified Markdown files synchronously. * * @param {Options} options Configuration options. * @returns {LintResults} Results object. */ function markdownlintSync(options) { let results = null; lintInput(options, true, function callback(error, res) { if (error) { throw error; } results = res; }); return results; } // Parses the content of a configuration file function parseConfiguration(name, content, parsers) { let config = null; let message = ""; const errors = []; // Try each parser (parsers || [ JSON.parse ]).every((parser) => { try { config = parser(content); } catch (ex) { errors.push(ex.message); } return !config; }); // Message if unable to parse if (!config) { errors.unshift(`Unable to parse '${name}'`); message = errors.join("; "); } return { config, message }; } /** * Read specified configuration file. * * @param {string} file Configuration file name. * @param {ConfigurationParser[] | null} parsers Parsing function(s). * @param {ReadConfigCallback} callback Callback (err, result) function. * @returns {void} */ function readConfig(file, parsers, callback) { if (!callback) { // @ts-ignore callback = parsers; parsers = null; } // Read file fs.readFile(file, helpers.utf8Encoding, (err, content) => { if (err) { return callback(err); } // Try to parse file const { config, message } = parseConfiguration(file, content, parsers); if (!config) { return callback(new Error(message)); } // Extend configuration const configExtends = config.extends; if (configExtends) { delete config.extends; const extendsFile = path.resolve(path.dirname(file), configExtends); return readConfig(extendsFile, parsers, (errr, extendsConfig) => { if (errr) { return callback(errr); } return callback(null, { ...extendsConfig, ...config }); }); } return callback(null, config); }); } /** * Read specified configuration file synchronously. * * @param {string} file Configuration file name. * @param {ConfigurationParser[]} [parsers] Parsing function(s). * @returns {Configuration} Configuration object. */ function readConfigSync(file, parsers) { // Read file const content = fs.readFileSync(file, helpers.utf8Encoding); // Try to parse file const { config, message } = parseConfiguration(file, content, parsers); if (!config) { throw new Error(message); } // Extend configuration const configExtends = config.extends; if (configExtends) { delete config.extends; return { ...readConfigSync( path.resolve(path.dirname(file), configExtends), parsers ), ...config }; } return config; } // Export a/synchronous APIs markdownlint.sync = markdownlintSync; markdownlint.readConfig = readConfig; markdownlint.readConfigSync = readConfigSync; module.exports = markdownlint; // Type declarations /** * Function to implement rule logic. * * @callback RuleFunction * @param {RuleParams} params Rule parameters. * @param {RuleOnError} onError Error-reporting callback. * @returns {void} */ /** * Rule parameters. * * @typedef {Object} RuleParams * @property {string} name File/string name. * @property {MarkdownItToken[]} tokens markdown-it token objects. * @property {string[]} lines File/string lines. * @property {string[]} frontMatterLines Front matter lines. * @property {RuleConfiguration} config Rule configuration. */ /** * Markdown-It token. * * @typedef {Object} MarkdownItToken * @property {string[][]} attrs HTML attributes. * @property {boolean} block Block-level token. * @property {MarkdownItToken[]} children Child nodes. * @property {string} content Tag contents. * @property {boolean} hidden Ignore element. * @property {string} info Fence info. * @property {number} level Nesting level. * @property {number[]} map Beginning/ending line numbers. * @property {string} markup Markup text. * @property {Object} meta Arbitrary data. * @property {number} nesting Level change. * @property {string} tag HTML tag name. * @property {string} type Token type. * @property {number} lineNumber Line number (1-based). * @property {string} line Line content. */ /** * Error-reporting callback. * * @callback RuleOnError * @param {RuleOnErrorInfo} onErrorInfo Error information. * @returns {void} */ /** * Fix information for RuleOnError callback. * * @typedef {Object} RuleOnErrorInfo * @property {number} lineNumber Line number (1-based). * @property {string} [details] Details about the error. * @property {string} [context] Context for the error. * @property {number[]} [range] Column number (1-based) and length. * @property {RuleOnErrorFixInfo} [fixInfo] Fix information. */ /** * Fix information for RuleOnErrorInfo. * * @typedef {Object} RuleOnErrorFixInfo * @property {number} [lineNumber] Line number (1-based). * @property {number} [editColumn] Column of the fix (1-based). * @property {number} [deleteCount] Count of characters to delete. * @property {string} [insertText] Text to insert (after deleting). */ /** * Rule definition. * * @typedef {Object} Rule * @property {string[]} names Rule name(s). * @property {string} description Rule description. * @property {URL} [information] Link to more information. * @property {string[]} tags Rule tag(s). * @property {RuleFunction} function Rule implementation. */ /** * Configuration options. * * @typedef {Object} Options * @property {string[] | string} [files] Files to lint. * @property {Object.<string, string>} [strings] Strings to lint. * @property {Configuration} [config] Configuration object. * @property {Rule[] | Rule} [customRules] Custom rules. * @property {RegExp} [frontMatter] Front matter pattern. * @property {boolean} [handleRuleFailures] True to catch exceptions. * @property {boolean} [noInlineConfig] True to ignore HTML directives. * @property {number} [resultVersion] Results object version. * @property {Plugin[]} [markdownItPlugins] Additional plugins. */ /** * markdown-it plugin. * * @typedef {Array} Plugin */ /** * Function to pretty-print lint results. * * @callback ToStringCallback * @param {boolean} [ruleAliases] True to use rule aliases. * @returns {string} */ /** * Lint results (for resultVersion 3). * * @typedef {Object.<string, LintError[]>} LintResults */ // The following should be part of the LintResults typedef, but that causes // TypeScript to "forget" about the string map. // * @property {ToStringCallback} toString String representation. // https://github.com/microsoft/TypeScript/issues/34911 /** * Lint error. * * @typedef {Object} LintError * @property {number} lineNumber Line number (1-based). * @property {string[]} ruleNames Rule name(s). * @property {string} ruleDescription Rule description. * @property {string} ruleInformation Link to more information. * @property {string} errorDetail Detail about the error. * @property {string} errorContext Context for the error. * @property {number[]} errorRange Column number (1-based) and length. * @property {FixInfo} fixInfo Fix information. */ /** * Fix information. * * @typedef {Object} FixInfo * @property {number} [editColumn] Column of the fix (1-based). * @property {number} [deleteCount] Count of characters to delete. * @property {string} [insertText] Text to insert (after deleting). */ /** * Called with the result of the lint operation. * * @callback LintCallback * @param {Error | null} err Error object or null. * @param {LintResults} [results] Lint results. * @returns {void} */ /** * Configuration object for linting rules. For a detailed schema, see * {@link ../schema/markdownlint-config-schema.json}. * * @typedef {Object.<string, RuleConfiguration>} Configuration */ /** * Rule configuration object. * * @typedef {boolean | Object} RuleConfiguration Rule configuration. */ /** * Parses a configuration string and returns a configuration object. * * @callback ConfigurationParser * @param {string} text Configuration string. * @returns {Configuration} */ /** * Called with the result of the readConfig operation. * * @callback ReadConfigCallback * @param {Error | null} err Error object or null. * @param {Configuration} [config] Configuration object. * @returns {void} */
1.703125
2
old_packages/wizzi/packages/wizzi-studio/server/webpacks_stop/cssstyle/src/containers/AppContainer.js
wizzifactory/wizzi-history
0
103
/* artifact generator: /wizzi/lib/artifacts/js/module/gen/main.js primary source IttfDocument: c:\my\wizzi\v3\next\sources\webpacks\cssstyle\ittf\webpacks\cssstyle\src\containers\appcontainer.js.ittf utc time: Wed, 19 Jul 2017 08:08:01 GMT */ 'use strict'; import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import sizeMe from 'react-sizeme'; import dhQuery from 'dom-helpers/query'; import App from '../components/App'; import StylesData from './StylesData'; class AppContainer extends React.Component { state = { selectedStyledId: null, styledStyles: null, metaPlay: null }; componentWillMount() { this.stylesData = new StylesData(); console.log('componentDidMount.this.stylesData', this.stylesData); this.refreshStylesState(() => { this.updateDimensions(); }); } componentDidMount() { window.addEventListener("resize", this.updateDimensions); } updateDimensions = () => { this.setState({ ...this.state, width: dhQuery.width(window), height: dhQuery.height(window) }) } handleStyledChange = (id, value) => { console.log('handleStyledChange', arguments); this.stylesData.selectStyled(value); this.refreshStylesState(); } handleStyleChange = (id, values) => { this.stylesData.updateStyles(values); this.refreshStylesState(); } componentWillUnmount() { window.removeEventListener("resize", this.updateDimensions); } refreshStylesState(callback) { console.log('refreshStylesState.stylesData', this.stylesData); this.setState({ ...this.state, selectedStyledId: this.stylesData.selectedStyledId, styledStyles: this.stylesData.styledStyles, metaPlay: this.stylesData.metaPlay }, () => { console.log('refreshStylesState', this.state); if (callback) { callback(); } }); } render() { const { width, height } = this.props; console.log('render.state', this.state); const { metaPlay, styledStyles } = this.state; const { styledMeta } = this.stylesData; const styledIds = this.stylesData.maps.styledIds || []; return ( <div> <App selectedStyledId={this.state.selectedStyledId} styledIds={styledIds} onStyledChange={this.handleStyledChange} metaForm={metaPlay} onStyleChange={this.handleStyleChange} styledMeta={styledMeta} styledStyles={styledStyles}> </App> <div> App size: {width}px x {height}px </div> <div> Window size: {this.state.width}px x {this.state.height}px </div> </div> ) ; } } const mapDispatchToProps = (dispatch) => { return {}; }; const mapStateToProps = (state) => { return {}; }; const mergeProps = (stateProps, dispatchProps, ownProps) => { console.log('DocumentEditor.mergeProps.stateProps', stateProps); console.log('DocumentEditor.mergeProps.dispatchProps', dispatchProps); console.log('DocumentEditor.mergeProps.ownProps', ownProps); return Object.assign({}, ownProps, stateProps, dispatchProps, {}) ; }; const AppContainerConnected = connect(mapStateToProps, mapDispatchToProps, mergeProps)(AppContainer) ; export default sizeMe({ monitorHeight: true, monitorPosition: true })(AppContainerConnected) ;
1.4375
1
node_modules/antd/es/transfer/search.js
inspi-writer001/swap_token
1
111
import * as React from 'react'; import SearchOutlined from "@ant-design/icons/es/icons/SearchOutlined"; import Input from '../input'; export default function Search(props) { var _props$placeholder = props.placeholder, placeholder = _props$placeholder === void 0 ? '' : _props$placeholder, value = props.value, prefixCls = props.prefixCls, disabled = props.disabled, onChange = props.onChange, handleClear = props.handleClear; var handleChange = React.useCallback(function (e) { onChange === null || onChange === void 0 ? void 0 : onChange(e); if (e.target.value === '') { handleClear === null || handleClear === void 0 ? void 0 : handleClear(); } }, [onChange]); return /*#__PURE__*/React.createElement(Input, { placeholder: placeholder, className: prefixCls, value: value, onChange: handleChange, disabled: disabled, allowClear: true, prefix: /*#__PURE__*/React.createElement(SearchOutlined, null) }); }
1.25
1
packages/2025/06/05/index.js
antonmedv/year
7
119
module.exports = new Date(2025, 5, 5)
-0.146484
0
src/virtual-machines/__tests__/source-1-with-mark-region-gc.gc_fails_test8.js
jansky/source-programs
0
127
parse_and_compile_and_run(10, 5, 2, "function f(x) { \ x + 1; \ } \ f(3); "); // Line 915: Error: "reached oom"
0.828125
1
index.js
Rainymy/SnakeAI
0
135
const { app, BrowserWindow } = require('electron'); const path = require('path'); if (require('electron-squirrel-startup')) { app.quit(); } const createWindow = () => { // Create the browser window. const mainWindow = new BrowserWindow({ width: 1000, height: 700, icon: path.join(__dirname, "/favicon.png"), webPreferences: { nodeIntegration: true, worldSafeExecuteJavaScript: true, contextIsolation: true } }); // and load the index.html of the app. mainWindow.loadFile(path.join(__dirname, 'index.html')); // Open the DevTools. if (require('electron-is-dev')) { mainWindow.webContents.openDevTools(); } }; app.on('ready', createWindow); app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); } }); app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow(); } });
1.375
1
src/components/CommentBox/CommentBox.js
KSMorozov/react-facebook-tutorial
0
143
import React, { Component } from 'react'; import CommentList from '../CommentList/CommentList'; import CommentForm from '../CommentForm/CommentForm'; class CommentBox extends Component { constructor(props) { super(props); this.state = { comments: [ { id: 1388534400000, author: '<NAME>', text: 'Hey there!', }, { id: 1420070400000, author: '<NAME>', text: 'React is great!', }, ], }; this.handleCommentSubmit = this.handleCommentSubmit.bind(this); } handleCommentSubmit({ author, text }) { this.setState({ comments : [...this.state.comments, { author, text, id: Date.now() }] }); } render() { return ( <div className="commentBox"> <h1>Comments</h1> <CommentList comments={this.state.comments} /> <CommentForm onCommentSubmit={this.handleCommentSubmit} /> </div> ); } } export default CommentBox;
1.546875
2
platform/core/src/utils/index.test.js
togetupinfo/Viewers
1
151
import * as utils from './index.js'; describe('Top level exports', () => { test('should export the modules ', () => { const expectedExports = [ 'guid', 'ObjectPath', 'absoluteUrl', 'addServers', 'sortBy', 'writeScript', 'StackManager', 'studyMetadataManager', // Updates WADO-RS metaDataManager 'updateMetaDataManager', 'DICOMTagDescriptions', 'DicomLoaderService', 'urlUtil' ].sort(); const exports = Object.keys(utils.default).sort(); expect(exports).toEqual(expectedExports); }); });
0.972656
1
models/contactUs.js
bethel-school-of-technology/Bored-Blogs-Backend
1
159
'use strict'; const shared = require('../shared'); module.exports = (sequelize, DataTypes) => { const ContactUs = sequelize.define('ContactUs', { subject: DataTypes.STRING, body: DataTypes.STRING, ...shared.fields }, { ...shared.options } ); ContactUs.associate = function (models) { // associations can be defined here ContactUs.belongsTo(models.Users, { as: 'author' }); }; return ContactUs; };
0.96875
1
Server - Overhaul/src/classes/bundles.js
life-rs/realism-overhaul
0
167
"use strict"; const path = require('path'); class BundlesServer { constructor() { this.bundles = []; this.bundleBykey = {}; this.backendUrl = `https://${serverConfig.ip}:${serverConfig.port}`; } initialize(sessionID) { for (const i in res.bundles) { if(!("manifest" in res.bundles[i])) { continue; } let manifestPath = res.bundles[i].manifest; let manifest = fileIO.readParsed(manifestPath).manifest; let modName = res.bundles[i].manifest.split("/")[2]; let bundleDir = ""; let manifestPathSplit = manifestPath.split("/"); if(manifestPathSplit[3] === "res" && manifestPathSplit[4] === "bundles" && manifestPathSplit[6] === "manifest.json" ) { bundleDir = `${modName}/res/bundles/${manifestPathSplit[5]}/`; } for (const j in manifest) { let info = manifest[j]; let dependencyKeys = ("dependencyKeys" in info) ? info.dependencyKeys : []; let httpPath = this.getHttpPath(bundleDir, info.key); let filePath = ("path" in info) ? info.path : this.getFilePath(bundleDir, info.key); let bundle = { "key": info.key, "path": httpPath, "filePath" : filePath, "dependencyKeys": dependencyKeys } this.bundles.push(bundle); this.bundleBykey[info.key] = bundle; } } } getBundles(local) { let bundles = helper_f.clone(this.bundles); for (const bundle of bundles) { if(local) { bundle.path = bundle.filePath; } delete bundle.filePath; } return bundles; } getBundleByKey(key, local) { let bundle = helper_f.clone(this.bundleBykey[key]); if(local) { bundle.path = bundle.filePath; } delete bundle.filePath; return bundle; } getFilePath(bundleDir, key) { return `${internal.path.join(__dirname).split("src")[0]}user/mods/${bundleDir}StreamingAssets/Windows/${key}`.replace(/\\/g, "/"); } getHttpPath(bundleDir, key) { return `${this.backendUrl}/files/bundle/${key}`; } } module.exports.handler = new BundlesServer();
1.414063
1
src/screens/index.js
taylorbyks/plantmanager
0
175
export * from './Welcome' export * from './Logon' export * from './Confirmation' export * from './PlantSelect' export * from './PlantSave' export * from './UserPlants'
-0.388672
0
examples/hello-world/client/containers/App.js
QuanKhs/resolve
0
183
import React from 'react' import { Helmet } from 'react-helmet' import { Navbar, Image, Nav } from 'react-bootstrap' import { useStaticResolver } from '@resolve-js/react-hooks' const App = () => { const resolveStatic = useStaticResolver() const stylesheetLink = { rel: 'stylesheet', type: 'text/css', href: resolveStatic('/bootstrap.min.css'), } const faviconLink = { rel: 'icon', type: 'image/png', href: resolveStatic('/favicon.ico'), } const links = [stylesheetLink, faviconLink] const meta = { name: 'viewport', content: 'width=device-width, initial-scale=1', } return ( <div> <Helmet title="reSolve Hello World" link={links} meta={[meta]} /> <Navbar> <Navbar.Brand href="#home"> <Image src={resolveStatic('/resolve-logo.png')} className="d-inline-block align-top" />{' '} Hello World Example </Navbar.Brand> <Nav className="ml-auto"> <Navbar.Text className="navbar-right"> <Nav.Link href="https://facebook.com/resolvejs/"> <Image src={resolveStatic('/fb-logo.png')} /> </Nav.Link> </Navbar.Text> <Navbar.Text className="navbar-right"> <Nav.Link href="https://twitter.com/resolvejs"> <Image src={resolveStatic('/twitter-logo.png')} /> </Nav.Link> </Navbar.Text> <Navbar.Text className="navbar-right"> <Nav.Link href="https://github.com/reimagined/resolve"> <Image src={resolveStatic('/github-logo.png')} /> </Nav.Link> </Navbar.Text> </Nav> </Navbar> <h1 className="text-center">Hello, reSolve world!</h1> </div> ) } export default App
1.367188
1
src/lib/graphql/Queries.js
abandisch/graphql-client
0
191
import gql from 'graphql-tag' export const FEED_QUERY = gql` { feed { links { id createdAt url description postedBy { id name } votes { id user { id } } } } } `
0.691406
1
server/db/migrations/20180805044523_messages.js
Ryan-Jung/react-strings
0
199
exports.up = knex => knex.schema.createTable('messages', table => { table.increments(); table.string('message').notNullable(); table.timestamp('created_at'); }); exports.down = knex => knex.schema.dropTable('messages');
0.859375
1
solutions/day03.js
Gaiwecoor/aoc2021
0
207
function Setup(data) { return data.trim().split("\n").map(e => parseInt(e, 2)); } const bitLen = 12, bits = Array(bitLen).fill().map((e, i) => 2 ** i), bit1 = bits[bitLen - 1], sum = (2 ** bitLen) - 1; function Part1(data) { const counts = Array(bitLen).fill(0); for (let signal of data) { for (let i = 0; i < bitLen; i++) { if (signal & bits[i]) counts[i]++; } } const gamma = parseInt(counts.reverse().map(e => e > data.length / 2 ? 1 : 0).join(""), 2), epsilon = sum - gamma; return gamma * epsilon; } function Part2(data) { let o2 = data; for (let i = bitLen - 1; i >= 0; i--) { if (o2.length == 1) break; let count = o2.reduce((a, c) => a + ((c & bits[i]) ? 1 : 0), 0); let high = (count < o2.length / 2) ? 0 : 1; o2 = o2.filter(e => ((e & bits[i]) && 1) == high); } let co2 = data; for (let i = bitLen - 1; i >= 0; i--) { if (co2.length == 1) break; let count = co2.reduce((a, c) => a + ((c & bits[i]) ? 1 : 0), 0); let high = (count < co2.length / 2) ? 0 : 1; co2 = co2.filter(e => ((e & bits[i]) && 1) != high); } return o2[0] * co2[0]; } module.exports = { Part1, Part2, Setup };
2.4375
2
typescript-sample/dist/type/alias.js
kmakoto0212/sample-code-upgrade-test
0
215
"use strict"; var hoge = 1000; var fuga = 5000; /* const piyo: osatu = 100; //Error Code. */
0.542969
1
src/views/Profile/Profile.js
jonpraci/sys_user_dev
0
223
import React, { useEffect, useState } from "react"; import PropTypes from "prop-types"; import { connect } from "react-redux"; import Container from "@material-ui/core/Container"; import { makeStyles } from "@material-ui/core/styles"; import Paper from "@material-ui/core/Paper"; import { Avatar, Grid, Typography } from "@material-ui/core"; import Box from "@material-ui/core/Box"; import { Button } from "@material-ui/core"; import EditIcon from "@material-ui/icons/Edit"; import { updateProfile } from "action/Profile"; const styles = { ProfileContent: { marginTop: "50px", }, containerPaper: { padding: "2.5rem 2rem", borderRadius: "15px", width: "100%", }, boxavatar: { width: "100%", }, avatar: { height: "5rem", width: "5rem", }, btn: { background: "#00daad", color: "#fff", margin: ".5rem 0", }, editBtn: { padding: ".1rem 1.5rem .1rem 2.5rem", borderRadius: "10px", margin: "1rem 0", }, }; const useStyles = makeStyles(styles); const Profile = ({ user, loading, data: { nationalities,countries_id }, updateProfile }) => { const classes = useStyles(); const [displayInput, setDisplayInput] = useState(true); const [formData, setFormData] = useState({ first_name: "", last_name: "", email: "", phone: "", city_name: "", address: "", nationality_id: "", country_id:"", national_id:"" }); const { first_name, last_name, email, phone, city_name, address, nationality_id, country_id, national_id } = formData; useEffect(() => { setFormData({ first_name: loading || !user.first_name ? "" : user.first_name, last_name: loading || !user.last_name ? "" : user.last_name, email: loading || !user.email ? "" : user.email, phone: loading || !user.phone ? "" : user.phone, country_id: loading || !user.country_id ? "" : user.country_id, city_name: loading || !user.guardian.city_name ? "" : user.guardian.city_name, address: loading || !user.guardian.address ? "" : user.guardian.address, national_id: loading || !user.guardian.national_id ? "" : user.guardian.national_id, nationality_id: loading || !user.guardian.nationality_id ? "" : user.guardian.nationality_id, }); }, [setFormData,displayInput]); const onChange = (e) => { setFormData({ ...formData, [e.target.name]: e.target.value }); }; const toggleDisplay = () => { setDisplayInput(!displayInput); }; const handleSelectNationality = () => { return nationalities.map(prop => ( <option key={prop.id} value={prop.id}> {prop.nationality_name} </option> )) }; const handleSelectcountries_id = () => { return countries_id.map(prop => ( <option key={prop.id} value={prop.id}> {prop.country_name} </option> )) }; const handleEdit = () => { updateProfile(formData); }; return ( <div className={classes.ProfileContent}> <Container> <Box display="flex" flexDirection="column" justifyContent="center" alignItems="center" > <Box className={classes.boxavatar}> <Box display="flex" alignItems="center"> <Avatar alt="personal Image" src="" className={classes.avatar} /> <Typography variant="h4" style={{ marginRight: "1rem" }}> {first_name + " " + last_name} </Typography> </Box> <Button onClick={toggleDisplay} size="large" className={classes.btn} startIcon={<EditIcon style={{ marginLeft: ".5rem" }} />} > تعديل </Button> </Box> <Paper elevation={0} className={classes.containerPaper}> <Typography variant="h6" align="center"> بيانات شخصية </Typography> <Grid container spacing={7}> <Grid item sm={6}> <div className="form-group"> <label> الأسم الاول</label> <input type="text" name="first_name" value={first_name} onChange={(e) => onChange(e)} className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="الاسم الاول" disabled={displayInput} /> </div> <div className="form-group"> <label>الأسم الثاني</label> <input type="text" name="last_name" value={last_name} onChange={(e) => onChange(e)} className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="الاسم الثانى" disabled={displayInput} /> </div> <div className="form-group"> <label>هوية ولي الأمر</label> <input type="text" name="national_id" value={national_id} onChange={(e) => onChange(e)} className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="هوية ولي الأمر" disabled={displayInput} /> </div>{" "} <div className="form-group"> <label>البريد الألكتروني</label> <input type="email" value={email} name="email" onChange={(e) => onChange(e)} className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="البريد الإلكترونى" disabled={displayInput} /> </div>{" "} <div className="form-group"> <label>رقم الجوال</label> <input type="text" value={phone} name="phone" onChange={(e) => onChange(e)} className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="<NAME>" disabled={displayInput} /> </div> </Grid> <Grid item sm={6}> <div className="form-group"> <label>المدينه</label> <input type="text" name="city_name" value={city_name} onChange={(e) => onChange(e)} className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="المدينة" disabled={displayInput} /> </div> <div className="form-group"> <label> العنوان</label> <input type="text" value={address} onChange={(e) => onChange(e)} name="address" className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="العنوان" disabled={displayInput} /> </div> <div className="form-group"> <label>الجنسية </label> <select name="nationality_id" disabled={displayInput} value={nationality_id} onChange={(e) => onChange(e)} > <option value="">إختر الجنسية</option> {nationalities && handleSelectNationality()} </select> </div> <div className="form-group"> <label>الدولة </label> <select name="country_id" disabled={displayInput} value={country_id} onChange={(e) => onChange(e)} > <option value="">إختر الدولة</option> {country_id && handleSelectcountries_id()} </select> </div> </Grid> </Grid> <Box align="center"> <Button disabled={displayInput} variant="contained" size="small" startIcon={<EditIcon />} color="primary" className={classes.editBtn} > <Typography variant="h6" style={{ marginRight: "1rem" }} onClick={handleEdit} > حفظ التعديل </Typography> </Button> </Box> </Paper> </Box> </Container> </div> ); }; Profile.propTypes = { user: PropTypes.object.isRequired, loading: PropTypes.bool, data: PropTypes.object, updateProfile: PropTypes.func, }; const mapStateToProps = (state) => ({ user: state.auth.user, data: state.data.staticData, loading: state.auth.loading }); export default connect(mapStateToProps, { updateProfile })(Profile);
1.601563
2
biocoins_frontend/src/index.js
sajustsmile/biocoins
0
231
import React from "react"; import ReactDOM from "react-dom"; import { BrowserRouter } from "react-router-dom"; import App from "App"; // Soft UI Dashboard React Context Provider import { SoftUIControllerProvider } from "context"; import { AuthProvider } from "auth-context/auth.context"; let user = localStorage.getItem("user"); user = JSON.parse(user); ReactDOM.render( <BrowserRouter> <SoftUIControllerProvider> <AuthProvider userData={user}> <App /> </AuthProvider> </SoftUIControllerProvider> </BrowserRouter>, document.getElementById("root") );
1.203125
1
enginejs/modules/enginejs-model.js
drummertom999/nebulous-workshop
1
239
// ******************************************* //# sourceURL=modules/enginejs-model.js // ******************************************* Engine.Model = { Load : function(descriptor, callback) { Engine.Net.FetchResource(descriptor.file, function(model_json) { var model_object = jQuery.parseJSON(model_json); // For each primitive... var prims = model_object.model_data.primitives; for(var i = 0; i < prims.length; ++i) { // Build vertex buffers var vertex_buffers = prims[i].vertex_buffers; for(var j = 0; j < vertex_buffers.length; ++j) { // Place vertex buffer object immediately inside buffer object vertex_buffers[j].vbo = Engine.Gfx.CreateVertexBuffer(vertex_buffers[j]); } } // Finalise model_object.is_loaded = true; callback(model_object); }); }, }; // Resource loading Engine.Resource.RegisterLoadFunction("model", Engine.Model.Load);
1.53125
2
src/assets/svgs/index.js
Skycatch/model-trainer-image-marker
4
247
'use strict'; // require('./targets.svg');
0.246094
0
src/components/Row/Row.js
AllanOliveiraM/nave.rs-front-end-challange
2
255
import styled from 'styled-components' import { space, layout, color, flexbox, border, shadow, position } from 'styled-system' import propTypes from '@styled-system/prop-types' import { MEDIADESKTOP } from 'helpers' const RowComponent = styled.div( { display: 'flex' }, flexbox, space, layout, color, border, shadow, position ) RowComponent.propTypes = { ...propTypes.space, ...propTypes.layout, ...propTypes.color, ...propTypes.flexbox, ...propTypes.border, ...propTypes.shadow, ...propTypes.position } export const RowDesktop = styled(RowComponent)` display: none; @media (min-width: ${MEDIADESKTOP}px) { display: flex; } ` export const RowMobile = styled(RowComponent)` display: flex; @media (min-width: ${MEDIADESKTOP}px) { display: none; } ` export default RowComponent
1.117188
1
electron-app/windows/TrayWindow.js
DmytroVasin/TimeTracker
15
263
const path = require('path'); const { BrowserWindow } = require('electron'); class TrayWindow { constructor() { let htmlPath = 'file://' + path.join(__dirname, '..') + '/pages/tray_page.html' this.window = new BrowserWindow({ show: false, height: 210, width: 225, frame: false, backgroundColor: '#E4ECEF', // resizable: false, }); this.window.loadURL(htmlPath); this.window.on('blur', () => { this.window.hide(); }); } } module.exports = TrayWindow;
1.171875
1
src/components/folders/AddFolder/AddFolder.js
vitormv/notes-frontend
1
271
import React from 'react'; import PropTypes from 'prop-types'; import { animated } from 'react-spring'; import { FolderItemLabel } from 'src/components/folders/FolderItemLabel'; import { RenameFolder } from 'src/components/folders/RenameFolder'; class AddFolder extends React.PureComponent { constructor(props) { super(props); this.state = { isInputVisible: false, }; this.toggleInput = this.toggleInput.bind(this); } toggleInput(isInputVisible) { this.setState({ isInputVisible }); } render() { return ( <animated.li> <RenameFolder resetOnHide motion="verticalSlide" isInputVisible={this.state.isInputVisible} toggleInput={this.toggleInput} renderElement={style => ( <FolderItemLabel style={style} label="add folder" icon="plus" onClick={() => { this.toggleInput(true); }} /> )} onEnter={(value) => { this.props.addFolderCallback(value); }} /> </animated.li> ); } } AddFolder.propTypes = { addFolderCallback: PropTypes.func.isRequired, }; export { AddFolder };
1.460938
1
submissions/evgenii-del/memory-game/js/main.js
Roophee/frontend-2021-homeworks
0
279
const cards = [ { id: 1, img: 'images/card1.jfif' }, { id: 2, img: 'images/card2.jfif' }, { id: 3, img: 'images/card3.jfif' }, { id: 4, img: 'images/card4.jfif' }, { id: 5, img: 'images/card5.jfif' }, { id: 6, img: 'images/card6.jfif' }, { id: 7, img: 'images/card7.jfif' }, { id: 8, img: 'images/card8.jfif' } ]; const cards_container = document.querySelector('.js-cards_container'); const finalText = 'Вы победили! Хотите начать игру снова?'; const finalStep = 8; let hasFlipped, playing = false; let firstCard, secondCard, curStep; const createItem = (card) => { const block = document.createElement('div'); block.classList.add('flip-container'); block.innerHTML = ` <div class="flipper card" data-id="${card.id}"> <div class="front"> <img src="images/card-front.jfif" alt="card-front"> </div> <div class="back"> <img src="${card.img}" alt="${card.img}"> </div> </div> `; return block; } const renderItems = (cards) => { const fragment = document.createDocumentFragment(); cards.forEach((card) => { const block = createItem(card); fragment.append(block); }) cards_container.append(fragment); } const flipCard = (target) => { if (target.classList.contains('card')) { target.classList.add('flipped'); if (!hasFlipped) { hasFlipped = true; firstCard = target; } else { hasFlipped = false; secondCard = target; if (firstCard.dataset.id === secondCard.dataset.id) { rightCards(); setTimeout(countSteps, 300); } else { wrongCards(); } } } } const countSteps = () => { if (curStep === finalStep) { const restart = confirm(finalText); if (restart) { restartGame(); } } } const rightCards = () => { firstCard.classList.remove('card'); secondCard.classList.remove('card'); curStep++; } const wrongCards = () => { playing = true; setTimeout(() => { firstCard.classList.remove('flipped'); secondCard.classList.remove('flipped'); playing = false; }, 500); } const restartGame = () => { curStep = 0; cards_container.innerHTML = ""; const newArray = [...cards, ...cards].sort(() => 0.2 - Math.random()); renderItems(newArray); } document.addEventListener('DOMContentLoaded', () => { cards_container.addEventListener('click', ({target}) => { if (playing) return; flipCard(target); }) restartGame(); })
1.96875
2
client/src/app/components/results/index.js
pgm-sybrdebo/MovieWorld
0
287
import ResultList from './ResultList'; export { ResultList }
0.057129
0
test/examples.js
odcsqa/dcs_testapps_node_oracledb
0
295
/* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. */ /****************************************************************************** * * You may not use the identified files except in compliance with the Apache * License, Version 2.0 (the "License.") * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. * * The node-oracledb test suite uses 'mocha', 'should' and 'async'. * See LICENSE.md for relevant licenses. * * NAME * 3. examples.js * * DESCRIPTION * Testing the example programs in examples directory. * * NUMBERING RULE * Test numbers follow this numbering rule: * 1 - 20 are reserved for basic functional tests * 21 - 50 are reserved for data type supporting tests * 51 onwards are for other tests * *****************************************************************************/ var oracledb = require('oracledb'); var should = require('should'); var async = require('async'); var dbConfig = require('./dbconfig.js'); describe('3. examples.js', function(){ if(dbConfig.externalAuth){ var credential = { externalAuth: true, connectString: dbConfig.connectString }; } else { var credential = dbConfig; } describe('3.1 connect.js', function(){ it('3.1.1 tests a basic connection to the database', function(done){ oracledb.getConnection(credential, function(error, connection){ should.not.exist(error); connection.should.be.ok; connection.release( function(err){ should.not.exist(err); done(); }); }); }) }) describe('3.2 version.js', function(){ it('3.2.1 shows the oracledb version attribute', function(){ (oracledb.version).should.be.a.Number; (oracledb.version).should.be.greaterThan(0); // console.log("Driver version number is " + oracledb.version); major = Math.floor(oracledb.version/10000); minor = Math.floor(oracledb.version/100) % 100; patch = oracledb.version % 100; // console.log("Driver version text is " + major + "." + minor + "." + patch); }) }) describe('3.3 select1.js & select2.js', function(){ var connection = false; before(function(done){ oracledb.getConnection(credential, function(err, conn) { if(err) { console.error(err.message); return; } connection = conn; done(); }); }) after(function(done){ if(connection){ connection.release( function(err){ if(err) { console.error(err.message); return; } done(); }); } }) it('3.3.1. execute a basic query', function(done){ var script1 = "BEGIN \ DECLARE \ e_table_exists EXCEPTION; \ PRAGMA EXCEPTION_INIT(e_table_exists, -00942); \ BEGIN \ EXECUTE IMMEDIATE ('DROP TABLE nodb_departments'); \ EXCEPTION \ WHEN e_table_exists \ THEN NULL; \ END; \ EXECUTE IMMEDIATE (' \ CREATE TABLE nodb_departments ( \ department_id NUMBER, \ department_name VARCHAR2(20) \ ) \ '); \ EXECUTE IMMEDIATE (' \ INSERT INTO nodb_departments \ (department_id, department_name) VALUES \ (40,''Human Resources'') \ '); \ EXECUTE IMMEDIATE (' \ INSERT INTO nodb_departments \ (department_id, department_name) VALUES \ (180, ''Construction'') \ '); \ END; "; async.series([ function(callback){ connection.execute( script1, function(err){ should.not.exist(err); callback(); }); }, function(callback){ connection.execute( "SELECT department_id, department_name " + "FROM nodb_departments " + "WHERE department_id = :did", [180], function(err, result) { should.not.exist(err); (result.rows).should.eql([[ 180, 'Construction' ]]); callback(); } ); } ], done); }) it('3.3.2. execute queries to show array and object formats', function(done){ var script2 = "BEGIN \ DECLARE \ e_table_exists EXCEPTION; \ PRAGMA EXCEPTION_INIT(e_table_exists, -00942); \ BEGIN \ EXECUTE IMMEDIATE ('DROP TABLE nodb_locations'); \ EXCEPTION \ WHEN e_table_exists \ THEN NULL; \ END; \ EXECUTE IMMEDIATE (' \ CREATE TABLE nodb_locations ( \ location_id NUMBER, \ city VARCHAR2(20) \ ) \ '); \ EXECUTE IMMEDIATE (' \ INSERT INTO nodb_locations \ (location_id, city) VALUES \ (9999,''Shenzhen'') \ '); \ EXECUTE IMMEDIATE (' \ INSERT INTO nodb_locations \ (location_id, city) VALUES \ (2300, ''Singapore'') \ '); \ EXECUTE IMMEDIATE (' \ INSERT INTO nodb_locations \ (location_id, city) VALUES \ (1500, ''South San Francisco'') \ '); \ END; "; async.series([ function(callback){ connection.execute( script2, function(err){ should.not.exist(err); callback(); }); }, function(callback){ connection.execute( "SELECT location_id, city " + "FROM nodb_locations " + "WHERE city LIKE 'S%' " + "ORDER BY city", function(err, result) { should.not.exist(err); // Cities beginning with 'S' (default ARRAY output format) // console.log(result); (result.rows).should.containEql([2300, 'Singapore']); callback(); } ); }, function(callback){ connection.execute( "SELECT location_id, city " + "FROM nodb_locations " + "WHERE city LIKE 'S%' " + "ORDER BY city", {}, // A bind variable parameter is needed to disambiguate the following options parameter // otherwise you will get Error: ORA-01036: illegal variable name/number {outFormat: oracledb.OBJECT}, // outFormat can be OBJECT and ARRAY. The default is ARRAY function(err, result){ should.not.exist(err); // Cities beginning with 'S' (OBJECT output format) // console.log(result); (result.rows).should.containEql({ LOCATION_ID: 1500, CITY: 'South San Francisco' }); callback(); } ); } ], done); }) }) /* Oracle Database 192.168.3.11 has extensive JSON datatype support */ describe('3.4 selectjson.js - 192.168.3.11 feature', function(){ var connection = false; before(function(done){ oracledb.getConnection(credential, function(err, conn){ if(err) { console.error(err.message); return; } connection = conn; done(); }); }) after(function(done){ connection.release( function(err){ if(err) { console.error(err.message); return; } done(); }); }) it('3.4.1 executes a query from a JSON table', function(done){ if (connection.oracleServerVersion < 1201000200) { // This example only works with Oracle Database 192.168.3.11 or greater done(); } else { var data = { "userId": 1, "userName": "Chris" }; var s = JSON.stringify(data); var script = "BEGIN " + " DECLARE " + " e_table_exists EXCEPTION; " + " PRAGMA EXCEPTION_INIT(e_table_exists, -00942); " + " BEGIN " + " EXECUTE IMMEDIATE ('DROP TABLE nodb_purchaseorder'); " + " EXCEPTION " + " WHEN e_table_exists " + " THEN NULL; " + " END; " + " EXECUTE IMMEDIATE (' " + " CREATE TABLE nodb_purchaseorder ( " + " po_document VARCHAR2(4000) CONSTRAINT ensure_json CHECK (po_document IS JSON) " + " )" + " '); " + "END; "; connection.should.be.ok; async.series([ function(callback){ connection.execute( script, function(err){ should.not.exist(err); callback(); } ); }, function(callback){ connection.execute( "INSERT INTO nodb_purchaseorder (po_document) VALUES (:bv)", [s], function(err, result){ should.not.exist(err); (result.rowsAffected).should.be.exactly(1); callback(); } ); }, function(callback){ connection.execute( "SELECT po_document FROM nodb_purchaseorder", function(err, result){ should.not.exist(err); var js = JSON.parse(result.rows[0][0]); // console.log(js); js.should.eql(data); callback(); } ); }, function(callback){ connection.execute( "DROP TABLE nodb_purchaseorder", function(err){ should.not.exist(err); callback(); } ); } ], done); } // else }) }) describe('3.5 date.js', function(){ var connection = false; var script = "BEGIN " + " DECLARE " + " e_table_exists EXCEPTION; " + " PRAGMA EXCEPTION_INIT(e_table_exists, -00942); " + " BEGIN " + " EXECUTE IMMEDIATE ('DROP TABLE nodb_testdate'); " + " EXCEPTION " + " WHEN e_table_exists " + " THEN NULL; " + " END; " + " EXECUTE IMMEDIATE (' " + " CREATE TABLE nodb_testdate ( " + " timestampcol TIMESTAMP, " + " datecol DATE " + " )" + " '); " + "END; "; var date = new Date(); before(function(done){ oracledb.getConnection(credential, function(err, conn){ if(err) { console.error(err.message); return; } connection = conn; done(); }); }) after(function(done){ connection.release( function(err){ if(err) { console.error(err.message); return; } done(); }); }) it('3.5.1 inserts and query DATE and TIMESTAMP columns', function(done){ async.series([ function(callback){ // create table connection.execute( script, function(err){ should.not.exist(err); callback(); } ); }, function(callback){ // insert data connection.execute( "INSERT INTO nodb_testdate (timestampcol, datecol) VALUES (:ts, :td)", { ts: date, td: date }, { autoCommit: false }, function(err){ should.not.exist(err); callback(); } ); }, function(callback){ // select data connection.execute( "SELECT timestampcol, datecol FROM nodb_testdate", function(err, result){ should.not.exist(err); var ts = result.rows[0][0]; ts.setDate(ts.getDate() + 5); // console.log(ts); var d = result.rows[0][1]; d.setDate(d.getDate() - 5); // console.log(d); callback(); } ); }, function(callback){ connection.rollback( function(err){ should.not.exist(err); callback(); }); }, function(callback){ connection.execute( "DROP TABLE nodb_testdate", function(err){ should.not.exist(err); callback(); } ); } ], done); }) }) describe('3.6 rowlimit.js', function(){ var connection = false; var createTable = "BEGIN \ DECLARE \ e_table_exists EXCEPTION; \ PRAGMA EXCEPTION_INIT(e_table_exists, -00942); \ BEGIN \ EXECUTE IMMEDIATE ('DROP TABLE nodb_employees'); \ EXCEPTION \ WHEN e_table_exists \ THEN NULL; \ END; \ EXECUTE IMMEDIATE (' \ CREATE TABLE nodb_employees ( \ employees_id NUMBER, \ employees_name VARCHAR2(20) \ ) \ '); \ END; "; var insertRows = "DECLARE \ x NUMBER := 0; \ n VARCHAR2(20); \ BEGIN \ FOR i IN 1..107 LOOP \ x := x + 1; \ n := 'staff ' || x; \ INSERT INTO nodb_employees VALUES (x, n); \ END LOOP; \ END; "; before(function(done){ oracledb.getConnection(credential, function(err, conn){ if(err) { console.error(err.message); return; } connection = conn; connection.execute(createTable, function(err){ if(err) { console.error(err.message); return; } connection.execute(insertRows, function(err){ if(err) { console.error(err.message); return; } done(); }); }); }); }) after(function(done){ connection.execute( 'DROP TABLE nodb_employees', function(err){ if(err) { console.error(err.message); return; } connection.release( function(err){ if(err) { console.error(err.message); return; } done(); }); } ); }) it('3.6.1 by default, the number is 100', function(done){ var defaultLimit = oracledb.maxRows; defaultLimit.should.be.exactly(100); connection.should.be.ok; connection.execute( "SELECT * FROM nodb_employees", function(err, result){ should.not.exist(err); should.exist(result); // Return 100 records although the table has 107 rows. (result.rows).should.have.length(100); done(); } ); }) it('3.6.2 can also specify for each execution', function(done){ connection.should.be.ok; connection.execute( "SELECT * FROM nodb_employees", {}, {maxRows: 25}, function(err, result){ should.not.exist(err); should.exist(result); // Return 25 records according to execution setting (result.rows).should.have.length(25); done(); } ); }) }) describe('3.7 plsql.js', function(){ var connection = false; before(function(done){ oracledb.getConnection(credential, function(err, conn){ if(err) { console.error(err.message); return; } connection = conn; done(); }); }) after(function(done){ connection.release( function(err){ if(err) { console.error(err.message); return; } done(); }); }) it('3.7.1 can call PL/SQL procedure and binding parameters in various ways', function(done){ var proc = "CREATE OR REPLACE PROCEDURE nodb_testproc (p_in IN VARCHAR2, p_inout IN OUT VARCHAR2, p_out OUT NUMBER) \ AS \ BEGIN \ p_inout := p_in || p_inout; \ p_out := 101; \ END; "; var bindVars = { i: 'Chris', // bind type is determined from the data type io: { val: 'Jones', dir : oracledb.BIND_INOUT }, o: { type: oracledb.NUMBER, dir : oracledb.BIND_OUT } } async.series([ function(callback){ connection.execute( proc, function(err){ should.not.exist(err); callback(); } ); }, function(callback){ connection.execute( "BEGIN nodb_testproc(:i, :io, :o); END;", bindVars, function(err, result){ should.not.exist(err); (result.outBinds.o).should.be.exactly(101); (result.outBinds.io).should.equal('ChrisJones'); callback(); } ); }, function(callback){ connection.execute( "DROP PROCEDURE nodb_testproc", function(err, result){ should.not.exist(err); callback(); } ); } ], done); }) it('3.7.2 can call PL/SQL function', function(done) { var proc = "CREATE OR REPLACE FUNCTION nodb_testfunc (p1_in IN VARCHAR2, p2_in IN VARCHAR2) RETURN VARCHAR2 \ AS \ BEGIN \ return p1_in || p2_in; \ END; "; var bindVars = { p1: 'Chris', p2: 'Jones', ret: { dir: oracledb.BIND_OUT, type: oracledb.STRING, maxSize: 40 } }; async.series([ function(callback){ connection.execute( proc, function(err){ should.not.exist(err); callback(); } ); }, function(callback){ connection.execute( "BEGIN :ret := nodb_testfunc(:p1, :p2); END;", bindVars, function(err, result){ should.not.exist(err); // console.log(result); (result.outBinds.ret).should.equal('ChrisJones'); callback(); } ); }, function(callback){ connection.execute( "DROP FUNCTION nodb_testfunc", function(err, result){ should.not.exist(err); callback(); } ); } ], done); }) }) describe('3.8 insert1.js', function(){ var connection = false; var script = "BEGIN " + " DECLARE " + " e_table_exists EXCEPTION; " + " PRAGMA EXCEPTION_INIT(e_table_exists, -00942); " + " BEGIN " + " EXECUTE IMMEDIATE ('DROP TABLE nodb_testinsert'); " + " EXCEPTION " + " WHEN e_table_exists " + " THEN NULL; " + " END; " + " EXECUTE IMMEDIATE (' " + " CREATE TABLE nodb_testinsert ( " + " id NUMBER, " + " name VARCHAR2(20) " + " )" + " '); " + "END; "; before(function(done){ oracledb.getConnection(credential, function(err, conn){ if(err) { console.error(err.message); return; } connection = conn; done(); }); }) after(function(done){ connection.release( function(err){ if(err) { console.error(err.message); return; } done(); }); }) it('3.8.1 creates a table and inserts data', function(done){ async.series([ function(callback){ connection.execute( script, function(err){ should.not.exist(err); callback(); } ); }, function(callback){ connection.execute( "INSERT INTO nodb_testinsert VALUES (:id, :nm)", [1, 'Chris'], // Bind values function(err, result){ should.not.exist(err); (result.rowsAffected).should.be.exactly(1); callback(); } ); }, function(callback){ connection.execute( "INSERT INTO nodb_testinsert VALUES (:id, :nm)", [2, 'Alison'], // Bind values function(err, result){ should.not.exist(err); (result.rowsAffected).should.be.exactly(1); callback(); } ); }, function(callback){ connection.execute( "UPDATE nodb_testinsert SET name = 'Bambi'", function(err, result){ should.not.exist(err); (result.rowsAffected).should.be.exactly(2); callback(); } ); }, function(callback){ connection.execute( "DROP TABLE nodb_testinsert", function(err){ should.not.exist(err); callback(); } ); } ], done); }) }) describe('3.9 insert2.js', function(){ var conn1 = false; var conn2 = false; var script = "BEGIN " + " DECLARE " + " e_table_exists EXCEPTION; " + " PRAGMA EXCEPTION_INIT(e_table_exists, -00942); " + " BEGIN " + " EXECUTE IMMEDIATE ('DROP TABLE nodb_testcommit'); " + " EXCEPTION " + " WHEN e_table_exists " + " THEN NULL; " + " END; " + " EXECUTE IMMEDIATE (' " + " CREATE TABLE nodb_testcommit ( " + " id NUMBER, " + " name VARCHAR2(20) " + " )" + " '); " + "END; "; before(function(done){ oracledb.getConnection(credential, function(err, conn){ if(err) { console.error(err.message); return; } conn1 = conn; oracledb.getConnection(credential, function(err, conn){ if(err) { console.error(err.message); return; } conn2 = conn; done(); }); }); }) after(function(done){ conn1.release( function(err){ if(err) { console.error(err.message); return; } conn2.release( function(err){ if(err) { console.error(err.message); return; } done(); }); }); }) it('3.9.1 tests the auto commit behavior', function(done){ async.series([ function(callback){ conn1.execute( script, function(err){ should.not.exist(err); callback(); } ); }, function(callback){ conn1.execute( "INSERT INTO nodb_testcommit VALUES (:id, :nm)", [1, 'Chris'], // Bind values { autoCommit: true }, function(err, result){ should.not.exist(err); (result.rowsAffected).should.be.exactly(1); callback(); } ); }, function(callback){ conn1.execute( "INSERT INTO nodb_testcommit VALUES (:id, :nm)", [2, 'Alison'], // Bind values // { autoCommit: true }, function(err, result){ should.not.exist(err); (result.rowsAffected).should.be.exactly(1); callback(); } ); }, function(callback){ conn2.execute( "SELECT * FROM nodb_testcommit", function(err, result){ should.not.exist(err); // This will only show 'Chris' because inserting 'Alison' is not commited by default. // Uncomment the autoCommit option above and you will see both rows // console.log(result.rows); (result.rows).should.eql([ [ 1, 'Chris' ] ]); callback(); } ); }, function(callback){ conn1.execute( "DROP TABLE nodb_testcommit", function(err){ should.not.exist(err); callback(); } ); } ], done); }) }) describe('3.10 resultset.js', function() { var connection = false; var createTable = "BEGIN \ DECLARE \ e_table_exists EXCEPTION; \ PRAGMA EXCEPTION_INIT(e_table_exists, -00942); \ BEGIN \ EXECUTE IMMEDIATE ('DROP TABLE nodb_employees'); \ EXCEPTION \ WHEN e_table_exists \ THEN NULL; \ END; \ EXECUTE IMMEDIATE (' \ CREATE TABLE nodb_employees ( \ employees_id NUMBER, \ employees_name VARCHAR2(20) \ ) \ '); \ END; "; var insertRows = "DECLARE \ x NUMBER := 0; \ n VARCHAR2(20); \ BEGIN \ FOR i IN 1..207 LOOP \ x := x + 1; \ n := 'staff ' || x; \ INSERT INTO nodb_employees VALUES (x, n); \ END LOOP; \ END; "; before(function(done){ oracledb.getConnection(credential, function(err, conn){ if(err) { console.error(err.message); return; } connection = conn; connection.execute(createTable, function(err){ if(err) { console.error(err.message); return; } connection.execute(insertRows, function(err){ if(err) { console.error(err.message); return; } done(); }); }); }); }) after(function(done){ connection.execute( 'DROP TABLE nodb_employees', function(err){ if(err) { console.error(err.message); return; } connection.release( function(err){ if(err) { console.error(err.message); return; } done(); }); } ); }) it('3.10.1 resultset1.js - getRow() function', function(done) { connection.should.be.ok; var rowCount = 1; connection.execute( "SELECT employees_name FROM nodb_employees", [], { resultSet: true, prefetchRows: 50 }, function(err, result) { should.not.exist(err); (result.resultSet.metaData[0]).name.should.eql('EMPLOYEES_NAME'); fetchRowFromRS(connection, result.resultSet); } ); function fetchRowFromRS(connection, rs) { rs.getRow(function(err, row) { should.not.exist(err); if(row) { // console.log(row); row[0].should.be.exactly('staff ' + rowCount); rowCount++; return fetchRowFromRS(connection, rs); } else { rs.close(function(err) { should.not.exist(err); done(); }); } }); } }) it('3.10.2 resultset2.js - getRows() function', function(done) { connection.should.be.ok; var numRows = 10; // number of rows to return from each call to getRows() connection.execute( "SELECT * FROM nodb_employees", [], { resultSet: true, prefetchRows: 110 }, function(err, result) { should.not.exist(err); (result.resultSet.metaData[0]).name.should.eql('EMPLOYEES_ID'); (result.resultSet.metaData[1]).name.should.eql('EMPLOYEES_NAME'); fetchRowsFromRS(connection, result.resultSet); } ); function fetchRowsFromRS(conn, rs) { rs.getRows(numRows, function(err, rows) { should.not.exist(err); if(rows.length > 0) { //console.log("length of rows " + rows.length); //for(var i = 0; i < rows.length; i++) // console.log(rows[i]); return fetchRowsFromRS(conn, rs); } else { rs.close(function(err) { should.not.exist(err); done(); }); } }); } }) }) describe('3.11 refcursor.js', function() { var connection = false; var script = "BEGIN \ DECLARE \ e_table_exists EXCEPTION; \ PRAGMA EXCEPTION_INIT(e_table_exists, -00942); \ BEGIN \ EXECUTE IMMEDIATE ('DROP TABLE nodb_employees'); \ EXCEPTION \ WHEN e_table_exists \ THEN NULL; \ END; \ EXECUTE IMMEDIATE (' \ CREATE TABLE nodb_employees ( \ name VARCHAR2(40), \ salary NUMBER, \ hire_date DATE \ ) \ '); \ EXECUTE IMMEDIATE (' \ INSERT INTO nodb_employees \ (name, salary, hire_date) VALUES \ (''Steven'',24000, TO_DATE(''20030617'', ''yyyymmdd'')) \ '); \ EXECUTE IMMEDIATE (' \ INSERT INTO nodb_employees \ (name, salary, hire_date) VALUES \ (''Neena'',17000, TO_DATE(''20050921'', ''yyyymmdd'')) \ '); \ EXECUTE IMMEDIATE (' \ INSERT INTO nodb_employees \ (name, salary, hire_date) VALUES \ (''Lex'',17000, TO_DATE(''20010112'', ''yyyymmdd'')) \ '); \ EXECUTE IMMEDIATE (' \ INSERT INTO nodb_employees \ (name, salary, hire_date) VALUES \ (''Nancy'',12008, TO_DATE(''20020817'', ''yyyymmdd'')) \ '); \ EXECUTE IMMEDIATE (' \ INSERT INTO nodb_employees \ (name, salary, hire_date) VALUES \ (''Karen'',14000, TO_DATE(''20050104'', ''yyyymmdd'')) \ '); \ EXECUTE IMMEDIATE (' \ INSERT INTO nodb_employees \ (name, salary, hire_date) VALUES \ (''Peter'',9000, TO_DATE(''20100525'', ''yyyymmdd'')) \ '); \ END; "; var proc = "CREATE OR REPLACE PROCEDURE get_emp_rs (p_sal IN NUMBER, p_recordset OUT SYS_REFCURSOR) \ AS \ BEGIN \ OPEN p_recordset FOR \ SELECT * FROM nodb_employees \ WHERE salary > p_sal; \ END; "; before(function(done){ async.series([ function(callback) { oracledb.getConnection( credential, function(err, conn) { should.not.exist(err); connection = conn; callback(); } ); }, function(callback) { connection.execute( script, function(err) { should.not.exist(err); callback(); } ); }, function(callback) { connection.execute( proc, function(err) { should.not.exist(err); callback(); } ); } ], done); }) after(function(done){ connection.execute( 'DROP TABLE nodb_employees', function(err){ if(err) { console.error(err.message); return; } connection.release( function(err){ if(err) { console.error(err.message); return; } done(); }); } ); }) it('3.11.1 REF CURSOR', function(done) { connection.should.be.ok; var numRows = 100; // number of rows to return from each call to getRows() connection.execute( "BEGIN get_emp_rs(:sal, :cursor); END;", { sal: 12000, cursor: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT } }, function(err, result) { should.not.exist(err); result.outBinds.cursor.metaData[0].name.should.eql('NAME'); result.outBinds.cursor.metaData[1].name.should.eql('SALARY'); result.outBinds.cursor.metaData[2].name.should.eql('HIRE_DATE'); fetchRowsFromRS(result.outBinds.cursor); } ); function fetchRowsFromRS(resultSet) { resultSet.getRows( numRows, function(err, rows) { should.not.exist(err); if(rows.length > 0) { // console.log("fetchRowsFromRS(): Got " + rows.length + " rows"); // console.log(rows); rows.length.should.be.exactly(5); fetchRowsFromRS(resultSet); } else { resultSet.close( function(err) { should.not.exist(err); done(); }); } } ); } }) }) })
1.359375
1
backend/node_modules/@tensorflow/tfjs-layers/dist/engine/training_dataset.js
michael-fourie/DanceParty
1
303
/** * @license * Copyright 2018 Google LLC * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. * ============================================================================= */ /** * Interfaces and methods for training models using TensorFlow.js datasets. */ import * as tfc from '@tensorflow/tfjs-core'; import { scalar } from '@tensorflow/tfjs-core'; import { configureCallbacks, standardizeCallbacks } from '../base_callbacks'; import { NotImplementedError, ValueError } from '../errors'; import { disposeTensorsInLogs } from '../logs'; import { singletonOrArray, toList } from '../utils/generic_utils'; import { standardizeClassWeights, standardizeWeights } from './training_utils'; // Default batch size used during tensor-based validation. const DEFAULT_VALIDATION_BATCH_SIZE = 32; /** * Standardize the output of a dataset iterator for use by * LayersModel.fitDataset(). * * @param model: A `tf.LayersModel` object. * @param iteratorOut The output of a dataset iterator. It is required to be * an object of the form `{xs: TensorOrArrayOrMap, ys: * TensorOrArrayOrMap}`, where `TensorOrArrayOrMap` is a single `tf.Tensor`, * a `tf.Tensor[]`, or a flat map from string names to `tf.Tensor`s. * @returns A flat array of `tf.Tensor` objects: the input `tf.Tensor`s * followed by the target `tf.Tensor`s. When `tf.Tensor`s are provided * as a map, the order in the resulting array is taken from the `inputNames` * and `outputNames` of the model. */ function standardizeDataIteratorOutput( // Type `model` as `any` here to avoid circular dependency w/ // training.ts. // tslint:disable-next-line:no-any model, iteratorOut) { let xs; let ys; const iteratorOutObj = iteratorOut; xs = iteratorOutObj['xs']; ys = iteratorOutObj['ys']; tfc.util.assert(xs != null && ys != null, () => 'A Dataset iterator for fitDataset() is expected to generate ' + 'objects of the form `{xs: xVal, ys: yVal}`, where the two ' + 'values may be `tf.Tensor`, an array of Tensors, or a map of ' + 'string to Tensor. The provided Dataset instead generates ' + `${iteratorOut}`); const flattenedXs = flattenTensorOrArrayOrMap('input', model.inputNames, xs); const flattenedYs = flattenTensorOrArrayOrMap('output', model.outputNames, ys); const batchSize = flattenedXs[0].shape[0]; tfc.util.assert(flattenedXs.length === model.inputs.length, () => `LayersModel has ${model.inputs.length} inputs, but the dataset ` + `provides ${flattenedXs.length} inputs. (Expected input keys: ` + `${JSON.stringify(model.inputNames)})`); tfc.util.assert(flattenedYs.length === model.outputs.length, () => `LayersModel has ${model.outputs.length} outputs, but the dataset ` + `provides ${flattenedYs.length} outputs. (Expected output keys: ` + `${JSON.stringify(model.outputNames)})`); for (let xIndex = 0; xIndex < flattenedXs.length; xIndex++) { tfc.util.assert(flattenedXs[xIndex].shape[0] === batchSize, () => `Batch size mismatch: input ` + `${model.inputNames[xIndex]} has ${flattenedXs[xIndex].shape[0]}; ` + `expected ${batchSize} based on input ${model.inputNames[0]}.`); } for (let yIndex = 0; yIndex < flattenedYs.length; yIndex++) { tfc.util.assert(flattenedYs[yIndex].shape[0] === batchSize, () => `Batch size mismatch: output ` + `${model.outputNames[yIndex]} has ${flattenedYs[yIndex].shape[0]}; ` + `expected ${batchSize} based on input ${model.inputNames[0]}.`); } return { xs: flattenedXs, ys: flattenedYs }; } function flattenTensorOrArrayOrMap(inputOrOutput, names, values) { if (values instanceof tfc.Tensor) { return [values]; } else if (Array.isArray(values)) { tfc.util.assert(values.length === names.length, () => `Received an array of ${values.length} Tensors, but expected ${names.length} to match the ${inputOrOutput} keys ${names}.`); return values; } else { const result = []; // Check that all the required keys are available. for (const name of names) { if (values[name] == null) { throw new ValueError(`The feature data generated by the dataset lacks the required ` + `${inputOrOutput} key '${name}'.`); } result.push(values[name]); } return result; } } function standardizeTensorValidationData(data) { if (data.length === 3) { throw new NotImplementedError('Validation with sample weights is not implemented yet.'); } return { xs: data[0], ys: data[1] }; } export async function fitDataset( // Type `model` as `any` here to avoid circular dependency w/ // training.ts. // tslint:disable-next-line:no-any model, dataset, args) { const hasBatchesPerEpoch = args.batchesPerEpoch != null; tfc.util.assert(model.optimizer != null, () => 'You must compile a model before training/testing. Use ' + 'LayersModel.compile(modelCompileConfig).'); tfc.util.assert(args != null, () => `For fitDataset(), the 2nd argument (config) is required, ` + `but it is not provided in this call.`); tfc.util.assert(args.epochs != null && args.epochs > 0 && Number.isInteger(args.epochs), () => `For fitDataset(), config.epochs is expected to be a positive ` + `integer, but got ${args.epochs}`); tfc.util.assert(!hasBatchesPerEpoch || (args.batchesPerEpoch > 0 && Number.isInteger(args.batchesPerEpoch)), () => `For fitDataset(), config.batchesPerEpoch is expected to be a ` + `positive integer if specified, but got ${args.batchesPerEpoch}`); tfc.util.assert( // tslint:disable-next-line:no-any args['validationSplit'] == null, () => '`validationSplit` is not supported by `fitDataset()`. ' + 'Use validationData instead.'); if (model.isTraining) { throw new Error('Cannot start training because another fit() call is ongoing.'); } model.isTraining = true; try { const doValidation = args.validationData != null; let valXs; let valYs; if (doValidation) { if (isDatasetObject(args.validationData)) { tfc.util.assert(args.validationBatches == null || (args.validationBatches > 0 && Number.isInteger(args.validationBatches)), () => `For fitDataset() with dataset-based validation, ` + `config.validationBatches is expected not to be provided, ` + `or to be a positive integer, ` + `but got ${args.validationBatches}`); } else { const validationData = standardizeTensorValidationData(args.validationData); valXs = validationData.xs; valYs = validationData.ys; } } const trainFunction = model.makeTrainFunction(); const outLabels = model.getDedupedMetricsNames(); let callbackMetrics; if (doValidation) { callbackMetrics = outLabels.slice().concat(outLabels.map(n => 'val_' + n)); } else { callbackMetrics = outLabels.slice(); } const callbacks = standardizeCallbacks(args.callbacks, args.yieldEvery); const verbose = args.verbose == null ? 1 : args.verbose; const { callbackList, history } = configureCallbacks(callbacks, verbose, args.epochs, null, null, getStepsPerEpoch(dataset, args), null, // Batch size determined by the dataset itself. doValidation, callbackMetrics); callbackList.setModel(model); model.history = history; await callbackList.onTrainBegin(); model.stopTraining_ = false; let epoch = args.initialEpoch == null ? 0 : args.initialEpoch; let dataIterator = await dataset.iterator(); while (epoch < args.epochs) { const epochLogs = {}; await callbackList.onEpochBegin(epoch); let stepsDone = 0; let batchIndex = 0; if (!hasBatchesPerEpoch) { dataIterator = await dataset.iterator(); } while (hasBatchesPerEpoch ? stepsDone < args.batchesPerEpoch : true) { const iteratorOut = await dataIterator.next(); // If `batchesPerEpoch` is specified, the dataset should not be // exhausted until all epoches are done. if (hasBatchesPerEpoch && iteratorOut.done) { console.warn('You provided `batchesPerEpoch` as ' + `${args.batchesPerEpoch}, ` + 'but your dataset iterator ran out of data after ' + `${stepsDone} batches; ` + 'interrupting training. Make sure that your ' + 'dataset can generate at least `batchesPerEpoch * epochs` ' + 'batches (in this case, ' + `${args.batchesPerEpoch * args.epochs} batches). ` + 'You may need to use the repeat() function when building ' + 'your dataset.'); break; } if (iteratorOut.value != null) { const { xs, ys } = standardizeDataIteratorOutput(model, iteratorOut.value); const batchLogs = {}; batchLogs['batch'] = batchIndex; batchLogs['size'] = xs[0].shape[0]; await callbackList.onBatchBegin(batchIndex, batchLogs); const sampleWeights = []; if (args.classWeight != null) { const standardClassWeights = standardizeClassWeights(args.classWeight, model.outputNames); for (let i = 0; i < standardClassWeights.length; ++i) { sampleWeights.push(await standardizeWeights(ys[i], null, standardClassWeights[i])); } } // Train on batch. const ins = xs.concat(ys).concat(sampleWeights); const outs = trainFunction(ins); tfc.dispose(ins); for (let i = 0; i < outLabels.length; ++i) { const label = outLabels[i]; const out = outs[i]; batchLogs[label] = out; tfc.keep(out); } await callbackList.onBatchEnd(batchIndex, batchLogs); disposeTensorsInLogs(batchLogs); batchIndex++; stepsDone++; } if (hasBatchesPerEpoch ? stepsDone >= args.batchesPerEpoch : iteratorOut.done) { // Epoch finished. Perform validation. if (doValidation) { let valOuts; if (isDatasetObject(args.validationData)) { valOuts = toList(await model.evaluateDataset(args.validationData, { batches: args.validationBatches })); } else { valOuts = toList(model.evaluate(valXs, valYs, { batchSize: args.validationBatchSize == null ? DEFAULT_VALIDATION_BATCH_SIZE : args.validationBatchSize, verbose: 0 })); } for (let i = 0; i < model.metricsNames.length; ++i) { epochLogs[`val_${model.metricsNames[i]}`] = valOuts[i]; } } // Call `break` to exit one epoch lopp after validation is done. If // config.batchesPerEpoch is specified, an epoch while loop will // stop when `stepsDone >= config.batchesPerEpoch`. When // config.batchesPerEpoch is not provided, the following `break` is // required to exit the while lopp after dataset is exhausted. break; } if (model.stopTraining_) { break; } } await callbackList.onEpochEnd(epoch, epochLogs); epoch++; if (model.stopTraining_) { break; } } await callbackList.onTrainEnd(); await model.history.syncData(); return model.history; } finally { model.isTraining = false; } } /** Helper function that determines number of steps (batches) per epoch. */ function getStepsPerEpoch(dataset, args) { // Attempt to determine # of batches in an epoch. let stepsPerEpoch = null; if (args.batchesPerEpoch != null) { stepsPerEpoch = args.batchesPerEpoch; } else if (Number.isFinite(dataset.size)) { stepsPerEpoch = dataset.size; } return stepsPerEpoch; } // Check if provided object is a Dataset object by checking its .iterator // element. function isDatasetObject(dataset) { return (typeof dataset.iterator === 'function'); } // Check if provided object is a LazyIterator object by checking it's .next // element. function isLazyIteratorObject(iterator) { return (typeof iterator.next === 'function'); } export async function evaluateDataset( // Type `model` as `any` here to avoid circular dependency w/ // training.ts. // tslint:disable-next-line:no-any model, dataset, args) { args = args || {}; const hasBatches = args.batches != null; const f = model.testFunction; let outs = []; if (args.verbose > 0) { throw new NotImplementedError('Verbose mode is not implemented yet.'); } tfc.util.assert(!hasBatches || (args.batches > 0 && Number.isInteger(args.batches)), () => 'Test loop expects `batches` to be a positive integer, but ' + `received ${JSON.stringify(args.batches)}`); const dataIterator = isLazyIteratorObject(dataset) ? dataset : await dataset.iterator(); // Keeps track of number of examples used in this evaluation. let numExamples = 0; let batch = 0; while (hasBatches ? batch < args.batches : true) { const iteratorOut = await dataIterator.next(); outs = tfc.tidy(() => { if (iteratorOut.value) { // TODO(cais): Once real dataset is available, use // `map(x => standardizeDataIteratorOutput(model, x).map(f)`. const { xs, ys } = standardizeDataIteratorOutput(model, iteratorOut.value); const xsAndYs = xs.concat(ys); const batchOuts = tfc.tidy(() => f(xsAndYs)); tfc.dispose(xsAndYs); if (batch === 0) { for (let i = 0; i < batchOuts.length; ++i) { outs.push(scalar(0)); } } const batchSize = xsAndYs[0].shape[0]; for (let i = 0; i < batchOuts.length; ++i) { const batchOut = batchOuts[i]; const oldScalar = outs[i]; outs[i] = tfc.tidy(() => tfc.add(outs[i], tfc.mul(batchSize, batchOut))); if (batch > 0) { tfc.dispose(oldScalar); } } tfc.dispose(batchOuts); numExamples += batchSize; ++batch; } return outs; }); if (iteratorOut.done) { if (hasBatches) { console.warn('Your dataset iterator ran out of data during evaluateDataset(). ' + 'Interrupting evalution. Make sure that your ' + 'dataset can generate at least `batches` ' + `batches (in this case, ${args.batches} batches). ` + 'You may need to use the repeat() function when building ' + 'your dataset.'); } break; } } for (let i = 0; i < outs.length; ++i) { const oldScalar = outs[i]; outs[i] = tfc.div(outs[i], numExamples); tfc.dispose(oldScalar); } return singletonOrArray(outs); } //# sourceMappingURL=training_dataset.js.map
1.765625
2
assets/scripts/dropdown.js
rustyb/phr-design-system
8
311
'use strict'; import React from 'react'; import TetherComponent from 'react-tether'; import ReactCSSTransitionGroup from 'react-addons-css-transition-group'; const Dropdown = React.createClass({ displayName: 'Dropdown', propTypes: { triggerElement: React.PropTypes.oneOf(['a', 'button']), triggerClassName: React.PropTypes.string, triggerActiveClassName: React.PropTypes.string, triggerTitle: React.PropTypes.string, triggerText: React.PropTypes.string.isRequired, direction: React.PropTypes.oneOf(['up', 'down', 'left', 'right']), alignment: React.PropTypes.oneOf(['left', 'center', 'right', 'middle']), className: React.PropTypes.string, children: React.PropTypes.node }, _bodyListener: function (e) { // Get the dropdown that is a parent of the clicked element. If any. let theSelf = e.target; if (theSelf.tagName === 'BODY' || theSelf.tagName === 'HTML' || e.target.getAttribute('data-hook') === 'dropdown:close') { this.close(); return; } // If the trigger element is an "a" the target is the "span", but it is a // button, the target is the "button" itself. // This code handles this case. No idea why this is happening. // TODO: Unveil whatever black magic is at work here. if (theSelf.tagName === 'SPAN' && theSelf.parentNode === this.refs.trigger && theSelf.parentNode.getAttribute('data-hook') === 'dropdown:btn') { return; } if (theSelf && theSelf.getAttribute('data-hook') === 'dropdown:btn') { if (theSelf !== this.refs.trigger) { this.close(); } return; } do { if (theSelf && theSelf.getAttribute('data-hook') === 'dropdown:content') { break; } theSelf = theSelf.parentNode; } while (theSelf && theSelf.tagName !== 'BODY' && theSelf.tagName !== 'HTML'); if (theSelf !== this.refs.dropdown) { this.close(); } }, getDefaultProps: function () { return { triggerElement: 'button', direction: 'down', alignment: 'center' }; }, getInitialState: function () { return { open: false }; }, // Lifecycle method. // Called once as soon as the component has a DOM representation. componentDidMount: function () { window.addEventListener('click', this._bodyListener); }, // Lifecycle method. // Called once as soon as the component has a DOM representation. componentWillUnmount: function () { window.removeEventListener('click', this._bodyListener); }, _toggleDropdown: function (e) { e.preventDefault(); this.toggle(); }, toggle: function () { this.setState({ open: !this.state.open }); }, open: function () { this.setState({ open: true }); }, close: function () { this.setState({ open: false }); }, render: function () { // Base and additional classes for the trigger and the content. var klasses = ['drop__content', 'drop__content--react', `drop-trans--${this.props.direction}`]; var triggerKlasses = ['drop__toggle']; if (this.props.className) { klasses.push(this.props.className); } if (this.props.triggerClassName) { triggerKlasses.push(this.props.triggerClassName); } // Additional trigger props. var triggerProps = {}; if (this.props.triggerElement === 'button') { triggerProps.type = 'button'; } else { triggerProps.href = '#'; } if (this.props.triggerTitle) { triggerProps.title = this.props.triggerTitle; } let tetherAttachment; let tetherTargetAttachment; switch (this.props.direction) { case 'up': tetherAttachment = `bottom ${this.props.alignment}`; tetherTargetAttachment = `top ${this.props.alignment}`; break; case 'down': tetherAttachment = `top ${this.props.alignment}`; tetherTargetAttachment = `bottom ${this.props.alignment}`; break; case 'left': tetherAttachment = `${this.props.alignment} left`; tetherTargetAttachment = `${this.props.alignment} right`; break; case 'right': tetherAttachment = `${this.props.alignment} right`; tetherTargetAttachment = `${this.props.alignment} left`; break; } if (this.state.open && this.props.triggerActiveClassName) { triggerKlasses.push(this.props.triggerActiveClassName); } return ( <TetherComponent attachment={tetherAttachment} targetAttachment={tetherTargetAttachment} constraints={[{ to: 'scrollParent', attachment: 'together' }]}> <this.props.triggerElement {...triggerProps} className={triggerKlasses.join(' ')} onClick={this._toggleDropdown} data-hook='dropdown:btn' ref='trigger' > <span>{ this.props.triggerText }</span> </this.props.triggerElement> <ReactCSSTransitionGroup component='div' transitionName='drop-trans' transitionEnterTimeout={300} transitionLeaveTimeout={300} > { this.state.open ? <div className={klasses.join(' ')} ref='dropdown' data-hook='dropdown:content'>{ this.props.children }</div> : null } </ReactCSSTransitionGroup> </TetherComponent> ); } }); module.exports = Dropdown;
1.515625
2
appendixa/modules/babel/shipping.js
zy31415/angular2typescript
504
319
export function ship() { console.log("Shipping products..."); } function calculateShippingCost(){ console.log("Calculating shipping cost"); }
0.890625
1
tests/conditionals/index.test.js
jabzzy/pug-to-jsx
0
327
const { resolve } = require('path'); const { readFile } = require('fs/promises'); const { convert } = require('../../index'); describe('conditionals / https://pugjs.org/language/conditionals.html', () => { test.each([ ['conditionals'], ['unless'], ])('%s', async (path) => { path = resolve(__dirname, path); const actual = convert([`${path}.pug`])[`${path}.pug`]; const expected = await readFile(`${path}.jsx`, { encoding: 'utf-8' }); expect(actual).toBe(expected.replace(/\n$/, '')); }); });
1.1875
1
extern/tbb-2019-u4/html/a00941.js
robgrzel/OpenCV_Examples
0
335
var a00941 = [ [ "Policy", "a00593.html", null ], [ "has_policy", "a00315.html", null ], [ "has_policy< ExpectedPolicy, FirstPolicy, Policies... >", "a00317.html", null ], [ "has_policy< ExpectedPolicy, SinglePolicy >", "a00321.html", null ], [ "has_policy< ExpectedPolicy, Policy< Policies... > >", "a00319.html", null ], [ "rejecting", "a00650.html", null ], [ "reserving", "a00656.html", null ], [ "queueing", "a00614.html", null ], [ "lightweight", "a00473.html", null ], [ "key_matching", "a00458.html", "a00458" ], [ "source_body", "a00712.html", "a00712" ], [ "source_body_leaf", "a00715.html", "a00715" ], [ "function_body", "a00279.html", "a00279" ], [ "function_body_leaf", "a00281.html", "a00281" ], [ "function_body_leaf< continue_msg, continue_msg, B >", "a00284.html", "a00284" ], [ "function_body_leaf< Input, continue_msg, B >", "a00288.html", "a00288" ], [ "function_body_leaf< continue_msg, Output, B >", "a00286.html", "a00286" ], [ "multifunction_body", "a00503.html", "a00503" ], [ "multifunction_body_leaf", "a00505.html", "a00505" ], [ "type_to_key_function_body", "a00841.html", "a00841" ], [ "type_to_key_function_body< Input, Output & >", "a00842.html", "a00842" ], [ "type_to_key_function_body_leaf", "a00845.html", "a00845" ], [ "type_to_key_function_body_leaf< Input, Output &, B >", "a00847.html", "a00847" ], [ "forward_task_bypass", "a00275.html", "a00275" ], [ "apply_body_task_bypass", "a00058.html", "a00058" ], [ "source_task_bypass", "a00718.html", "a00718" ], [ "empty_body", "a00240.html", "a00240" ], [ "decrementer", "a00196.html", "a00196" ], [ "__TBB__flow_graph_body_impl_H", "a00995.html#ab9d2ba83d8960680e772da17421d553f", null ], [ "queueing_lightweight", "a00941.html#ac59383a052dfc3ac6d1801b9e47342b1", null ], [ "rejecting_lightweight", "a00941.html#a9a827fec92e29177d19e357ca29dde3a", null ], [ "tag_matching", "a00941.html#a07bb0317f784a7989fc6523595630a1c", null ], [ "tag_value", "a00941.html#aa121a64d655ae5f0fea92a986bfad35e", null ] ];
0.304688
0
public/js/general.js
emporehezertama/emhr-datang
0
343
// init price_format(); jQuery('.datepicker').datepicker({ dateFormat: 'yy/mm/dd', changeMonth: true, changeYear: true }); $('#data_table_no_copy').DataTable({ dom: 'Bfrtip', buttons: [] }); $('#data_table_no_copy2').DataTable({ dom: 'Bfrtip', buttons: [] }); $('#data_table_no_copy3').DataTable({ dom: 'Bfrtip', buttons: [] }); $('#data_table').DataTable({ dom: 'Bfrtip', buttons: [ 'copy', 'csv', 'excel', 'pdf', 'print' ], pageLength: 100 }); $('#data_table2').DataTable({ dom: 'Bfrtip', buttons: [ 'copy', 'csv', 'excel', 'pdf', 'print' ] }); $('#data_table2_no_search').DataTable({ dom: 'Bfrtip', searching: false, pageLength: 30, buttons: [ ] }); $('#data_table3').DataTable({ dom: 'Bfrtip', buttons: [ 'copy', 'csv', 'excel', 'pdf', 'print' ] }); $('.data_table').each(function(){ $(this).DataTable({ dom: 'Bfrtip', searching: false, pageLength: 30, bPaginate: false, bInfo: false, buttons: [ ] }); }); /** * [numberWithComma description] * @param {[type]} x [description] * @return {[type]} [description] */ function numberWithComma(x) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); } function numberWithDot(x) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, "."); } function price_format() { $('.price_format').priceFormat({ prefix: '', centsSeparator: '.', thousandsSeparator: '.', clearOnEmpty: true, centsLimit : 0 }); } $("#data_table_no_search").DataTable({ dom: 'Bfrtip', searching: false, pageLength: 30, buttons: [ ] }); $("#data_table_no_pagging").DataTable({ dom: 'Bfrtip', searching: false, pageLength: 30, bPaginate: false, bInfo: false, buttons: [ ] }); $(".data_table_no_pagging").each(function(){ $(this).DataTable({ dom: 'Bfrtip', searching: false, pageLength: 30, bPaginate: false, bInfo: false, buttons: [ ] }); }); function _confirm(msg, url) { if(msg == "") return false; bootbox.confirm({ title : "<i class=\"fa fa-warning\"></i> EMPORE SYSTEM", message: msg, closeButton: false, backdrop: true, buttons: { confirm: { label: '<i class="fa fa-trash"></i> Yes', className: 'btn btn-sm btn-danger' }, cancel: { label: '<i class="fa fa-close"></i> No', className: 'btn btn-sm btn-default btn-outline' } }, callback: function (result) { if(result) { document.location = url; } } }); return false; } function _confirm_submit(msg, form) { if(msg == "") return false; bootbox.confirm({ title : "<i class=\"fa fa-warning\"></i> EMPORE SYSTEM", message: msg, closeButton: false, backdrop: true, buttons: { confirm: { label: '<i class="fa fa-check"></i> Yes', className: 'btn btn-sm btn-success' }, cancel: { label: '<i class="fa fa-close"></i> No', className: 'btn btn-sm btn-default btn-outline' } }, callback: function (result) { if(result) { form.trigger('submit'); } } }); return false; } /** * [alert_ description] * @param {[type]} msg [description] * @return {[type]} [description] */ function _alert(msg) { if(msg == "") return false; bootbox.alert({ title : "<i class=\"fa fa-check-square text-success\"></i> EMPORE SYSTEM", closeButton: false, message: msg, backdrop: true, buttons: { ok: { label: 'OK', className: 'btn btn-sm btn-success' }, }, }) } function _alert_error(msg) { if(msg == "") return false; bootbox.alert({ title : "<i class=\"fa fa-exclamation-triangle text-danger\"></i> EMPORE SYSTEM", closeButton: false, message: msg, backdrop: true, buttons: { ok: { label: 'OK', className: 'btn btn-sm btn-success' }, }, }) } /** * [_confirm description] * @param {[type]} msg [description] * @return {[type]} [description] */ function confirm_delete(msg, el) { if(msg == "") return false; bootbox.confirm({ title : "<i class=\"fa fa-warning\"></i> EMPORE SYSTEM", message: msg, closeButton: false, backdrop: true, buttons: { confirm: { label: 'Yes', className: 'btn btn-sm btn-success' }, cancel: { label: 'No', className: 'btn btn-sm btn-danger' } }, callback: function (result) { if(result) { $(el).parent().submit(); } } }); return false; }
1.085938
1
javascript/linkedlists/linked-list/__test__/linked-list.test.js
tiftaylor/data-structures-and-algorithms
0
351
const file = require('../linked-list.js'); // tests for CC05 describe('Testing linked list file methods', () => { test('can make empty list', () => { const list = new file.LinkedList(); expect(list.head).toBe(null); }) test('insert node in front of list', () => { const one = new file.Node(1, null); const list = new file.LinkedList(one); list.insert(2); expect(list.head.next.value).toBe(1); }) test('head points to first node in list', () => { const one = new file.Node(1, null); const list = new file.LinkedList(one); list.insert(2); expect(list.head.value).toBe(2); }) test('True when finding a value in list', () => { const one = new file.Node(1, null); const list = new file.LinkedList(one); expect(list.includes(1)).toBeTruthy(); }) test('False when value is not in list', () => { const one = new file.Node(1, null); const list = new file.LinkedList(one); expect(list.includes(7)).toBeFalsy(); }) test('returns string of all values in list', () => { const one = new file.Node(1, null); const list = new file.LinkedList(one); const testItem = list.toString(); expect(testItem).toBe('{ 1 } -> NULL'); }) }) // tests for CC06 describe('Testing cc06 methods', () => { test('append one node at end', () => { const one = new file.Node(1, null); const list = new file.LinkedList(one); list.append(2); expect(one.next).not.toBe(null); expect(one.next.value).toBe(2); expect(one.next.next).toBe(null); }) test('append multiple nodes at end', () => { const one = new file.Node(1, null); const list = new file.LinkedList(one); list.append(2); list.append(3); list.append(4); expect(one.next.value).toBe(2); expect(one.next.next.value).toBe(3); expect(one.next.next.next.value).toBe(4); }) test('insert node BEFORE middle of list', () => { const list = new file.LinkedList(); list.insert(3); list.insert(2); list.insert(1); list.insertBefore(2,4); expect(list.head.next.value).toBe(4); expect(list.head.next.next.value).toBe(2); }) test('insert node BEFORE the first node of list', () => { const list = new file.LinkedList(); list.insert(2); list.insert(1); list.insertBefore(1,3); expect(list.head.value).toBe(3); expect(list.head.next.value).toBe(1); }) test('insert AFTER a middle node', () => { const list = new file.LinkedList(); list.insert(3); list.insert(2); list.insert(1); list.insertAfter(2,4); expect(list.head.next.next.value).toBe(4); expect(list.head.next.next.next.value).toBe(3); }) test('insert AFTER last node', () => { const list = new file.LinkedList(); list.insert(2); list.insert(1); list.insertAfter(2,3); expect(list.head.next.next.value).toBe(3); expect(list.head.next.next.next).toBe(null); }) }) // Tests for CC07 describe('Testing cc07 methods', () => { test('when k is longer than the list', () => { k = 3; const list = new file.LinkedList(); list.insert(2); list.insert(1); expect(() => { list.kthFromEnd(k); }).toThrow('There are not that many nodes'); }) test('when k and length of list are same', () => { k = 3; const list = new file.LinkedList(); list.insert(3); list.insert(2); list.insert(1); expect(() => { list.kthFromEnd(k); }).toThrow('There are not that many nodes'); }) test('when k is a negative int', () => { k = -1; const list = new file.LinkedList(); list.insert(2); list.insert(1); expect(() => { list.kthFromEnd(k); }).toThrow('k cannot be negative'); }) test('when the list is 1 and k is 0', () => { k = 0; const list = new file.LinkedList(); list.insert(1); expect(list.kthFromEnd(k)).toEqual(1); }) test('when k is an int that lands somewhere in the middle', () => { k = 2; const list = new file.LinkedList(); list.insert(5); list.insert(4); list.insert(3); list.insert(2); list.insert(1); expect(list.kthFromEnd(k)).toEqual(3); }) })
2.015625
2
packages/data/.eslintrc.js
sparkmeter/data
0
359
module.exports = { extends: ['eslint-config-salesforce-typescript', 'eslint-config-salesforce-license'], };
0.171875
0
src/components/Nav/Navbar.js
arsmth/gatsby-responsive-nav
10
367
import React, { PureComponent } from 'react' import { StaticQuery, graphql } from 'gatsby' import styled, { css } from 'styled-components' import { Link } from 'gatsby' import rem from '../../utils/rem' import { navbarHeight } from '../../utils/sizes' import { mobile } from '../../utils/media' import NavLinks from './NavLinks' import Social from './Social' import MobileNavbar from './MobileNavbar' const Wrapper = styled.nav` position: fixed; left: 0; box-sizing: border-box; z-index: 3; width: 100%; height: ${rem(navbarHeight)}; font-size: ${rem(15)}; font-weight: 500; background: tomato; transition: background 300ms ease-out; color: white; a { text-decoration: none; } ` const NormalNavbar = styled.div` display: flex; align-items: center; justify-content: space-between; padding: 0 ${rem(20)}; ${mobile(css` display: none; `)} ` const StartWrapper = styled.div` display: flex; align-items: center; justify-content: flex-start; ` const EndWrapper = styled.div` display: flex; align-items: center; justify-content: flex-end; ` const LogoLink = styled(Link).attrs({ to: '/', 'aria-label': 'home', })` display: inline-block; vertical-align: center; margin-right: ${rem(35)}; color: currentColor; ` class NavBar extends PureComponent { render() { const { onMobileNavToggle, isMobileNavFolded, } = this.props return ( <StaticQuery query={graphql` query { site { siteMetadata { title } } } `} render={data => ( <Wrapper> <NormalNavbar> <StartWrapper> <LogoLink> <p>{data.site.siteMetadata.title}</p> </LogoLink> <NavLinks /> </StartWrapper> <EndWrapper> <Social /> </EndWrapper> </NormalNavbar> <MobileNavbar isMobileNavFolded={isMobileNavFolded} onMobileNavToggle={onMobileNavToggle} /> </Wrapper> )} /> ) } } export default NavBar
1.523438
2
js/rank_manager.js
JunhuaLin/NAS2048
0
375
/** * Created by junhua on 18-5-13. */ const REFRESH_TIME = 60 * 1000; function RankManager(score_dao) { var self = this; this.scoreDao = score_dao; this.rankTable = document.querySelector(".rank-table"); self.daUpdateRankData([]); self.updateRankData(); window.setInterval(function () { self.updateRankData(); }, REFRESH_TIME); } RankManager.prototype.daUpdateRankData = function (rankList) { if (!rankList) { rankList = []; } var self = this; for (var rowIndex = 1; rowIndex < self.rankTable.rows.length; rowIndex++) { var row = self.rankTable.rows[rowIndex]; row.cells[0].innerHTML = rowIndex + ""; var scoreObj = null; if (rowIndex - 1 < rankList.length) { scoreObj = rankList[rowIndex - 1]; } console.log("daUpdateRankData:" + scoreObj); if (scoreObj) { var username = scoreObj.name; var index = username.lastIndexOf('@'); if (index > 0) { username = username.substring(0, index); } row.cells[1].innerHTML = username; row.cells[2].innerHTML = scoreObj.score; } else { row.cells[1].innerHTML = "--"; row.cells[2].innerHTML = "--"; } } }; RankManager.prototype.updateRankData = function () { var self = this; this.scoreDao.getRank(function (rankList) { self.daUpdateRankData(rankList); }); }; RankManager.prototype.mockData = function () { var data = []; for (var i = 0; i < 9; i++) { data[i] = { name: "junhua" + i + "@" + i, score: 666 - i }; } return data; };
2.0625
2
tests/functionality/middleware/styles/postprocessor.js
riu-web/odom
45
383
import { createComponent } from "/src/main.js"; import logResult from "/tests/functionality/log-result.js"; const postprocessor = async () => { const markup = /* html */`<div></div>`; const styles = /* css */` :scope { width: 500px; } `; const _postprocessor = async (css) => css.replace("width", "height"); const _styles = { postprocessor: _postprocessor }; const middleware = { styles: _styles }; const options = { markup, styles, middleware }; const Postprocessor = await createComponent(options); document.body.appendChild(Postprocessor.scope); const passed = getComputedStyle(Postprocessor.scope).getPropertyValue("height") === "500px"; logResult(passed); return Postprocessor; }; export default postprocessor;
1.398438
1
src/components/ionSideMenuContainer.js
RafalSladek/reactionic
570
391
import React from 'react'; import Snap from 'snapjs'; var IonSideMenuContainer = React.createClass({ contextTypes: { ionSetSnapper: React.PropTypes.func }, propTypes: { settings: React.PropTypes.object, }, getDefaultProps: function() { return { settings: {}, }; }, componentDidMount: function() { var sideMenuContent = document.getElementById('IonSideMenuContent'); let snapper = new Snap({ element: sideMenuContent, ...this.props.settings, }); if (typeof snapper.toggle === 'undefined') { // add a toggle method if it doesn't exist yet (in some future version) snapper.toggle = function(direction) { if( this.state().state==direction ){ this.close(); } else { this.open(direction); } }; } this.context.ionSetSnapper(snapper); }, componentWillUnmount: function() { this.context.ionSetSnapper(null); }, render() { return ( <div> { this.props.children } </div> ); } }); export default IonSideMenuContainer;
1.445313
1
src/actions/RightPaneActions.js
dxiuu/AntAlmanac
25
399
import dispatcher from '../dispatcher'; import AppStore from '../stores/RightPaneStore'; import ReactGA from 'react-ga'; export const updateFormValue = (field, value) => { const formData = { ...AppStore.getFormData(), [field]: value }; dispatcher.dispatch({ type: 'UPDATE_FORM_FIELD', formData, }); }; export const resetFormValues = () => { dispatcher.dispatch({ type: 'RESET_FORM_FIELDS', }); }; export const handleTabChange = (event, value) => { switch ( value // 0 is Class Search Tab, 1 is Added Classes Tab, 2 is Map Tab ) { case 1: ReactGA.event({ category: 'antalmanac-rewrite', action: `Switch tab to Added Classes`, }); break; case 2: ReactGA.event({ category: 'antalmanac-rewrite', action: `Switch tab to Map`, }); break; default: // do nothing } dispatcher.dispatch({ type: 'TAB_CHANGE', activeTab: value, }); };
1.140625
1
packages/expo-local-authentication/build/LocalAuthentication.js
tai8292/expo
2
407
import { UnavailabilityError } from '@unimodules/core'; import invariant from 'invariant'; import { Platform } from 'react-native'; import ExpoLocalAuthentication from './ExpoLocalAuthentication'; import { AuthenticationType } from './LocalAuthentication.types'; export { AuthenticationType }; export async function hasHardwareAsync() { if (!ExpoLocalAuthentication.hasHardwareAsync) { throw new UnavailabilityError('expo-local-authentication', 'hasHardwareAsync'); } return await ExpoLocalAuthentication.hasHardwareAsync(); } export async function supportedAuthenticationTypesAsync() { if (!ExpoLocalAuthentication.supportedAuthenticationTypesAsync) { throw new UnavailabilityError('expo-local-authentication', 'supportedAuthenticationTypesAsync'); } return await ExpoLocalAuthentication.supportedAuthenticationTypesAsync(); } export async function isEnrolledAsync() { if (!ExpoLocalAuthentication.isEnrolledAsync) { throw new UnavailabilityError('expo-local-authentication', 'isEnrolledAsync'); } return await ExpoLocalAuthentication.isEnrolledAsync(); } export async function authenticateAsync(promptMessageIOS = 'Authenticate') { if (!ExpoLocalAuthentication.authenticateAsync) { throw new UnavailabilityError('expo-local-authentication', 'authenticateAsync'); } if (Platform.OS === 'ios') { invariant(typeof promptMessageIOS === 'string' && promptMessageIOS.length, 'Fingerprint.authenticateAsync must be called with a non-empty string on iOS'); const result = await ExpoLocalAuthentication.authenticateAsync(promptMessageIOS); if (result.warning) { console.warn(result.warning); } return result; } else { return await ExpoLocalAuthentication.authenticateAsync(); } } export async function cancelAuthenticate() { if (!ExpoLocalAuthentication.cancelAuthenticate) { throw new UnavailabilityError('expo-local-authentication', 'cancelAuthenticate'); } await ExpoLocalAuthentication.cancelAuthenticate(); } //# sourceMappingURL=LocalAuthentication.js.map
1.265625
1
src/components/organisms/dot/dot.stories.js
jh3y/open-banking-reference-app
25
415
import React from 'react' import 'storybook/index.css' import { withKnobs, boolean } from '@storybook/addon-knobs' import Dot from './index' import StoryPage, { DocText, Description, DocItem } from 'storybook/story-components' export default { component: Dot, title: 'Organisms/Dot', decorators: [ withKnobs, storyFn => ( <StoryPage title="Pin" url="components/organisms/dot"> <Description> <DocText>An Indicator to display how many pin numbers have been entered</DocText> </Description> {storyFn()} </StoryPage> ) ] } export const withActive = () => { return ( <DocItem example={{ render: () => <Dot index={0} active={boolean('Active', false)} /> }} /> ) }
1.453125
1
src/modules/spoc-crm-web/src/libs/crmReferral.js
wunike/iview-admin-metis
0
423
import { http, httpCrmBlob } from "./request"; const k = '/crmReferral' const post = (u, data) => { return http.post(`${k}${u}`, data); }; const get = (u, data) => { return http.get(`${k}${u}`, data); }; export const crmReferral = { listReferralPage(params) { return post('/listReferralPage', params) }, listCreatersPage(params) { return post('/listCreatersPage', params) }, getShowTitle(params) { return get('/getShowTitle', { params }) }, clearShowField(params) { return get('/clearShowField', { params }) }, updateShowTitle(pageIdentifier ,params){ return post('/updateShowTitle?pageIdentifier=' + pageIdentifier, params); }, audit(params) { return get('/audit', { params }) }, reward(params) { return get('/reward', { params }) }, //转中心导出 crmReferralExport(params) { return httpCrmBlob.post(`${k}/export`, params) }, }
0.90625
1
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
0
Edit dataset card