text
stringlengths 7
3.69M
|
|---|
function runTest()
{
FBTest.openNewTab(basePath + "css/nestedRules/atMediaStyleEditing.html", function(win)
{
FBTest.openFirebug(function()
{
var panel = FBTest.selectPanel("stylesheet");
FBTest.selectPanelLocationByName(panel, "atMediaStyleEditing.html");
// Check the number of displayed style rules
var styleRules = panel.panelNode.querySelectorAll(".cssRule:not(.cssMediaRule)");
FBTest.compare(3, styleRules.length, "Three style rules must be shown");
// Check the number of displayed @media rules
var atMediaRuleCount = 0;
var allMediaRule = null;
for (var i=0, len = styleRules.length; i<len; ++i)
{
var atMediaRule = FW.FBL.getAncestorByClass(styleRules[i], "cssMediaRule");
if (atMediaRule)
{
atMediaRuleCount++;
if (atMediaRule.getElementsByClassName("cssMediaRuleCondition").item(0).
textContent == "all")
{
allMediaRule = atMediaRule;
}
}
}
FBTest.compare(2, atMediaRuleCount, "Two @media rules must be shown");
// Try manipulating the properties inside the '@media all' rule
if (FBTest.ok(allMediaRule, "One of the rules must have a 'all' media type"))
{
var propValue = allMediaRule.getElementsByClassName("cssPropValue").item(0);
// Click the value of the 'background-image' property inside the '#element' rule
FBTest.synthesizeMouse(propValue);
var editor = panel.panelNode.getElementsByClassName("textEditorInner").item(0);
if (FBTest.ok(editor, "Editor must be available now"))
{
// Enter '-moz-linear-gradient(135deg, #FF788C, #FFB4C8)' and verify display
FBTest.sendString("-moz-linear-gradient(135deg, #FF8C78, #FFC8B4)", editor);
var element = win.document.getElementById("element");
var csElement = win.getComputedStyle(element);
// Wait a bit until the new style gets applied
setTimeout(function()
{
FBTest.compare(
"-moz-linear-gradient(135deg, rgb(255, 140, 120), rgb(255, 200, 180))",
csElement.backgroundImage, "Element display must be correct");
// Click outside the CSS property value to stop inline editing
FBTest.synthesizeMouse(panel.panelNode, 300, 0);
var prop = FW.FBL.getAncestorByClass(propValue, "cssProp");
// Click the value of the 'background-image' property inside the '#element' rule
FBTest.synthesizeMouse(prop, 2, 2);
// Verify the element display
FBTest.compare(
"-moz-linear-gradient(135deg, rgb(120, 140, 255), rgb(180, 200, 255))",
csElement.backgroundImage, "Element display must be correct");
FBTest.testDone();
}, 500);
}
}
});
});
}
|
import lesson2 from '../lesson2';
const {
sum,
sumAll,
pow,
random,
} = lesson2.task;
describe('sum function', () => {
it('should work with 2 numbers', () => {
expect(sum(10, 20)).toBe(30);
expect(sum(-10, 20)).toBe(10);
});
it('should throw exception if one of the arguments in not numeric', () => {
expect(() => sum('abc', 10)).toThrow('Illegal first argument, should be a number');
expect(() => sum(200, true)).toThrow('Illegal second argument, should be a number');
});
it('should throw exception with less then 2 arguments', () => {
expect(() => sum(10)).toThrow('Not enough arguments, should be two numbers');
expect(() => sum()).toThrow('Not enough arguments, should be two numbers');
});
});
describe('sumAll function', () => {
it('should return sum of all arguments', () => {
expect(sumAll(1, 2, 3)).toBe(6);
expect(sumAll(-100, 0, 50, 10.25, 1e5)).toBe(99960.25);
});
it('should return 0 w/o arguments', () => {
expect(sumAll()).toBe(0);
});
// it('should ignore/skip illegal arguments')
});
describe('pow function', () => {
it('should works with positive exponent', () => {
expect(pow(2, 5)).toBe(32);
expect(pow(-2, 2)).toBe(4);
expect(pow(-10, 3)).toBe(-1000);
expect(pow(-10, 0)).toBe(1);
});
it('should throw exception if base or exponent are not numeric', () => {
expect(() => pow('bar', 5)).toThrow('Illegal value of base, should be a number');
expect(() => pow(32, {})).toThrow('Illegal value of exponent, should be a positive integer number');
});
it('should throw exception if exponent is a float value', () => {
expect(() => pow(2, 5.23)).toThrow('Illegal value of exponent, should be a positive integer number');
});
it('should throw exception if exponent is negative value', () => {
expect(() => pow(2, -5)).toThrow('Exponent cannot be negative value');
});
});
describe('random function', () => {
it('should generate value with correct arguments', () => {
const result = random(2, 100);
expect(result).toBeGreaterThanOrEqual(2);
expect(result).toBeLessThanOrEqual(100);
});
it('should throw error if to argument is less than or equal to', () => {
expect(() => random(2, 2)).toThrow('from argument should be less than to');
expect(() => random(50, 40)).toThrow('from argument should be less than to');
});
it('should throw error if from or to are not numbric numbers', () => {
expect(() => random('five', 2)).toThrow('Illegal value of lower bound, should be a number');
expect(() => random(7, {})).toThrow('Illegal value of upper bound, should be a number');
});
});
|
$(()=>{
$.ajax({
type: "get",
url: "../../api/listB.php",
// data: "data",
dataType: "json",
success: function (response) {
console.log(response);
}
});
})
|
import React, { Component } from 'react'
import { Redirect } from 'react-router-dom'
export default class Connexion extends Component {
state = {
pseudo: '',
goToApp: false
}
goToApp = event => {
event.preventDefault()
this.setState({ goToApp: true })
}
handleChange = event => {
const pseudo = event.target.value
this.setState({ pseudo })
}
render() {
if(this.state.goToApp) {
return <Redirect push to = {`/pseudo/${ this.state.pseudo }`} />
}
return (
<div className='connexionBox'>
<form className = 'connexion' onSubmit = { this.goToApp }>
<h1>Ma boite à recettes</h1>
<input
type = 'text'
value = { this.state.pseudo }
onChange = { this.handleChange }
placeholder = 'Nom du chef'
required
pattern = '[A-Za-z-]{1,}' />
<button type = 'submit'>GO !</button>
<p>Pas de caractères spéciaux</p>
</form>
</div>
)
}
}
|
import React from "react";
import "react-native-gesture-handler";
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
import Search from "../screens/Tabs/Search";
import Notifications from "../screens/Tabs/Notifications";
import Profile from "../screens/Tabs/Profile";
import { View } from "react-native";
import MessagesLink from "../components/MessagesLink";
import StackFactory from "../components/StackFactory";
import Home from "../screens/Tabs/Home";
import { createStackNavigator } from "@react-navigation/stack";
const TabNavigation = createBottomTabNavigator();
export default ({ navigation, route }) => {
const { SetSwipeEnabled } = route.params;
return (
<TabNavigation.Navigator initialRouteName="Home">
<TabNavigation.Screen
name="Home"
component={StackFactory}
initialParams={{
initialRoute: Home,
customConfig: {
title: "Home",
headerRight: () => <MessagesLink />,
},
}}
listeners={{
tabPress: () => SetSwipeEnabled(true),
}}
/>
<TabNavigation.Screen
name="Search"
component={StackFactory}
initialParams={{
initialRoute: Search,
customConfig: { title: "Search" },
}}
listeners={{
tabPress: () => SetSwipeEnabled(false),
}}
/>
<TabNavigation.Screen
name="Add"
component={View}
listeners={{
tabPress: (e) => {
console.log("#######################################");
e.preventDefault();
navigation.navigate("PhotoNavigation");
},
}}
/>
<TabNavigation.Screen
name="Notifications"
component={StackFactory}
initialParams={{
initialRoute: Notifications,
customConfig: { title: "Notifications" },
}}
listeners={{
tabPress: () => SetSwipeEnabled(false),
}}
/>
<TabNavigation.Screen
name="Profile"
component={StackFactory}
initialParams={{
initialRoute: Profile,
customConfig: { title: "Profile" },
}}
listeners={{
tabPress: (e) => SetSwipeEnabled(false),
}}
/>
</TabNavigation.Navigator>
);
};
|
var username = document.querySelector('.input__name');
var email = document.querySelector('.input__email');
var password = document.querySelector('.input__password');
var repassword = document.querySelector('.input__repassword');
var submit = document.querySelector('.btn');
var checkbox = document.getElementById("terms");
var username_error = document.getElementById('username_error');
var email_error = document.getElementById('email_error');
var password_error = document.getElementById('password_error');
var repassword_error = document.getElementById('repassword_error');
var terms_error = document.getElementById('terms_error');
const usernameCheck = /[^A-Za-z0-9]/;
const emailCheck = /.[^@]+@[^\.]+\...+/;
const passwordCheck = /^[a-zA-Z0-9!?@%:<>#$&(*)\\-`.+,={}[\]/\"]*$/
function checkUsername(){
if(username.value === "") {
username_error.innerText = "Field is required";
}
else if (usernameCheck.test(username.value)){
username_error.innerText = "Only letters and numbers allowed"
}
else {
username_error.innerText = ""
submit.disabled = false;
}
}
function checkEmail(){
if(email.value === "") {
email_error.innerText = "Field is required"
}
else {
email_error.innerText = ""
submit.disabled = false;
}
}
function checkEmailFormat(){
if (!emailCheck.test(email.value)){
email_error.innerText = "Please enter correct email address";
}
else {
submit.disabled = false;
}
}
function checkPassword(){
if(password.value === "") {
password_error.innerText = "Field is required";
}
else if (!passwordCheck.test(password.value)){
password_error.innerText = "Password contains unallowed characters"
}
else {
password_error.innerText = "";
submit.disabled = false;
}
}
function checkPasswordLength(){
if (password.value.length <= 6){
password_error.innerText = "Password have to be 6 characters long or more";
}
else {
submit.disabled = false;
}
}
function checkTerms(){
if (!checkbox.checked){
terms_error.innerText = "You need to agree with terms of use to proceed"
submit.disabled = true;
}
else {
terms_error.innerText = ""
submit.disabled = false;
}
}
function checkOnSubmit(){
checkEmail();
checkUsername();
checkPassword();
checkTerms();
if (password.value != repassword.value){
repassword_error.innerText = "Passwords are not matched";
}
if (
password_error.innerText.length > 0 ||
repassword_error.innerText.length > 0 ||
username_error.innerText.length > 0 ||
terms_error.innerText.length > 0
) {
submit.disabled = true;
}
else
{
submit.disabled = false;
}
}
|
/**
* 这里是登录表单
* @type {[type]}
*/
var loginModule = angular.module("loginModule", []);
loginModule.controller('loginCtrl', function($scope, $http, $rootScope, AUTH_EVENTS, AuthService) {
$scope.userInfo = {
username: '',
password: ''
};
$scope.loginfail = false;
$scope.login = function(userInfo) {
AuthService.login(userInfo).then(function(data) {
if (!(data.role === "guest")) {
$rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
$rootScope.setCurrentUser(data.username);
$rootScope.first = true;
} else {
$scope.loginfail = true;
}
}, function() {
$rootScope.$broadcast(AUTH_EVENTS.loginFailed);
});
};
$scope.resetForm = function() {
$scope.userInfo = {
username: "",
password: ""
};
};
});
loginModule.constant('AUTH_EVENTS', {
loginSuccess: 'auth-login-success',
loginFailed: 'auth-login-failed',
passwordError: 'auth-login-error',
logoutSuccess: 'auth-logout-success',
sessionTimeout: 'auth-session-timeout',
notAuthenticated: 'auth-not-authenticated',
notAuthorized: 'auth-not-authorized'
});
loginModule.constant('USER_ROLES', {
all:'*',
admin: 'admin',
teacher: 'teacher',
student: 'student',
guest: 'guest'
});
//一些操作的身份认证授权服务 登录的具体实现逻辑应该在这里,登录认证应该解耦,登录Controller应该只关心表单的事情
loginModule.factory('AuthService', function($http, Session) {
var authService = {};
authService.login = function(userInfo) {
return $http
.post('LoginServlet', userInfo)
.then(function(res) {
Session.create(res.data.password, res.data.username,
res.data.role);
return res.data;
});
}
authService.isAuthenticated = function() {
return !!Session.userId;
};
authService.isAuthorized = function(authorizedRoles) {
if (!angular.isArray(authorizedRoles)) {
authorizedRoles = [authorizedRoles];
}
return (authService.isAuthenticated() &&
authorizedRoles.indexOf(Session.userRole) !== -1);
};
return authService;
});
loginModule.service('Session', function($http,$rootScope) {
this.userRole = "guest";
this.create = function(sessionId, userId, userRole) {
this.id = sessionId;
this.userId = userId;
this.userRole = userRole;
};
this.getRole = function(){
return this.userRole;
};
this.destroy = function() {
this.id = null;
this.userId = null;
this.userRole = null;
};
this.getSessionFromServer = function() {
var that = this;
$http.post('SessionServlet').then(function(res) {
that.create(res.data.password, res.data.username,
res.data.role);
if(res.data.username){
$rootScope.setCurrentUser(res.data.username);
$rootScope.first = true;
}
});
};
this.toLocalString = function() {
console.log("localToString----");
console.log("sessionid=" + this.id + ",userId=" + this.userId);
};
return this;
});
/**
* 这里是数据表单版块
*
*/
var gridModule = angular.module('gridModule', []);
gridModule.controller('dropzoneCtrl', function($scope,$rootScope,$http) {
$scope.downloaddata = {
};
$scope.uploaddata = {
};
$scope.errord= false;
$scope.successd = false;
$scope.erroru= false;
$scope.successu = false;
$scope.upload = function(){
$http.post('StudentServlet',{data:uploaddata,method:"commitAll"}).then(function(res) {
$scope.successu = true;
});;
};
$scope.download = function(){
$http.post('GirdServlet').then(function(res) {
$scope.downloaddata = res.data;
$scope.successd = true;
});
};
});
gridModule.controller('passCtrl', function($scope,$rootScope,$http) {
var name = $rootScope.user.username + "";
$scope.pass = {
username: name,
oldpass:'',
newpass:'',
method:'editPass'
};
$scope.errorf= false;
$scope.successf = false;
$scope.editpass = function(pass){
console.log(pass);
$http.post('UserServlet',pass).then(function(res) {
if(res.data){
$scope.successf = true;
}else{
$scope.errorf= true;
}
});
};
});
gridModule.controller('StuListCtrl', function($scope,$http) {
var vm = $scope.vm = {};
vm.page = {
size: 5,
index: 1
};
$scope.errorf= false;
$scope.successf = false;
vm.setindex = function(index){
vm.page.index = index;
};
vm.addstudent = {};
vm.addstu = function(addstudent){
vm.items.push(addstudent);
vm.addstudent = {};
};
vm.commit = function(){
var data = JSON.stringify(vm.items);
$http.post('StudentServlet',{data:data,method:"commitAll"}).then(function(res) {
if(res.data){
$scope.successf = true;
}else{
$scope.errorf= true;
}
});;
};
vm.cancel = function(){
vm.items = vm.backup;
};
vm.sort = {
column: 'id',
direction: -1,
toggle: function(column) {
if (column.sortable === false)
return;
if (this.column === column.name) {
this.direction = -this.direction || -1;
} else {
this.column = column.name;
this.direction = -1;
}
}
};
vm.columns = [{
label: '学号',
name: 'id',
type: 'string'
}, {
label: '姓名',
name: 'name',
type: 'string'
}, {
label: '性别',
name: 'sex',
type: 'boolean'
}, {
label: '班级',
name: 'sclass',
type: 'string'
}, {
label: '联系电话',
name: 'phone',
type: 'string'
}, {
label: '地址',
name: 'phone',
type: 'string'
}, {
label: '政治背景',
name: 'party',
type: 'string'
}, {
label: '',
name: 'actions',
sortable: false
}];
vm.items = [];
vm.backup = [];
$http.post('GirdServlet').then(function(res) {
vm.items = res.data;
vm.backup = res.data;
});
});
var chartsModule = angular.module('chartsModule',[]);
chartsModule.controller('chartsCtrl', function($scope) {
$scope.option = {};
$scope.chartInit = function() {
var myChart = echarts.init(document.getElementById('main'));
var option = {
title: {
text: '功能尚未完善,请期待',
x: 'center'
},
tooltip: {
trigger: 'item',
formatter: "{a} <br/>{b} : {c} ({d}%)"
},
legend: {
orient: 'vertical',
x: 'left',
data: ['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎']
},
toolbox: {
show: true,
feature: {
mark: {
show: true
},
dataView: {
show: true,
readOnly: false
},
magicType: {
show: true,
type: ['pie', 'funnel'],
option: {
funnel: {
x: '25%',
width: '50%',
funnelAlign: 'left',
max: 1548
}
}
},
restore: {
show: true
},
saveAsImage: {
show: true
}
}
},
calculable: true,
series: [{
name: '访问来源',
type: 'pie',
radius: '55%',
center: ['50%', '60%'],
data: [{
value: 335,
name: '直接访问'
}, {
value: 310,
name: '邮件营销'
}, {
value: 234,
name: '联盟广告'
}, {
value: 135,
name: '视频广告'
}, {
value: 1548,
name: '搜索引擎'
}]
}]
};
myChart.setOption(option);
}
});
|
//Agregar un nuevo trayecto
$(document).on("pagecreate", function () {
$("#add").click(function () {
nextId++;
var content = "<div data-role='collapsible' id='set" + nextId + "' data-collapsed='false'><h3>Trayecto " + nextId + "</h3>"
+ "<div>"
+ "<table>"
+ "<tr>"
+ "<td colspan='2'>"
+ "Categoria"
+ "</td>"
+ "</tr>"
+ "<tr>"
+ "<td colspan='2'>"
+ "<select name='categoria' id='categoria" + nextId + "' data-mini='true' style='width: 220px;'>"
+ "</select>"
+ "</td>"
+ "</tr>"
+ "<tr>"
+ "<td>"
+ "Salida"
+ "</td>"
+ "<td rowspan='2' style='position:relative; top:12px;'>"
+ "</td>"
+ "</tr>"
+ "<tr>"
+ "<td>"
+ "<input type='text' name='salida' id='salida" + nextId + "' disabled='true' style='width: 180px;' />"
+ "</td>"
+ "</tr>"
+ "<tr>"
+ "<td>"
+ "Llegada"
+ "</td>"
+ "<td rowspan='2' style='position:relative; top:12px;'>"
+ "<a href='#popupMap' class='ui-btn ui-icon-location ui-btn-icon-notext' data-icon='location' data-rel='popup' data-iconpos='notext' data-shadow='false' data-iconshadow='false' data-position-to='window' data-transition='slidedown' style='-webkit-border-radius: .3125em; border-radius: .3125em;' onclick=\"SetLocationIndex('llegada', " + nextId + ");\">Map</a>"
+ "</td>"
+ "</tr>"
+ "<tr>"
+ "<td>"
+ "<input type='text' name='llegada' id='llegada" + nextId + "' onchange='cargarSalidas();' style='width: 180px;' />"
+ "</td>"
+ "</tr>"
+ "<tr>"
+ "<td colspan='2'>"
+ "Descripción"
+ "</td>"
+ "</tr>"
+ "<tr>"
+ "<td colspan='2'>"
+ "<textarea cols=26 rows='4' name='descripcion' id='descripcion" + nextId + "' style='width: 220px;'></textarea>"
+ "</td>"
+ "</tr>"
+ "</table>"
+ "<a href='#popupEliminarTrayecto' data-rel='popup' data-shadow='false' data-iconshadow='false' data-position-to='window' style='text-decoration: none;'><button type='button' data-icon='gear' data-iconpos='left' data-mini='false' data-inline='false' id='cambiarpass' onclick='SetTrayectoIndex(" + nextId + ")'>Eliminar trayecto</button></a>"
+ "</div>"
+ "</div>";
$("#set").append(content).collapsibleset("refresh");
var concat = "";
for (var i = 0; i < categorias.length; i++) {
concat += "<option value='" + categorias[i].Id + "'>" + categorias[i].Nombre + "</option>";
}
$("#categoria" + nextId + "").append(concat);
cargarSalidas();
});
});
|
const path = require('path')
/**
* Configure Storybook.
*
* @see https://storybook.js.org/docs/react/configure/overview
*/
module.exports = {
reactOptions: {
fastRefresh: true,
strictMode: true
},
stories: [
'../components/**/**/*.stories.@(js|mdx)',
'../docs/**/**/*.stories.@(mdx)'
],
addons: [
'@storybook/addon-a11y',
'@storybook/addon-essentials',
'@storybook/addon-links',
'storybook-css-modules-preset'
],
webpackFinal: async (config) => {
// Enable @ symbol aliases.
config.resolve.alias = {
...config.resolve.alias,
'@': path.resolve(__dirname, '../')
}
// Enable sourcemaps in Storybook.
config.module.rules.push({
test: /\.css$/i,
use: [
{
loader: 'postcss-loader',
options: {
sourceMap: true
}
}
]
})
return config
}
}
|
import React from 'react';
const ErrorGenerator = ({ action }) => (
<p>
<button onClick={() => action('ACTION_ERROR_IN_PUT')}>Action erro in put</button>{' '}
<button onClick={() => action('ACTION_ERROR_IN_SELECT')}>Action erro in select</button>{' '}
<button onClick={() => action('ACTION_ERROR_IN_CALL_SYNC')}>Action erro in call sync</button>{' '}
<button onClick={() => action('ACTION_ERROR_IN_CALL_ASYNC')}>Action erro in call async</button>{' '}
<button onClick={() => action('ACTION_ERROR_IN_CALL_INLINE')}>Action erro in call inline</button>{' '}
<button onClick={() => action('ACTION_ERROR_IN_CALL_FORK')}>Action erro in call fork</button>{' '}
<button onClick={() => action('ACTION_ERROR_IN_CALL_SPAWN')}>Action erro in call spawn</button>{' '}
<button onClick={() => action('ACTION_ERROR_IN_CALL_RACE')}>Action erro in call race</button>{' '}
<button onClick={() => action('ACTION_CAUGHT_ERROR')}>Action caught error</button>{' '}
<button onClick={() => action('ACTION_INLINE_SAGA_ERROR')}>Action error inlined error</button>{' '}
<button onClick={() => action('ACTION_IN_DELEGATE_ERROR')}>Action error in delegated error</button>{' '}
<button onClick={() => action('ACTION_FUNCTION_EXPRESSION_ERROR')}>Action error in saga as function expression</button>
<button onClick={() => action('ACTION_ERROR_IN_RETRY')}>Error in retry</button>
<button onClick={() => action('ACTION_ERROR_PRIMITIVE')}>Error as a primitive</button>
</p>
);
export default ErrorGenerator;
|
"use strict";
var archDevRequire = require("@walmart/electrode-archetype-react-app-dev/require");
var mergeWebpackConfig = archDevRequire("webpack-partial").default;
var cdnLoader = archDevRequire.resolve("@walmart/cdn-file-loader");
module.exports = function () {
return function (config) {
return mergeWebpackConfig(config, {
module: {
loaders: [{
name: "images",
test: /\.(jpe?g|png|gif|svg)$/i,
loader: cdnLoader + "?limit=10000!isomorphic"
}]
}
});
};
};
|
module.exports.createAccessControlList = function(serviceLocator) {
var
acl = {};
function addResource(resource, description) {
if (acl[resource] === undefined) {
serviceLocator.logger.verbose('Adding resource \'' + resource + '\' to access control list');
acl[resource] = {
description: description,
actions: {}
};
} else {
serviceLocator.logger.verbose('Resource \'' + resource + '\' already added');
}
}
function grant(target, resource, action) {
if (acl[resource].actions[action] === undefined) {
acl[resource].actions[action] = [target];
} else if (acl[resource].actions[action].indexOf(target) === -1) {
acl[resource].actions[action].push(target);
}
}
function revoke(target, resource, action) {
}
function targetAllowed(target, resource, action) {
return acl[resource] && acl[resource].actions[action] && acl[resource].actions[action].indexOf(target) !== -1;
}
function allowed(targets, resource, action, callback) {
if (!Array.isArray(targets)) {
targets = [targets];
}
for (var i = 0; i < targets.length; i++) {
target = targets[i];
if (targetAllowed(target, resource, action)) {
return callback(null, true);
}
}
return callback(null, false);
}
return {
acl: acl,
addResource: addResource,
grant: grant,
revoke: revoke,
allowed: allowed
};
}
|
// meteor add webapp
// meteor add ostrio:spiderable-middleware
import { WebApp } from 'meteor/webapp';
import Spiderable from 'meteor/ostrio:spiderable-middleware';
WebApp.connectHandlers.use(new Spiderable({
rootURL: 'http://example.com',
serviceURL: 'https://render.ostr.io',
auth: 'APIUser:APIPass'
}));
|
import React, {Component} from 'react';
export default class PalindromeView extends Component {
render() {
return(
<div>
{this.props.s.map((f) => ([
<ul key={f.id}>
<h4 key={f.nameId}>{f.filename} </h4>
<p key={f.countId}> Count: {f.palindromeCount}</p>
{f.palindromes.map((g, index) => <li key={index}>{g}</li>)}
</ul>
])
)}
</div>
)
}
}
|
import React from 'react'
import {TitleBar} from "./TitleBar"
import axios from "axios"
const terrainMap = {
'O' : {color: 'blue'},
'B' : {color: 'burlywood'},
'G' : {color: 'lightgreen'},
'R' : {color: 'lightblue'},
'F' : {color: 'darkgreen'}
}
export class AppComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
startX: 1,
startY: 1,
squareSize: 10,
squares: null
}
}
getCoords(){
let x1=this.state.startX
let y1=this.state.startY
let x2=this.state.startX+this.state.squareSize-1
let y2=this.state.startY+this.state.squareSize-1
return {x1:x1,y1:y1,x2:x2,y2:y2}
}
async refreshData(){
let grid = {}
const {x1,y1,x2,y2} = this.getCoords()
const result = await axios.get('/api/square/area/' + x1 + '/' + y1 + '/' + x2 + '/' + y2)
// make a grid
result.data.forEach((cel) => {
if (!grid[cel.xc]) {
grid[cel.xc] = {}
}
grid[cel.xc][cel.yc] = cel
})
this.setState( {squares: grid})
}
async componentDidMount() {
this.refreshData()
}
makeGrid(){
let rows = []
if (!this.state.squares){
return [];
}
let celSize = 25
rows.push( )
for (let x=this.state.startX; x < this.state.startX+this.state.squareSize; x++){
let row = [], char
for (let y=this.state.startY; y < this.state.startY+this.state.squareSize; y++){
let r = this.state.squares[x]
char = "?"
if (!r){
char = "?"
}
else {
let cel = r[y]
if (cel) {
char = cel.terrainType
}
}
let color = terrainMap[char] ? terrainMap[char].color : 'white'
row.push( <div key={y} style={{ height: celSize, width: celSize, backgroundColor: color}}>{char} </div>)
}
rows.push(<div style={{display: 'flex', flexDirection: 'row'}} key={x}>{row}</div>)
}
return <div>{rows}</div>;
}
updateSize(inc){
this.state.squareSize = this.state.squareSize + inc
this.refreshData()
}
moveStart(xd, yd){
this.state.startX = Math.max(this.state.startX + xd, 1)
this.state.startY = Math.max(this.state.startY + yd, 1)
this.refreshData()
}
render() {
let celSize = 25
return (
<div>
<TitleBar title="Food Chain"/>
<div style={{display: 'flex', flexDirection: 'row', padding: 10}}>
{ this.makeGrid()}
<div style={{paddingLeft: 10}}>
<div>Location: {this.state.startX}, {this.state.startY}</div>
<div style={{display: 'flex', flexDirection: 'column'}}>
<div style={{display: 'flex', flexDirection: 'row'}}>
<div style={{width: celSize}}/>
<button style={{width: celSize }} onClick={this.moveStart.bind(this, -1, 0)}>U</button>
</div>
<div style={{display: 'flex', flexDirection: 'row'}}>
<button style={{width: celSize}} onClick={this.moveStart.bind(this, 0, -1)}>L</button>
<div style={{width: celSize}}/>
<button style={{width: celSize}} onClick={this.moveStart.bind(this, 0, 1)}>R</button>
</div>
<div style={{display: 'flex', flexDirection: 'row'}}>
<div style={{width: celSize}}/>
<button style={{width: celSize}} onClick={this.moveStart.bind(this, 1, 0)}>D</button>
</div>
</div>
<div style={{paddingTop: 25}}>Square Size: {this.state.squareSize}</div>
<div style={{display: 'flex', flexDirection: 'row'}}>
<button style={{width: celSize}} onClick={this.updateSize.bind(this, -1)}>-</button>
<div style={{width: celSize}}/>
<button style={{width: celSize}} onClick={this.updateSize.bind(this, 1)}>+</button>
</div>
</div>
</div>
</div>
)
}
}
|
function titleCase(title, minorWords) {
return title.split(' ').map(function(element) {
return element.toLowerCase()[0].toUpperCase().concat(element.substr(1, element.length).toLowerCase());
}).join(' ');
}
console.log(titleCase('the quick brown fox'));
|
/**
* 店铺地址
*/
import React, { Component, PureComponent } from 'react';
import {
StyleSheet,
Dimensions,
View,
Text,
Button,
Image,
ScrollView,
TouchableOpacity
} from 'react-native';
import { connect } from 'rn-dva';
import Header from '../../components/Header';
import CommonStyles from '../../common/Styles';
import ImageView from '../../components/ImageView';
import TextInputView from '../../components/TextInputView';
import * as nativeApi from '../../config/nativeApi';
import Line from '../../components/Line';
import Content from '../../components/ContentItem';
import picker from "../../components/Picker";
import * as Address from '../../const/address'
const { width, height } = Dimensions.get('window');
export default class StoreAddressScreen extends PureComponent {
static navigationOptions = {
header: null,
}
constructor(props) {
super(props)
this.state = {
address: this.props.navigation.state.params.address,
areaData: {
codes: ['120000', '120000', '120118'],
names: ['天津市', '天津市', '和平区']
},
location: {
lng: '',
lat: ''
},
currentShop: {
detail: {
}
}
}
}
componentDidMount() {
const { navigation } = this.props
let currentShop = navigation.getParam('currentShop', {})
let currentShopDetail = currentShop.detail || {};
let { provinceCode, cityCode, districtCode } = currentShopDetail || {};
let areaData = { // 获取省市区
codes: [provinceCode, cityCode, districtCode],
names: Address.getNamesByDistrictCode(districtCode)
}
let location = {
lat: currentShopDetail.lat || "",
lng: currentShopDetail.lng || ""
}
this.handleChangeState('areaData', areaData)
this.setState({
location,
areaData,
currentShop
})
}
componentWillUnmount() {
Loading.hide()
}
handleChangeState = (key = '', value = '', callback = () => { }) => {
this.setState({
[key]: value
}, () => {
callback()
})
}
save = () => {
if (this.state.address && this.state.currentShop.detail.locationAddress) {
this.props.navigation.state.params.callback({
address: this.state.address,
provinceCode: this.state.areaData.codes[0],
cityCode: this.state.areaData.codes[1],
districtCode: this.state.areaData.codes[2],
locationAddress: this.state.currentShop.detail.locationAddress,
...this.state.location
})
this.props.navigation.goBack()
}
}
// 未保存的状态下,保存选择的经纬度和店铺名
getLactionData = (data) => {
console.log(JSON.parse(data))
let _currentShop = JSON.parse(JSON.stringify(this.state.currentShop))
let locationData = JSON.parse(data)
const { title, point } = locationData
_currentShop.detail.locationAddress = title
_currentShop.detail.lat = point.lat
_currentShop.detail.lng = point.lng
this.setState({
currentShop: _currentShop,
location: point
})
}
selectArea=()=>{
picker._showAreaPicker(data => {
const isOldAdress=data==JSON.stringify(this.state.areaData)
const districtItem=Address.pickerArea.districts.find(item=>item.code==data.codes[2] && item.parentCode==data.codes[1]) || {}
this.setState({
areaData: data,
location:{lng: districtItem.longitude,lat: districtItem.latitude},
address:isOldAdress?this.state.address:'',
currentShop:{
...this.state.currentShop,
detail:{
...this.state.currentShop.detail,
locationAddress:isOldAdress?this.state.currentShop.detail.locationAddress:''
}
}
})
},this.state.areaData.names || []);
}
render() {
const { navigation } = this.props;
const { areaData, location, currentShop } = this.state
console.log(areaData)
return (
<View style={styles.container}>
<Header
title='店铺地址'
navigation={navigation}
goBack={true}
rightView={
<TouchableOpacity
onPress={() => this.save()}
style={{ width: 50 }}
>
<Text style={{ fontSize: 17, color: this.state.address && this.state.currentShop.detail.locationAddress ? '#fff' : 'rgba(255,255,255,0.5)' }}>保存</Text>
</TouchableOpacity>
}
/>
<ScrollView alwaysBounceVertical={false} style={{ flex: 1 }}>
<View style={styles.content}>
<Content>
<Line title='所属地区' type="horizontal" point={null}
onPress={this.selectArea}
value={!areaData || (areaData && areaData.codes && !areaData.codes[0])?'':areaData.names.join('-')}
/>
</Content>
<Content>
<Line title='店铺定位' type="horizontal" point={null} onPress={() => {
if (!areaData || (areaData && areaData.codes && !areaData.codes[0])) {
Toast.show('请选择所属地区')
} else {
let newLocation={...location}
if(!location.lat){
const districtItem=Address.pickerArea.districts.find(item=>item.code==areaData.codes[2]) || {}
newLocation.lat=districtItem.latitude
newLocation.lng=districtItem.longitude
this.setState({
location:newLocation
})
}
navigation.navigate('AddressLocation', {
headerTitle:'选择定位',
region:areaData.names,
title: currentShop.detail && currentShop.detail.locationAddress || '',
getLactionData: this.getLactionData,
...newLocation,
uriValue:'map'
})
}
}
}
value={currentShop.detail && currentShop.detail.locationAddress || ''}
/>
<Line
title='详细地址'
point={null}
type='input'
maxLength={20}
styleInput={{textAlign:'right'}}
placeholder='请输入详细地址'
value={this.state.address}
onChangeText={(data) => this.setState({ address: data })}
/>
</Content>
</View>
</ScrollView>
</View>
);
}
};
const styles = StyleSheet.create({
container: {
...CommonStyles.containerWithoutPadding,
backgroundColor: CommonStyles.globalBgColor
},
content: {
alignItems: 'center',
paddingBottom: 10
},
inputView: {
flex: 1,
marginLeft: 10
},
input: {
flex: 1,
padding: 0,
fontSize: 14,
lineHeight: 20,
height: 20,
},
});
|
const features = {};
function broadcastFeatures() {
Object.keys(localStorage).filter(key => key.startsWith('_feature.') && key !== '_feature._enabled')
.forEach(feature => features[feature] = JSON.parse(localStorage.getItem(feature)))
chrome.runtime.sendMessage({event: 'featureDiscovery', features});
}
chrome.runtime.onMessage.addListener(function (message, sendResponse) {
if (message.event === 'featureToggled') {
localStorage.setItem(message.feature, JSON.stringify(message.value));
sendResponse(true);
broadcastFeatures();
}
})
broadcastFeatures();
|
// Auth
export const AUTH = 'AUTH';
export const LOGOUT = 'LOGOUT';
export const ERROR = 'ERROR';
// Box
export const ADD_TO_BOX = 'ADD_TO_BOX';
export const REMOVE_FROM_BOX = 'REMOVE_FROM_BOX';
export const INCREASE_PRODUCT_AMOUNT = 'INCREASE_PRODUCT_AMOUNT';
export const DECREASE_PRODUCT_AMOUNT = 'DECREASE_PRODUCT_AMOUNT';
export const COUNT_FINAL_PRICE = 'COUNT_FINAL_PRICE';
// Products
export const GET_PRODUCTS = 'GET_PRODUCTS';
export const PRODUCTS_ERROR = 'PRODUCTS_ERROR';
// Users
export const ADD_USER = 'ADD_USER';
|
//! ################################################################
//! Copyright (c) 2004 Amazon.com, Inc., and its Affiliates.
//! All rights reserved.
//! Not to be reused without permission
//! $Change: 1312631 $
//! $Revision: 1.1 $
//! $DateTime: 2007/03/02 09:47:36 $
//! ################################################################
function n2PanesInitLibrary() { // Begin library code wrapper. Goes all the way to the bottom of the file
if (window.goN2LibMon) goN2LibMon.beginLoad('panes', 'n2CoreLibs');
window.N2MenuPane=function() {
N2PopoverPane.call ( this );
this.sCurrentHighlight=null;
this.sCurrentHighlightAction=null;
this.sSelectedClass = "expMenuSelected";
this.sUnselectedClass = null;
this.highlight = function (sDivID) {
if (this.sCurrentHighlight)
goN2U.setClass(this.sCurrentHighlight, this.sUnselectedClass);
this.sCurrentHighlight = this.oPopover.getID()+ this.sID + sDivID;
;
var oDiv;
if (oDiv = goN2U.getRawObject(this.sCurrentHighlight))
goN2U.setClass(oDiv, this.sSelectedClass);
else
;
}
}
N2MenuPane.prototype = new N2PopoverPane();
window.N2DynamicMenuPane=function() {
N2MenuPane.call ( this );
this.aEntries = new Array();
this.aActionIndex = new Array();
this.sSelectedClass = "microSelected";
this.sUnselectedClass = "micro";
this.sDisabledClass = "microDisabled";
this.addEntry = function (sAction, sHref, sText, bDisable) {
this.aActionIndex[sAction] = this.aEntries.length;
var aTmp = this.aEntries[this.aEntries.length] = {};
aTmp.sText = sText;
aTmp.sAction = sAction;
aTmp.sHref = sHref;
aTmp.bDisable = bDisable;
}
this.highlight = function (sAction) {
if (this.sCurrentHighlightAction) {
this.enableEntry(this.sCurrentHighlightAction);
}
var sDivID = this.sCurrentHighlight = this.oPopover.getID()+ this.sID + sAction;
;
var nIndex = this.aActionIndex[sAction];
var oDiv;
if (oDiv = goN2U.getRawObject(sDivID)) {
goN2U.setClass(oDiv, this.sSelectedClass);
this.aEntries[nIndex].sSaved = oDiv.innerHTML;
oDiv.innerHTML = this.aEntries[nIndex].sText;
this.sCurrentHighlightAction = sAction;
} else
;
}
this.enableEntry = function (sAction) {
var nIndex = this.aActionIndex[sAction];
var sDivID = this.oPopover.getID()+ this.sID + sAction;
var oDiv;
if (oDiv = goN2U.getRawObject(sDivID)) {
goN2U.setClass(oDiv, this.sUnselectedClass);
oDiv.innerHTML = this.aEntries[nIndex].sSaved;
} else {
;
}
}
this.disableEntry = function (sAction) {
var nIndex = this.aActionIndex[sAction];
var sDivID = this.oPopover.getID()+ this.sID + sAction;
var oDiv;
if (oDiv = goN2U.getRawObject(sDivID)) {
goN2U.setClass(oDiv, this.sDisabledClass);
oDiv.innerHTML = this.aEntries[nIndex].sText;
} else {
;
}
}
}
N2DynamicMenuPane.prototype = new N2MenuPane();
window.N2UpdatePane=function() {
N2PopoverPane.call ( this );
var oCfg = goN2U.getConfigurationObject('N2UpdatePane');
var nNoImageAvailabeCheckTimerMs = oCfg.getValue('noImageAvailableCheckDelay', '2000');
this.setDUAction('summary'); // set an action;
this.chainOnSuccess = this.onRequestSuccess; // save current to chain
this.onRequestSuccess = function (dataArray, fnArray, nStatus, sRequestID) {
;
var aParts = sRequestID.split('^');
this.oPopover.setLatestAction(aParts[1]);
if ((dataArray == null) && nStatus) {
dataArray= new Array();
dataArray[0] = this.defaultContent;
}
this.chainOnSuccess(dataArray, fnArray, nStatus, sRequestID);
var tmpFn = function () {
var i=1;
var oActive = goN2Events.getActivePopover();
var popID = oActive ? oActive.getID() : '';
var img = popID + '_PLI_' + i;
var elem, w;
while (elem = goN2U.getRawObject(img)) {
w = goN2U.getObjectWidth(elem);
if (w <2) {
elem.src = goN2Locale.getImageURL('JSF-thumb-no-image', 'x-locale/detail/thumb-no-image.gif');
}
i++;
img = popID + '_PLI_' + i;
}
}
try {
setTimeout(tmpFn, nNoImageAvailabeCheckTimerMs);
} catch (e) { }
}
}
N2UpdatePane.prototype = new N2PopoverPane()
window.N2ExpandoPane=function() {
N2PopoverPane.call ( this );
this.bDisableResizing = true;
this.deferredPopulate = this.populate;
this.initialize = function() {
;
this.bPopulated = false;
this.bExpanded = false;
this.aSP=null;
}
this.initialize();
this.populate = function (id, objectName, dataArrayName, populateMethod, locateMethod) {
this.aSP = [id, objectName, dataArrayName, populateMethod, locateMethod];
if (!this.bExpanded) {
this.setContent('');
this.bPopulated = false;
return;
} else {
var a = this.aSP;
this._defaultPopulate (a[0], a[1], a[2], a[3], a[4]);
this.bPopulated = true;
}
}
}
N2ExpandoPane.prototype = new N2PopoverPane();
N2ExpandoPane.prototype.oCfg = goN2U.getConfigurationObject('N2ExpandoPane');
N2ExpandoPane.prototype.deferredRePopulate = function (delay) {
var sElemID = this.oPopover.getID() + this.sID;
setTimeout("var e; if ( e = goN2U.getRawObject('" + sElemID +"') ) e.innerHTML=e.innerHTML;", delay);
}
N2ExpandoPane.prototype.oCfg = goN2U.getConfigurationObject('N2ExpandoPane');
N2ExpandoPane.prototype.toggle = function (id) {
if (this.bExpanded) this.contract(id)
else this.expand(id);
}
N2ExpandoPane.prototype.expand = function (id) {
var sIDM = this.oPopover.getID() + this.sID;
var contentDivID = sIDM + '_XI';
var contractorDivID = sIDM + '_C';
var expanderDivID = sIDM + '_X';
var delayMS = this.oCfg.getValue('expandContractDelay', '20');
;
var a = this.aSP;
if (!this.bPopulated) {
this.deferredPopulate (a[0], a[1], a[2], a[3], a[4]);
}
goN2U.expandDivHeight(contentDivID, expanderDivID, delayMS, null, contractorDivID);
if (!this.bPopulated) {
this.deferredRePopulate(2000);
} else {
this.deferredRePopulate(500);
}
this.oPopover.setLatestAction(this.sID);
this.bPopulated = true;
this.bExpanded = true;
}
N2ExpandoPane.prototype.contract = function (id) {
var sIDM = this.oPopover.getID() + this.sID;
var contentDivID = sIDM + '_XI';
var contractorDivID = sIDM + '_C';
var expanderDivID = sIDM + '_X';
var delayMS = this.oCfg.getValue('expandContractDelay', '20');
goN2U.collapseDivHeight(contentDivID, contractorDivID, delayMS, null, expanderDivID);
this.oPopover.setLatestAction('');
this.bExpanded = false;
}
window.N2SectionPane=function() {
N2PopoverPane.call ( this );
var aSections = new Array();
var aDefaultOrder = new Array();
var aCurrentOrder = new Array();
this.addSection = function (sID, sTitle, sContent, bExpanded) {
;
var tmp = new Object();
tmp.sID = sID;
tmp.sTitle = sTitle;
tmp.sContent = sContent;
tmp.bExpanded = bExpanded;
aSections[sID] = tmp;
var i = aDefaultOrder.length;
aCurrentOrder[i] = aDefaultOrder[i] = sID;
}
this.genSectionHTML = function (id) {
var sPID = this.oPopover.getID();
var tmp = aSections[id];
var sID = tmp.sID;
var sTitle = tmp.sTitle;
var sContent = tmp.sContent;
var bExpanded = tmp.bExpanded;
var sPopoverName = this.oPopover.getObjectName()
var sh="";
var rOrangeArrowImagePath = goN2Locale.getImageURL('JSF-r-orange-arrow', 'nav2/images/arrow-r-orange-11x10.gif');
var dOrangeArrowImagePath = goN2Locale.getImageURL('JSF-d-orange-arrow', 'nav2/images/arrow-d-orange-11x10.gif');
sh += '<table border="0"><tr><td width="12" valign="top">\n' +
'<span id="'+sPID+sID+'_X" ' +
(bExpanded ? 'style="display:none"' : '') +
'>\n' +
'<a href="javascript:' + sPopoverName + '.findPane(\''+sID+'\').expand(\''+sID+'\')">\n' +
'<img src="' + rOrangeArrowImagePath + '" width="11" height="10" border="0" alt="' +
goN2Locale.getString('alt_text_click_to_expand_36018', 'click to expand this section and see more') + '"></a>\n' +
'</span>\n' +
'<span id="'+sPID+sID+'_C" ' +
(!bExpanded ? 'style="display:none"' : '') +
'>\n' +
'<a href="javascript:' + sPopoverName + '.findPane(\''+sID+'\').contract(\''+sID+'\')">\n' +
'<img src="' + dOrangeArrowImagePath + '" width="11" height="10" border="0" alt="' +
goN2Locale.getString('alt_text_click_to_collapse_36019', 'click to collapse this section and see less') + '"></a>\n' +
'</span>\n' +
'</td><td class="internalLink"><a href="javascript:' + sPopoverName + '.findPane(\''+sID+'\').toggle(\''+sID+'\')">' + sTitle + '</a></td></tr></table>\n';
sh += '<div class="expandableVOuterVisible" ' +
(bExpanded ? '' : 'style="height:1"' )+
'>\n' +
'<div id="'+sPID+sID+'_XI" class="expandableInner" >\n' +
'<div id="'+sPID+sID+'" style="padding: 0 0 0 20px">'+sContent+'</div>' +
'\n</div></div>\n';
return sh;
}
this._determineOrder = function (sID, sType) {
var sExPaneID;
var sKey = sType+sID;
var aData = this.oPopover.getDataArray();
;
;
var tmp = this.oPopover.stack.current();
if (tmp && tmp.action && tmp.action != 'summary') {
sExPaneID = tmp.action;
} else if (aData[sKey].wl || aData[sKey].crt) {
sExPaneID = 'tiay';
} else if ( aData[sKey].nsims ) {
sExPaneID = 'sims';
} else {
sExPaneID = 'summary';
}
aCurrentOrder[1] = sExPaneID;
var len = aCurrentOrder.length;
for (var c=0, d=0;c<len;c++) {
if (c==1) c++;
if (aDefaultOrder[d] == sExPaneID) d++;
aCurrentOrder[c] = aDefaultOrder[d++];
}
return sExPaneID;
}
this.determineOrder = this._determineOrder;
this.populate = function(sAction, sID, sType, sParams, sLinkID, sHref, sLinkText){
;
var sExPaneID = this.determineOrder(sID, sType);
var sHtml = "";
var len = aCurrentOrder.length;
for (var i=0;i<len;i++) {
sHtml += this.genSectionHTML(aCurrentOrder[i]);
}
this.setContent(sHtml, false, true);
this.populateSubPanes(sAction, sID, sType, sParams, sLinkID, sHref, sLinkText);
this.oPopover.expandPane(sExPaneID);
;
};
}
N2SectionPane.prototype = new N2PopoverPane();
window.N2ExternalLink=function(sID, sHref, sText, sTip,
sDisField, sDisText,
nDisplayFlags) {
this.sID = sID;
this.sHref = sHref;
this.sText = sText;
this.sTip = sTip;
this.sDisField = sDisField;
this.sDisText = sDisText;
this.nFlags = nDisplayFlags;
this.getDisplayFlags = function() { return this.nFlags; }
this.getID = function() { return this.sID; }
this.setParent = function(oP) { this.oParent = oP; }
this.setPopover = function(oPop) { this.oPopover = oPop; }
this.genHTML = function (sTID, sTType) {
var sTxt;
var showDis = false;
if (this.oPopover && this.sDisField) {
var aTD = this.oPopover.getDataArray();
showDis = (sTType && sTID && (aTD[sTType + sTID][this.sDisField] >0)) ? true : false;
}
if (showDis) {
sTxt = '<div class="disabled">' + this.sDisText + '</div>';
} else {
sTxt = '<a href="' + this.sHref + '" onClick="n2HotspotDisableFeature()" '
+ 'name="disald" '
+ 'title="'+ this.sTip + '\n' +
goN2Locale.getString('you_will_go_to_new_page_36022', '(You will go to a new page)') + '">' +
this.sText + '</a>';
}
return sTxt;
}
}
window.N2InternalLink=function(sID, sField,
sTText, sTFunction, sTTip,
sFText, sFFunction, sFTip,
sDisField, sDisText,
nDisplayFlags) {
this.sID = sID;
this.sField = sField;
this.sTText = sTText;
this.sTFunction = sTFunction;
this.sFText = sFText;
this.sFTip = sFTip;
this.sTTip = sTTip;
this.sFFunction = sFFunction;
this.sDisField = sDisField;
this.sDisText = sDisText;
this.nFlags = nDisplayFlags;
this.getDisplayFlags = function() { return this.nFlags; }
this.getID = function() { return this.sID; }
this.setParent = function(oP) { this.oParent = oP; }
this.setPopover = function(oPop) { this.oPopover = oPop; }
this.genHTML = function (sTID, sTType) {
var sTxt;
var aTD = this.oPopover.getDataArray();
var valid = sTType && sTID;
if (valid && (aTD[sTType + sTID][this.sDisField] >0)) {
sTxt = '<div class="disabled">' + this.sDisText + '</div>';
} else if (valid && (aTD[sTType + sTID][this.sField] >0)) {
if (this.sTFunction != null) {
sTxt = '<div class="internalLink"><a href="javascript:' + this.sTFunction + '(\'' + sTID + '\',\'' + this.sID + '\')" ' +
'title="' + this.sTTip + '\n' +
goN2Locale.getString('you_will_stay_here_36023', '(You will stay right here)') + '">' +
this.sTText + '</a></div>';
} else {
sTxt = '<div class="disabled">' + this.sTText + '</div>';
}
} else {
if (this.sFFunction != null) {
sTxt = '<div class="internalLink"><a href="javascript:' + this.sFFunction + '(\'' + sTID + '\',\'' + this.sID + '\')" ' +
'title="' + this.sFTip + '\n' +
goN2Locale.getString('you_will_stay_here_36023', '(You will stay right here)') + '">' +
this.sFText + '</a></div>';
} else {
sTxt = '<div class="disabled">' + this.sFText + '</div>';
}
}
return sTxt;
}
}
window.N2LinksPane=function(oPopover, sID) {
N2PopoverPane.call ( this, oPopover, sID );
this.oPopover = oPopover;
this.sID = sID;
this.aEntries = new Array();
this.addEntry = function (oLink) {
this.aEntries[this.aEntries.length] = oLink;
oLink.setParent(this);
oLink.setPopover(this.oPopover);
}
this.setEntryStyle = function(s) { this.sEntryStyle = s; }
this.display = function (sEntryID) {
var sID = this.oPopover.getID() + this.getID() + sEntryID;
goN2U.display(sID);
}
this.undisplay = function (sEntryID) {
var sID = this.oPopover.getID() + this.getID() + sEntryID;
goN2U.undisplay(sID);
}
this.populate = function (action, id, type, sParams, sLinkID, sHref, sLinkText) {
var nLinks = this.aEntries.length;
var nDispFlag = goCust.isLoggedIn() ? 1 : 2; // yes: no
;
var sHtml = "";
for (var i=0; i<nLinks; i++) {
var oLink = this.aEntries[i];
if (oLink.getDisplayFlags() & nDispFlag) {
var sH = oLink.genHTML(id,type);
var sS = this.sEntryStyle ? 'style="' + this.sEntryStyle + '" ' : '';
if (sH && sH.length) {
sHtml += '<div id="' + this.oPopover.getID() + this.getID() + oLink.getID() + '" ' + sS + '>' + sH + '</div>\n';
}
}
}
this.setContent(sHtml);
}
this.overrideLink = function (n, s) {
var oLink = this.aEntries[n];
if (oLink) {
var eElem = goN2U.getRawObject(this.oPopover.getID() + this.getID() + oLink.getID());
if (eElem) eElem.innerHTML = s;
}
}
}
N2LinksPane.prototype = new N2PopoverPane();
if (window.goN2LibMon) goN2LibMon.endLoad('panes');
} // END library code wrapper
n2RunIfLoaded("popoverpane", n2PanesInitLibrary, "panes");
|
import React from 'react';
// components
import QuizHeader from './QuizHeader';
import Questions from './Questions';
import QuizResults from './QuizResults';
const Main = React.createClass({
render() {
return (
<div className="container quiz">
<div className="col-xs-12 col-sm-9 col-md-9 col-lg-8 col-centered" >
<QuizHeader {...this.props} />
<hr />
<Questions {...this.props} />
<hr />
<QuizResults {...this.props} />
</div>
</div>
);
}
});
export default Main;
|
// Copyright 2017 Joseph W. May. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* Run all unit tests.
*/
function runAllTests() {
var baseSpreadsheetTests = new BaseSpreadsheetTests();
baseSpreadsheetTests.run();
var masteryTrackerTests = new MasteryTrackerTests();
masteryTrackerTests.run();
var masteryDataTests = new MasteryDataTests();
masteryDataTests.run();
}
/**
* Base class for all tests.
* @constructor
*/
var Tests = function() {
// Do nothing.
};
/**
* Runs all member functions in the child class whose names begin with "test".
*/
Tests.prototype.run = function() {
var testCount = 0;
var failCount = 0;
var failNames = [];
Logger.log('Starting test run.');
for (var member in this) {
if ((typeof this[member] !== 'undefined') &&
(member.indexOf('test') === 0)) {
try {
testCount++;
this[member].call(this);
Logger.log('[PASS] : ' + member);
} catch (error) {
failCount++;
failNames.push('\t' + member + '\t\t' + error);
Logger.log('[FAIL] : ' + member + '\n' + error);
}
}
}
Logger.log(testCount + ' tests completed in this run.');
Logger.log(failCount + ' tests failed:\n' + failNames.join('\n'));
Logger.log('');
};
|
import helper from '../../../../common/common';
import {fetchDictionary2, setDictionary,fetchDictionary} from '../../../../common/dictionary';
import {buildEditDialogState} from '../../../../common/state';
import {createContainer} from '../EditPageContainer';
import showDialog from '../../../../standard-business/showDialog';
import {buildEditPageState} from '../../../basic/currencyFile/common/state';
const URL_CONFIG = '/api/basic/defaultOutput/config';
const addDefaultOutput = async () => {
try {
const {edit,dicNames} = helper.getJsonResult(await helper.fetchJson(URL_CONFIG));
const dictionary = helper.getJsonResult(await fetchDictionary(dicNames));
const payload = buildEditPageState(edit, {}, false);
const adjust = {title: '新增 - 默认模板输出'};
Object.assign(payload, adjust);
setDictionary(payload.controls, dictionary);
setDictionary(payload.tableCols, dictionary);
showDialog(createContainer, payload);
} catch(e) {
helper.showError(e.message);
}
};
export default addDefaultOutput;
|
'use strict'
/* Global Imports */
import { dbUser } from '../db-api/'
import { Success, Error } from '../util'
import { createToken } from '../services'
import Debug from 'debug'
/* Config Vars */
const debug = new Debug('nodejs-hcPartnersTest-backend:controllers:auth')
const register = async (req, res) => {
try {
debug('Register')
const params = req.body
const findUser = await dbUser.findByEmail(params.email)
if (findUser) {
return handleRegisterFailed(res, 'This email already exist')
} else {
let objectUser = params
objectUser.typeUserId = process.env.DEFAULT_ROL
const userSaved = await dbUser.create(objectUser)
const user = await dbUser.findUserTypeById(userSaved.id)
const token = await createToken(user)
const response = generateResponse(user, token)
Success(res, { data: response, model: 'user' }, 201)
}
} catch (error) {
Error(error, res)
}
}
const login = async (req, res) => {
try {
debug('Login')
const { identity, password } = req.body
const user = await dbUser.findUserTypeByEmail(identity)
if (!user) {
// validation if the email of user doesn't exist
return handleLoginFailed(res)
} else {
await user.comparePassword(password, user, function (error, match) {
if (error) Error(error, res)
else if (match) {
const token = createToken(user)
const response = generateResponse(user, token)
Success(res, { data: response, model: 'user' }, 200)
} else {
return handleLoginFailed(res, 'The username and password is invalid.')
}
})
}
} catch (error) {
Error(error, res)
}
}
/* Function to handle Errors in Login */
function handleLoginFailed (res, message) {
console.error(message || 'The user with email doesn\'t exist')
res.status(401).send({
message: message || 'The user with email doesn\'t exist',
error: 'Login failed'
})
}
function handleRegisterFailed (res, message) {
console.error(message || 'This email already exist')
res.status(409).send({
message: message || 'This email already exist',
error: 'Register Failed'
})
}
/* Function to generate the response object
* params:
* 1) User Object
* 2) Person Object
* 3) JWT token
*/
function generateResponse (user, token) {
const response = {
id: user.id,
name: user.name,
email: user.email,
type_user: user.type_user,
token
}
return response
}
/* Function to generate the objectUser
* params:
* 1) Object user
* 2) personId
*/
export default {
register,
login
}
|
var gameport = process.env.PORT || 3000;
var express = require('express');
// var verbose = false;
var app = express();
var http = require('http');
var server = http.Server(app);
var io = require('socket.io')(server);
var GachaServer = require('./server/GachaServer').GachaServer;
///This handler will listen for requests on /*, any file from the root of our server.
app.use(express.static(__dirname + '/public'));
//Tell the server to listen for incoming connections
server.listen(gameport,function(){
console.log('Server started!');
});
//By default, we forward the / path to index.html automatically.
app.all( '/', function(req, res){
res.sendFile( __dirname + '/public/index.html');
});
//Enter the game server code. The game server handles
//client connections looking for a game, creating games,
//leaving games, joining games and ending games when they leave.
io.on("connection", GachaServer.onSocketConnection);
process.on('uncaughtException', function (err) {
console.log("Connection was not established.")
console.log(err);
});
|
(function() {
function Message($firebaseArray) {
var Message = {};
var ref = firebase.database().ref().child("messages");
var messages = $firebaseArray(ref);
var date = new Date();
var datePost = date.toDateString();
Message.getByRoomId = function(roomId){
//filter message by room ID
var messageQuery = ref.orderByChild('roomId').equalTo(roomId);
var messageResult = $firebaseArray(messageQuery);
return messageResult;
};
Message.send = function(newMessage) {
messages.$add(newMessage);
};
return Message;
}
angular
.module('blocChat')
.factory('Message', ['$firebaseArray', Message]);
})();
|
import React, { Component } from 'react';
import { withStyles } from '@material-ui/core/styles';
import { Autocomplete } from '@material-ui/lab';
import PersonIcon from '@material-ui/icons/Person';
import AddIcon from '@material-ui/icons/Add';
import {
Box,
Button,
CircularProgress,
Dialog,
DialogActions,
DialogContent,
DialogContentText,
DialogTitle,
Fab,
MenuItem,
Select,
TextField,
Table,
TableHead,
TableBody,
TableRow,
TableCell,
Typography
} from '@material-ui/core';
const styles = theme => ({
duration: {
padding: '15px 30px',
borderColor: '#765ea8',
},
chip: {
marginRight: '5px',
},
avatar: {
backgroundColor: `${'#' + Math.floor(Math.random() * 16777215).toString(16)}`,
color: '#fff',
fontSize: 'xx-small'
},
inputlabel: {
fontSize: '12px',
lineHeight: '30px'
},
select: {
border: '1px solid rgba(0, 0, 0, 0.25)',
borderRadius: '5px',
paddingTop: '5px',
},
buttonGroup: {
marginTop: '16px'
},
fabAdd: {
borderRadius: "4px",
backgroundColor: "#4CAF50",
},
submitBtn: {
borderRadius: "4px",
margin: "30px 30px",
},
timeSelector: {
minWidth: "120px"
},
datePicker: {
minWidth: "120px"
}
});
class RequestDialog extends Component {
constructor(props) {
super(props);
}
render() {
const { classes, candidates, interviewers, rows, reqOpen, candidate, user } = this.props;
return (
<Dialog open={reqOpen} aria-labelledby="form-dialog-title" fullWidth maxWidth="lg">
<DialogTitle id="form-dialog-title">Schedule Interview</DialogTitle>
<DialogContent>
<DialogContentText>
To schedule a new interview, provide a candidate and a list of interviewers to request a list of options.
</DialogContentText>
<Autocomplete
autoFocus
options={candidates.filter(c => c.submittedAvailability == "T")}
getOptionLabel={candidate => candidate.firstName ? candidate.firstName + " " + candidate.lastName + " (" + candidate.email + ")" : ""}
style={{ width: 500 }}
renderInput={params => (
<TextField {...params} label="Candidate" variant="outlined" fullWidth />
)}
autoComplete={false}
value={candidate}
onChange={this.props.updateCandidate}
/>
<Table>
<TableHead>
<TableRow>
<TableCell>Required</TableCell>
<TableCell>Optional</TableCell>
<TableCell>Duration</TableCell>
<TableCell></TableCell>
</TableRow>
</TableHead>
<TableBody>
{rows.map((row, index) => (
<TableRow key={index}>
<TableCell>
<Autocomplete
multiple
options={interviewers}
getOptionLabel={interviewer => interviewer.email}
filterSelectedOptions
renderInput={params => (
<TextField {...params} label="Required interviewer(s)" variant="outlined" style={{ width: 450 }} />
)}
autoComplete={false}
value={row.required}
onChange={(event, value) => this.props.handleAutocompleteChange(event, value, index, 'required')}
/>
</TableCell>
<TableCell>
<Autocomplete
multiple
options={interviewers}
getOptionLabel={interviewer => interviewer.email}
filterSelectedOptions
renderInput={params => (
<TextField {...params} label="Optional interviewer(s)" variant="outlined" style={{ width: 450 }} />
)}
autoComplete={false}
value={row.optional}
onChange={(event, value) => this.props.handleAutocompleteChange(event, value, index, 'optional')}
/>
</TableCell>
<TableCell>
<Select
value={row.duration}
onChange={(event) => this.props.handleSelectorChange(event, index, 'duration')}
>
<MenuItem value={30}>0.5 hour</MenuItem>
<MenuItem value={60}>1 hour</MenuItem>
<MenuItem value={90}>1.5 hours</MenuItem>
<MenuItem value={120}>2 hours</MenuItem>
</Select>
</TableCell>
<TableCell>
<Button
variant="outlined"
color="primary"
onClick={() => { this.props.handleRemoveRow(index) }}
>
Remove
</Button>
</TableCell>
</TableRow>
))}
{rows.length > 0 && <TableRow>
<TableCell></TableCell>
<TableCell></TableCell>
<TableCell></TableCell>
<TableCell>
<Fab
aria-label="add"
size="small"
onClick={this.props.handleAddRow}
className={classes.fabAdd}>
<AddIcon />
</Fab>
</TableCell>
</TableRow>}
</TableBody>
</Table>
{rows.length === 0 &&
<Box>
<Typography
align='center'
style={{ margin: '100px auto' }}
>
No interviewer
</Typography>
<Button
variant="outlined"
color="primary"
onClick={this.props.handleAddRow}
style={{ margin: 'auto', display: 'block' }}
>
Add
</Button>
</Box>}
</DialogContent>
<DialogActions>
<Button onClick={this.props.handleClose} color="primary">Cancel</Button>
{
user.findMeetingTimesLoading
? <CircularProgress />
: (
<Button
onClick={this.props.handleNext}
color="primary"
disabled={!rows.length}
>
Next
</Button>
)
}
</DialogActions>
</Dialog >
);
}
}
export default withStyles(styles)(RequestDialog);
|
import React from "react";
import { Grid, Button } from "@material-ui/core";
import { connect } from "react-redux";
import { EgretTextField, EgretSelect } from '../../egret'
import { COLORS } from '../../app/config'
const SELECT_DATA = [
{ id: 1, name: 'Commercial Real Estate' },
{ id: 2, name: 'Cannabis Application Support' },
{ id: 3, name: 'Consumer Product & services' },
{ id: 4, name: 'Clean Tech, Fitness' },
{ id: 5, name: 'Financial Services' },
{ id: 6, name: 'Medical Technology, Biotech, Healthcare' },
{ id: 7, name: 'Education & E-Learning' },
];
function Header(props) {
return (
<div className="home-header">
<Grid container spacing={2}>
<Grid item lg={6} md={7} xs={12} className="plan-container px-sm-80 mt-100">
<div className="plan-investor">
Raise Capital With Custom Investor Business Plans And
</div>
<div className="plan mt-16">Venture Plans, your dream starts with us</div>
<div className="plan mt-12">Get funding with FINRA and Harvard</div>
<div className="plan mt-12">Accredited Industry Experts</div>
<EgretSelect
className="select-service mt-30"
placeholder="Select a Service"
data={SELECT_DATA}
backgroundcolor={COLORS.PRIMARY}
/>
</Grid>
<Grid item lg={6} md={5} xs={12} className="info-container px-sm-80">
<EgretTextField
placeholder="Full Name"
className="mt-12"
bordercolor={'transparent'}
/>
<EgretTextField
placeholder="Phone Number"
className="mt-16"
bordercolor={'transparent'}
/>
<EgretTextField
placeholder="Your Email Address"
className="mt-16"
bordercolor={'transparent'}
/>
<Button variant="contained" color="primary" className="mt-16 btnSubmit">
Submit
</Button>
</Grid>
</Grid>
</div>
);
}
const mapStateToProps = state => ({
});
export default connect(
mapStateToProps,
{ }
)(Header);
|
import React, { PureComponent } from 'react';
import { Redirect } from 'react-router-dom';
import { logout } from '../auth/auth-helper';
export default class Logout extends PureComponent {
render() {
logout(() => console.debug('logged out'));
return <Redirect to="/" />;
}
}
|
// Manages the layout of the dashboard
import DashMath from './dash-math.js'
let dragCoordOffset
function coordsInPixels({ x, y }, dashMath) {
return {
x: x * dashMath.unitSize,
y: y * dashMath.unitSize
}
}
function showGridGuide($guide = $('.dashboard-grid-square')) {
if ($guide) {
$guide.removeClass('hidden')
}
}
function hideGridGuide($guide = $('.dashboard-grid-square')) {
if ($guide) {
$guide.addClass('hidden')
}
}
function moveGridGuideTo({ x, y }, $guide = $('.dashboard-grid-square')) {
if ($guide) {
$guide.css({ transform: `translate(${x}px, ${y}px)`})
}
}
function setGridGuideSize(w, h, $guide = $('.dashboard-grid-square')) {
if ($guide) {
$guide.css({ width: w + 'px', height: h + 'px' })
}
}
function getDragCoords(e, $root, widget, unitSize, dragCoordOffset) {
let x, y
const { container } = widget.state
const gridBounds = $root[0].getBoundingClientRect()
x = e.clientX - gridBounds.left// - dragStartOffset.x
y = e.clientY - gridBounds.top// - dragStartOffset.y
x /= unitSize
y /= unitSize
// Throw away fractional component
x = ~~x
y = ~~y
// Adjust for coord offset
x -= dragCoordOffset.x
y -= dragCoordOffset.y
return { x, y }
}
function setUpEvents($el, $root, widget, dm, update, widgets) {
let dragImage
const $gridGuide = $('.dashboard-grid-square')
$el.on('dragstart', function(e) {
dragImage = dragImage || document.querySelector('#placeholder-pixel')
e.originalEvent.dataTransfer.setDragImage(dragImage, 0, 0)
$(this).addClass('dragging')
const unitSize = dm.unitSize
const [width, height] = widget.state.size
.split('x')
.map(n => parseInt(n) * unitSize)
setGridGuideSize(width, height, $gridGuide)
showGridGuide($gridGuide)
dragCoordOffset = {
x: ~~(e.offsetX / unitSize),
y: ~~(e.offsetY / unitSize)
}
})
$el.on('dragend', function(e) {
e.originalEvent.preventDefault()
$(this).removeClass('dragging')
hideGridGuide($gridGuide)
widget.coords = getDragCoords(e, $root, widget, dm.unitSize, dragCoordOffset)
update()
})
let lastFire = 0
let last = { x: null, y: null }
$root.on('dragover', function(e) {
const now = Date.now()
// Debounce. Otherwise this event fires ridiculously often.
if (now - lastFire > 60) {
const coords = getDragCoords(e, $root, widget, dm.unitSize, dragCoordOffset)
const coordsAreDifferent = !(coords.x === last.x && coords.y === last.y)
if (coordsAreDifferent) {
moveGridGuideTo(coordsInPixels(coords, dm), $gridGuide)
last = coords
}
lastFire = now
}
})
}
export default function() {
const widgets = []
const $root = $('#dashboard-widgets')
const $guide = $(`
<div class="dashboard-grid-square">
<div class="dashboard-grid-fill"></div>
</div>`)
$root.append($guide)
const dm = DashMath($root)
function updateWidget(widget) {
const { x, y } = coordsInPixels(widget.coords || { x: 0, y: 0 }, dm)
updateSize(widget)
widget.state.container.style.transform = `translate(${x}px, ${y}px)`
widget.render()
}
function update() {
widgets.forEach(updateWidget)
}
function add(widget) {
const $el = $('<div class="widget-container"><div class="widget-root"></div></div>')
$el.data('instance-id', widget.state.instanceID)
$el.prop('draggable', true)
$root.append($el)
widgets.push(widget)
// console.log(`${widgets.length} widget${widgets.length === 1 ? ' is' : 's are'} loaded`)
setUpEvents($el, $root, widget, dm, update, widgets)
widget.init($el[0])
updateWidget(widget)
}
function updateSize(widget) {
const { container } = widget.state
const unitSize = dm.unitSize
const [w, h] = widget.state.size
.split('x')
.map(n => parseInt(n) * unitSize)
container.width = w
container.height = h
container.style.width = w + 'px'
container.style.height = h + 'px'
}
window.addEventListener('resize', () => {
update()
})
return {
add,
updateSize,
update
}
}
|
import React, { Component } from "react";
import Home from "./contentSections/home";
import Idea from "./contentSections/idea";
import About from "./contentSections/about";
import Contact from "./contentSections/contact";
class Content extends Component {
render() {
return (
<div className="content">
<Home />
<Idea/>
<About/>
<Contact />
</div>
);
}
}
export default Content;
|
const mongoose = require('mongoose');
const patientSchema = new mongoose.Schema({
firstName: {type: String},
lastName: {type: String},
DOB: {type: Date, default: Date.now},
contact: {type: String},
residentAddress: {type: String},
emergencyNo: {type: String}
})
const patient = mongoose.model('patient', patientSchema);
const paymentSchema = new mongoose.Schema({
})
const payment = mongoose.model('payment', paymentSchema)
module.exports = { patient }
|
/*global JSAV, document */
// Written by Cliff Shaffer
// Based on earlier material written by Sushma Mandava and Milen John
// variable xPosition controls the horizonatl position of the visualization
$(document).ready(function() {
//"use strict";
var av_name = "NestedQuery3";
var av = new JSAV(av_name);
var config = ODSA.UTILS.loadConfig({av_name: av_name}),
interpret = config.interpreter, // get the interpreter
code = config.code; // get the code object
// Slide 1
av.umsg(interpret("").bold().big());
var lab1=av.label(interpret("<span style='color:red;'> Loading.........</span>"), {left:150, top: -40 });
lab1.css({"font-weight": "bold", "font-size": 40});
av.step();
av.displayInit();
//slide 2
var lab2=av.label(interpret("<span style='color:red;'> Loading..........</span>"), {left:150, top: -20 });
av.recorded();
});
|
$().ready(function(){
$(validForm());
$(validPassForm());
initHide();
$("li[id='li-info']").click(function(){
if ($("#Comp-UserType").val()=="0"){
showPersonal();
}else {
showCompnay();
}
});
$("li[id='li-pass']").click(function(){
showUpdatePass();
});
$("#save").click(function(){
if(!validForm().form())
return;
$("#user_detail_info").submit();
});
$("#cancel").click(function(){
if ($("#Comp-UserType").val()=="0"){
showPersonal();
}else {
showCompnay();
}
});
$("#btn-pass-update").click(function(){
if(!validPassForm().form())
return;
updatepass();
}
);
$("#btn-pass-cancel").click(function(){
window.location.href="/CXZKVIP/usermanage/personal/show?rand=" + Math.random();
});
$("#update-mobile").click(function(){
window.location.href="/CXZKVIP/usermanage/personal/mobile/show";
});
});
function showUpdatePass(){
$("#personal_info").hide();
$("#pass-update").show();
$("#welcome").hide();
$("#company-info").hide();
}
function showPersonal() {
$("#personal_info").show();
$("#company-info").hide();
$("#pass-update").hide();
$("#welcome").hide();
setPersonReadOnly();
}
function showCompnay(){
$("#personal_info").hide();
$("#company-info").show();
$("#pass-update").hide();
$("#welcome").hide();
setCompnayReadOnly();
if ($("#Comp-UserType").val()=="3") {
$("#notify-msg").text("资料审核中");
}else if ($("#Comp-UserType").val() == "2") {
$("#notify-msg").text("资料不合格,已被拒绝");
}
}
function initHide(){
$("#personal_info").hide();
$("#pass-update").hide();
$("#company-info").hide();
$("#welcome").show();
setCompnayReadOnly();
setPersonReadOnly();
}
function goEdit(){
$("#BANKCARD,#CARDID,#EMAIL,#NICKNAME,#WECHAT,#ADDRESS,#REALNAME").removeAttr("readonly");
$("#edit").hide();
$("#save").show();
$("#cancel").show();
};
function setPersonReadOnly(){
$("#MOBILE,#BANKCARD,#CARDID,#EMAIL,#NICKNAME,#SCORE,#WECHAT,#ADDRESS,#REALNAME").attr("readonly","readonly");
$("#edit").show();
$("#save").hide();
$("#cancel").hide();
};
function setCompnayReadOnly(){
$("#CMOBILE,#BANKCARD,#CARDID,#EMAIL,#COMPNAME,#COMPNUM,#PHONE,#NICKNAME,#SCORE,#WECHAT,#ADDRESS,#REALNAME").attr("readonly","readonly");
};
function updatepass(){
if ($("#PrePASS").val() == $("#PASS").val()){
$("#upPassMsg").text("新密码与旧密码不能相同!");
return;
}
var uid = getCookie('id');
if (uid==''){
alert("cookies 超时");
return;
}
$.ajax({
type: "POST",
async:false,
url: "/CXZKVIP/usermanage/personal/do_updatepass",
data: {USERMANAGE_ID:uid, PREPASSWORD:$("#PrePASS").val(),PASSWORD:$("#PASS").val()},
dataType: "json",
success: function(data){
if (data.IsSuccess == 1){
window.location.href="/CXZKVIP/usermanage/fg/show/result?IsSuccess=1";
}else if (data.IsSuccess == 2){
$("#upPassMsg").text("密码不正确");
}
}
});
};
function getCookie(objName){
var arrStr = document.cookie.split("; ");
for(var i = 0;i < arrStr.length;i ++){
var temp = arrStr[i].split("=");
if(temp[0] == objName){
if(temp.length>1){
return unescape(temp[1]);
}else{
return "";
}
};
}
return "";
}
jQuery.validator.addMethod("regex", function(value, element, param) {
var r = param;
return r.test(value);
}, "填写不正确");
function validForm(){
return $("#user_detail_info").validate({
rules:{
NICKNAME: {
required:true,
rangelength:[3,8],
},
REALNAME:{
required:true,
rangelength:[2,8],
regex:/[^\u0000-\u00FF]/,
},
EMAIL:{
email:true
},
CARDID:{
required:true,
rangelength:[15,18],
regex:/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
}
},
messages: {
NICKNAME: {
required: "请输入昵称",
rangelength: "长度必须为3-8位字符",
},
REALNAME:{
required:"请输入真实姓名",
rangelength:"长度不正确",
regex:"格式不正确"
},
EMAIL:{
email:"邮箱格式不正确"
},
CARDID:{
required:"请输入证件号",
rangelength:"长度不正确",
regex:"身份证格式不正确",
}
},
errorElement: "em"
});
}
function validPassForm(){
return $("#pass_form").validate({
rules:{
PrePASS:{
required:true,
minlength:6
},
PASS:{
required:true,
minlength:6
},
RePASS:{
required:true,
equalTo:"#PASS"
}
},
messages: {
PrePASS:{
required:"请输入原密码",
minlength:"密码长度不少于6"
},
PASS:{
required:"请输入原密码",
minlength:"密码长度不少于6"
},
RePASS:{
required:"请输入确认密码",
equalTo:"两次密码不同"
}
},
errorElement: "em"
});
}
|
/**
* Copyright (c) Benjamin Ansbach - all rights reserved.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
const P_CODE = Symbol('code');
const P_MESSAGE = Symbol('message');
class ResultError {
constructor(code, message) {
this[P_CODE] = code;
this[P_MESSAGE] = message;
}
get code() {
return this[P_CODE];
}
get message() {
return this[P_MESSAGE];
}
}
module.exports = ResultError;
|
module.exports = {
theme: {
extend: {
spacing: {
'80': '70vh',
},
container: {
center: true,
},
colors: {
primaryColor: '#003366',
secondaryColor: '#777777',
thirdColor: '#D6A419'
},
fontFamily: {
'body': ['Playfair Display', 'serif'],
}
},
},
variants: {},
plugins: []
}
|
const Promise = require("bluebird");
const stringify = Promise.promisify(require("csv-stringify"));
const writeFile = Promise.promisify(require("fs").writeFile);
class Output {
writeContents(args){
return this.write(args);
}
}
class CSVWrite extends Output{
constructor(content, csvFile){
super();
this.content = content;
this.csvFile = csvFile;
}
write(){
return stringify(this.content)
.then(res => writeFile(this.csvFile, res, {flag: 'w'}).bind(this));
}
}
module.exports = CSVWrite;
|
(function(){
var root=this;
var UI = {};
var AlertFieldType = {
Boolean: "boolean",
String: "string",
Number: "number",
Select: "select"
};
UI.AlertFieldType = AlertFieldType;
UI.showAlert = function(alert) {
var window=COSAlertWindow.new();
if(alert.icon) {
// var iconFilePath=sketch.scriptPath.stringByDeletingLastPathComponent()+alert.icon;
// var icon = NSImage.alloc().initByReferencingFile(iconFilePath);
var icon=fs.image(alert.icon);
window.setIcon(icon);
}
var index=0;
if(isDefined(alert.title)) window.setMessageText(alert.title);
if(isDefined(alert.description)) window.setInformativeText(alert.description);
function isDefined(obj) {
return !isUndefined(obj);
}
function isUndefined(obj) {
return obj === void 0;
}
function createComboBox(items, selectedItemIndex) {
selectedItemIndex = selectedItemIndex || 0
var comboBox = NSComboBox.alloc().initWithFrame(NSMakeRect(0, 0, 300, 25));
comboBox.addItemsWithObjectValues(items);
comboBox.selectItemAtIndex(selectedItemIndex);
return comboBox;
}
var firstResponderView=null;
// Process fields.
for(var key in alert.fields) {
var field=alert.fields[key];
if(isDefined(field.label) && !(field.control && field.control=="checkbox")) {
window.addTextLabelWithValue(field.label);
index+=1;
}
if(isDefined(field.type) && field.type==AlertFieldType.Select) {
var selectedItem=0;
for(var i=0;i<field.value.length;i++) {
if(field.value[i]==field.defaultValue) {
selectedItem=i;
break;
}
}
window.addAccessoryView(createComboBox(field.value,selectedItem));
if(isUndefined(field.getter)){
field.getter = function(value) {
return value;
};
}
}
if(isDefined(field.type) && field.type==AlertFieldType.Boolean) {
if(isUndefined(field.trueValue)) field.trueValue="Yes";
if(isUndefined(field.falseValue)) field.falseValue="No";
function createCheckbox(checked) {
var myCheckBox = [[NSButton alloc] initWithFrame:NSMakeRect(0,0,300,25)];
[myCheckBox setButtonType:NSSwitchButton];
myCheckBox.setTitle(field.label);
myCheckBox.setState(NSOnState);
[myCheckBox setBezelStyle:0]; // This is unnecessary. I include it to show that checkboxes don't have a bezel style.
return myCheckBox;
}
function createControl() {
if(isUndefined(field.control)) field.control="combo";
if(field.control.toLowerCase()=="combo") return createComboBox([field.trueValue,field.falseValue],(field.value) ? 0 : 1);
if(field.control.toLowerCase()=="checkbox") return createCheckbox(field.value);
}
window.addAccessoryView(createControl());
if(isUndefined(field.getter)){
field.getter = function(value) {
value=value.toLocaleString();
var trues=["yes","true","1",field.trueValue];
for(var i=0;i<trues.length;i++) {
if(value==trues[i]) {
return true;
}
}
return false;
};
}
}
if(isDefined(field.type) && field.type==AlertFieldType.String)
{
window.addTextFieldWithValue(isDefined(field.value) ? field.value : "");
if(field.placeholder) {
var fieldView=window.views().lastObject();
fieldView.setPlaceholderString(field.placeholder);
}
if(field.firstResponder) {
var view=window.views().lastObject();
// window.alert().window().setInitialFirstResponder(view);
window.alert().window().makeFirstResponder(view);
}
}
field["$Index"]=index;
index+=1;
}
for(var i=0;i<alert.buttons.length;i++) {
var button=alert.buttons[i];
window.addButtonWithTitle(button.title);
}
var response=window.runModal();
// Post-process fields.
var data = {};
for(var key in alert.fields) {
var field=alert.fields[key];
var value=window.viewAtIndex(field["$Index"]).stringValue().UTF8String();
if(field.type == AlertFieldType.Select) {
var index=window.viewAtIndex(field["$Index"]).indexOfSelectedItem();
data[key]=(isUndefined(field.getter)) ? value : field.getter(value,index);
} else {
data[key]=(isUndefined(field.getter)) ? value : field.getter(value);
}
}
var inx=((parseInt(response)-1000));
if(alert.buttons[inx].onClick) {
alert.buttons[inx].onClick(data);
}
};
root.UI = UI;
}).call(this);
|
// Cuando una función recibe un callback no es más que una función
// que se va a ejecutar después en cierto punto del tiempo
const getUsuarioById = ( id, callback ) => {
const usuario = {
id,
nombre: 'Oswaldo'
}
// setTimeout() es una función que ejecuta un callback en cierto momento del tiempo
setTimeout(() => {
callback( usuario );
}, 1000);
}
getUsuarioById( 10, ( usuario ) => {
console.log( usuario.id );
console.log( usuario.nombre.toUpperCase() );
});
|
angular.module('ngApp.common', ['pascalprecht.translate'])
.factory("SessionService", function ($window, $state) {
function setUser(userInfo) {
$window.sessionStorage["userInfo"] = JSON.stringify(userInfo);
}
function getUser(userInfo) {
return $window.sessionStorage["userInfo"] ? JSON.parse($window.sessionStorage["userInfo"]) : undefined;
}
function removeUser() {
$window.sessionStorage.removeItem("userInfo");
}
function setLanguage(lang) {
$window.sessionStorage["language"] = lang;
}
function getLanguage() {
return $window.sessionStorage["language"] ? $window.sessionStorage["language"] : 'en';
}
function getScreenHeight() {
var screenHeight = null;
screenHeight = $window.outerHeight;
if (screenHeight < 601) {
return 360;
}
else if (screenHeight < 769 && screenHeight > 600) {
return 402;
}
else if (screenHeight < 801 && screenHeight > 768) {
return 462;
}
else if (screenHeight < 901 && screenHeight > 800) {
return 520;
}
else if (screenHeight < 1051 && screenHeight > 900) {
return 588;
}
else if (screenHeight < 1081 && screenHeight > 1050) {
return 750;
}
else if (screenHeight < 1201 && screenHeight > 1080) {
return 820;
}
else {
return 402;
}
}
function windowUnload(evt) {
if ($state.current.name === 'customer.booking-home.eCommerce-booking' ||
$state.current.name === 'admin.booking-home.direct-booking' ||
$state.current.name === 'customer.booking-home.direct-booking' ||
$state.current.name === 'admin.booking-home.direct-booking' ||
$state.current.name === 'dbuser.booking-home.direct-booking') {
var message = 'Are you sure you want to leave?';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}
else {
}
}
return {
setUser: setUser,
getUser: getUser,
removeUser: removeUser,
getScreenHeight: getScreenHeight,
setLanguage: setLanguage,
getLanguage: getLanguage,
windowUnload: windowUnload
};
})
.factory("Spinner", function () {
function show(userInfo) {
document.getElementById('loader').style.display = 'block';
}
function hide(userInfo) {
document.getElementById('loader').style.display = 'none';
}
return {
show: show,
hide: hide
};
})
.filter('timeStampFilter', function () {
return function (value) {
var localTime = moment.utc(value).toDate();
localTime = moment(localTime).format('LT');
return localTime;
};
})
.filter('dateFilter', function () {
return function (value) {
if (value === undefined || value === null) {
return '';
}
else {
var localTime = moment.utc(value).toDate();
localTime = moment(localTime).format('DD/MM/YYYY');
return localTime;
}
};
})
.filter('shortTimeFilter', function () {
return function (value) {
if (value === undefined || value === null) {
return '';
}
else {
var hh = value.substring(0, 2);
var mm = value.substring(2, 4);
return hh + ':' + mm;
}
};
});
|
import React from 'react';
import BaseButton from '@material-ui/core/Button';
const Button = (props) => {
return (
<BaseButton {...props} style={{
borderRadius: '5rem',
paddingLeft: '1.8rem',
paddingRight: '1.8rem',
paddingTop: '0.5rem',
paddingBottom: '0.5rem',
...props.style
}} />
)
}
export default Button;
|
import React, { useState } from "react";
import RacingBarChart from "./RacingBarChart";
import useInterval from "./useInterval";
const getRandomIndex = array => {
return Math.floor(array.length * Math.random());
};
const getRandomnumber = () => {
return Math.floor(Math.random() * (20 - 10 + 1)) + 10;
};
function RacingBarChartData() {
const [iteration, setIteration] = useState(0);
const [start, setStart] = useState(false);
const [data, setData] = useState([{
name: "A",
value: 10,
color: "#f4efd3"
},
{
name: "B",
value: 15,
color: "#cccccc"
},
{
name: "C",
value: 20,
color: "#c2b0c9"
},
{
name: "D",
value: 25,
color: "#9656a1"
},
{
name: "E",
value: 30,
color: "#fa697c"
},
{
name: "F",
value: 35,
color: "#fcc169"
}
]);
useInterval(() => {
if (start) {
const randomIndex = getRandomIndex(data);
setData(
data.map((entry, index) =>
index === randomIndex ?
{
...entry,
value: entry.value + getRandomnumber()
} :
entry
)
);
setIteration(iteration + 1);
}
}, 300);
return (
<div className={'Chart'}>
<RacingBarChart data={data} />
< button onClick={() => setStart(!start)} > {start ? "Stop" : "Run"}
</button>
</div>
);
}
export default RacingBarChartData;
|
/* Directive is not isolated, but it also doesn't use parents scope so we can isolated it if we want */
var tokki = angular.module("directives").directive("searchDtes", ["$modal",
function($modal){
return {
restrict: "E",
templateUrl: "components/searchDtes/searchDtes.html",
link: function(scope, ele, attr){
var modal = $modal({scope: scope, templateUrl: 'components/searchDtes/form.html', show: false});
ele.on("click touchstart", function(){
modal.$promise.then(modal.show);
});
},
}
}
])
|
import React, {Component} from 'react';
import {connect} from 'react-redux';
import {test} from './action';
import './test.scss';
class Test extends Component{
constructor(props){
super(props);
//this.click = this.click.bind(this);
this.state = {
value: ''
}
}
click = ()=>{
this.props.dispatch(test(this.state.value));
}
change = (event) => {
this.setState({
value: event.target.value
});
}
render(){
return (
<div className="test">
<div style={{color:'red'}}>{this.props.text}</div>
<p>{this.props.data || '显示输入内容'}</p>
<input type="text" value={this.state.value} onChange={this.change}/>
<input type="button" onClick={this.click} value="button"/>
</div>
)
}
}
function mapStateToProps(state, ownprops) {
return {
text: state.testStroe.test,
data: state.testStroe.data,
}
}
function mapDispatchToProps(dispatch, ownprops) {//使用此函数会拦截 dispatch
return {
}
}
export default connect(mapStateToProps)(Test);
|
document.write(" <link rel=\"stylesheet\" href=\"assets/js/jquery/jquery/jquery_ui_dialog/jquery-ui_pop.css\" />");
document.write("<script src=\"assets/js/jquery/jquery/jquery_ui_dialog/jquery-1.9.1.js\"></script>");
document.write("<script src=\"assets/js/jquery/jquery/jquery_ui_dialog/jquery-ui.js\"></script>");
document.write("<link rel=\"stylesheet\" href=\"assets/css/overlay/button.css\">");
document.write("<link rel=\"stylesheet\" href=\"assets/css/overlay/plug.css\">");
document.write("<link rel=\"stylesheet\" href=\"assets/css/overlay/table.css\">");
document.write("<link rel=\"stylesheet\" href=\"assets/css/overlay/overlay.css\">");
document.write("<link rel=\"stylesheet\" href=\"assets/css/overlay/new_member.css\">");
document.write("<link rel=\"stylesheet\" href=\"assets/css/overlay/order_search.css\">");
document.write("<link rel=\"stylesheet\" href=\"assets/css/overlay/payment.css\">");
|
//number of ingrédients:
ingr = 0;
//number of steps:
stp = 0;
$(document).ready(function() {
$('.tabs').each(function(){
$(this).find('.tab-content').hide();
$($(this).find('ul li.active a').attr('href')).show();
$(this).find('ul li a').click(function() {
$(this).parents('.tabs').find('.tab-content').hide();
$($(this).attr('href')).fadeIn(1200);
$(this).parent().addClass('active').siblings().removeClass('active');
return false;
});
});
$('.recipes-details').each(function(){
$(this).find('.mode-cuisine-content').hide();
$(this).find('.mode-cuisine-button a').click(function() {
$($(this).attr('href')).slideToggle();
if ($(this).html() == "Cacher le mode-cuisine")
{
$(this).html("Afficher le mode-cuisine");
}
else
{
$(this).html("Cacher le mode-cuisine");
}
return false;
});
});
$('.tabs-body').each(function() {
$(this).find('.recipe-description').hide();
$($(this).find('.recipe-img')).mouseover(function(){
var totalHeight = $(this).height() - ($(this).height() * 0.05);
var titleHeight = $(this).find('h5').height() + 45;
var heightFinal = totalHeight - titleHeight;
$(this).find('.recipe-description').attr("style", "height: " + heightFinal +"px;");
});
$($(this).find('.recipe-img')).mouseout(function(){
$(this).find('.recipe-description').hide();
});
});
setTimeout(function() {
$('div.alert').fadeOut('300');
}, 2700);
$("ul.notes-echelle").addClass("js");
// On passe chaque note à l'état grisé par défaut
$("ul.notes-echelle li").addClass("note-off");
// Au survol de chaque note à la souris
$("ul.notes-echelle li").mouseover(function() {
// On passe les notes supérieures à l'état inactif (par défaut)
$(this).nextAll("li").addClass("note-off");
// On passe les notes inférieures à l'état actif
$(this).prevAll("li").removeClass("note-off");
// On passe la note survolée à l'état actif (par défaut)
$(this).removeClass("note-off");
});
// Lorsque l'on sort du sytème de notation à la souris
$("ul.notes-echelle").mouseout(function() {
// On passe toutes les notes à l'état inactif
$(this).children("li").addClass("note-off");
// On simule (trigger) un mouseover sur la note cochée s'il y a lieu
$(this).find("li input:checked").parent("li").trigger("mouseover");
});
});
function add_ingredient(ingr)
{
var ing = document.getElementsByName("ingr["+ ingr +"]")[0].value;
if(ing == "") {
alert('L\'ingrédient est nul et ne peut pas rester vide !! Veuillez introduire un ingrédient');
} else {
ingr++;
$('#form_ing'+ (ingr - 1)).after(
"<div id=\"form_ing"+ ingr + "\" class=\"form-group\">" +
"<div class='col-md-12'>" +
"<div class='col-md-1 ing-row'>" +
"<input name=\"quan[" + ingr + "]\" placeholder=\"Quantité\" class=\"form-control input-md\" type=\"text\">" +
"</div>" +
"<div style=\"padding: 0.5rem; float: left\"><p>(de)</p></div><div class=\"col-md-2\">" +
"<input name=\"ingr[" + ingr + "]\" placeholder=\"Ingrédient\" class=\"form-control input-md\" type=\"text\" required>" +
"</div> <div id=\"btn_ing" + ingr + "\" style=\"padding: 0.5rem; float: left\">" +
"<a onclick=\"add_ingredient("+ ingr+")\" class=\"btn btn-sm btn-info\"><span class=\"glyphicon glyphicon-plus\" style=\"padding-bottom: 3px;\">" +
"</span></a></div></div></div>"
);
$('#btn_ing' + (ingr - 1)).remove();
}
}
function add_step(stp)
{
var step_text = document.getElementsByName("step["+ stp +"]")[0].value;
if(step_text == "") {
alert('L\'étape est nul et ne peut pas rester vide !! Veuillez décrire l\'étape');
} else {
stp++;
$('#form_step'+ (stp - 1)).after(
"<div id=\"form_step"+ stp +"\" class=\"form-group\">" +
"<label class=\"col-md-4 control-label\">Étape "+ (stp + 1) +" :</label>" +
"<div class=\"col-md-3 steps\">" +
"<textarea name=\"step["+ stp +"]\" placeholder=\"Entrer l'étape de la recette ...\" class=\"form-control\" required></textarea>" +
"</div><div id=\"btn_stp"+ stp +"\" style=\"padding: 0.5rem; float: left\">" +
"<a onclick=\"add_step("+ stp +")\" class=\"btn btn-sm btn-info\"><span class=\"glyphicon glyphicon-plus\" style=\"padding-bottom: 3px;\"></span></a>" +
"</div></div>"
);
$('#btn_stp' + (stp - 1)).remove();
}
}
|
let pokemons = [{
name: 'Pikachu',
imgSrc: '0000779_mgka-igruka-pokemon-pikau-20-sm.png'
},
{
name: 'Bulbasaur',
imgSrc: '1891758-001bulbasaur.png'
},
{
name: 'Grookey',
imgSrc: 'CI_NSwitch_PokemonSwordShield_Grookey_image500w.png'
},
{
name: 'Eevee',
imgSrc: 'char-eevee.png'
},
{
name: 'Cubone',
imgSrc: '104.png'
},
{
name: 'Charizard',
imgSrc: '006.png'
},
{
name: 'Raichu',
imgSrc: '1898248-026raichu.png'
},
{
name: 'Turtwig',
imgSrc: '387Turtwig.0.png'
},
{
name: 'Squirtle',
imgSrc: '007.png'
},
{
name: 'Quagsire',
imgSrc: '195.png'
},
{
name: 'Charmander',
imgSrc: '004.png'
},
{
name: 'Panseras',
imgSrc: '513.png'
},
{
name: 'Marowak',
imgSrc: '105.png'
},
{
name: 'Meowth',
imgSrc: 'pokemon_meowth.png'
},
{
name: 'Jigglypuff',
imgSrc: '039Jigglypuff.png'
},
{
name: 'Wigglytuff',
imgSrc: '040.png'
},
{
name: 'Vaporeon',
imgSrc: '134-Vaporeon.png'
},
{
name: 'Marshtomp',
imgSrc: '259.png'
},
{
name: 'Riolu',
imgSrc: 'Riolu-Pokemon-Go.png'
},
{
name: 'Rowlet',
imgSrc: '722Rowlet.png'
},
{
name: 'Entei',
imgSrc: 'Entei.png'
},
{
name: 'Espeon',
imgSrc: '196.png'
},
{
name: 'Mewtwo',
imgSrc: '250px-150Mewtwo.png'
},
{
name: 'Azelf',
imgSrc: 'Azelf-Pokemon-Go.png'
},
{
name: 'Shinx',
imgSrc: '403.png'
},
{
name: 'Machamp',
imgSrc: '68-Machamp.png'
},
{
name: 'Aerodactyl',
imgSrc: '1123.png'
},
{
name: 'Luxio',
imgSrc: 'Luxio-Pokemon-Go.png'
},
{
name: 'Arceus',
imgSrc: 'poke-arceus-03f79.webp'
},
{
name: 'Dugtrio',
imgSrc: 'Dugtrio.png'
},
{
name: 'Psyduck',
imgSrc: 'Pokémon_Psyduck_art.png'
},
{
name: 'Vulpix',
imgSrc: '1891638-037vulpix.png'
},
{
name: 'Squirtle',
imgSrc: 'pokemon-hd-png-007squirtle-pokemon-mystery-dungeon-explorers-of-sky-png-1185.png'
},
{
name: 'Piplup',
imgSrc: 'pokemon_PNG85.png'
},
{
name: 'Mew',
imgSrc: '250px-151Mew.png'
},
{
name: 'Translucent',
imgSrc: 'pokemon-clipart-translucent-1.png'
},
{
name: 'Absol',
imgSrc: '5859611e4f6ae202fedf2859.png'
},
{
name: 'Zacian',
imgSrc: 'home-char-sword.png'
},
{
name: 'Croconaw',
imgSrc: '159.png'
},
{
name: 'Chikorita',
imgSrc: 'pokemon_PNG46.png'
},
{
name: 'Manaphy',
imgSrc: 'd2exn8i-084867d9-7d2e-4837-b411-8ca40df5b3d5.png'
},
{
name: 'Leafeon',
imgSrc: '470.png'
},
{
name: 'Fennekin',
imgSrc: 'pokemon_PNG159.png'
},
{
name: 'Ludicolo',
imgSrc: 'Ludicolo-Pokemon-Go.png'
},
{
name: 'Cyndaquil',
imgSrc: 'Cyndaquil.png'
},
{
name: 'Blissey',
imgSrc: '242-blissey.png'
},
{
name: 'Onix',
imgSrc: '1891842-095onix.png'
},
{
name: 'Magneton',
imgSrc: 'dd6fhk2-d96d9275-32f0-41db-98fd-3e91f06c7e4c.png'
},
{
name: 'Magikarp',
imgSrc: '129.png'
},
{
name: 'Dewgong',
imgSrc: 'Dewgong.png'
},
{
name: 'Popplio',
imgSrc: '728.png'
},
{
name: 'Zeraora',
imgSrc: '807.png'
},
{
name: 'Archeops',
imgSrc: 'Archeops.png'
},
{
name: 'Tyrantrum',
imgSrc: 'Tyrantrum-tyrantrum-35928437-841-949.png'
},
{
name: 'Zangoose',
imgSrc: 'enhanced-19010-1552779587-1.webp'
}
];
|
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
email: {
type: String,
match: /^\S+@\S+\.\S+$/,
required: true,
unique: true,
trim: true,
},
name: {
type: String,
maxlength: 128,
index: true,
trim: true,
},
mobile: {
type: String,
length: 10,
index: true,
trim: true,
},
address: {
type: String,
trim: true,
},
}, {
timestamps: true,
});
const userModule = mongoose.model('users', userSchema);
module.exports = userModule;
|
import React from 'react';
import { ProductConsumer } from '../context';
import { Link } from 'react-router-dom';
import { Modal } from 'react-bootstrap';
function MyModal() {
return (
<ProductConsumer>
{value => {
const { modalOpen, closeModal } = value;
const { title, img, price } = value.modalProduct;
return (
<>
<Modal
size="sm"
show={modalOpen}
onHide={closeModal}
centered
>
<div className="modal-header text-uppercase text-center d-block">
<h5>добавлено в корзину</h5>
</div>
<div className="modal-body">
<div className="container text-center">
<div className="modal_pic_wrapper">
<img
loading="lazy"
className="card-img-top"
src={img}
alt="изображение_лота"
/>
</div>
<div className="text-center">
<p>{title}</p>
<h5>{price} ₽</h5>
</div>
</div>
</div>
<div className=" modal-footer d-flex justify-content-center">
<Link to="/products">
<button className="btn btn-success mx-2 modal_button" onClick={() => {closeModal()}}>
Продолжить покупки
</button>
</Link>
<Link to="/cart">
<button className="btn btn-primary mx-2 modal_button" onClick={() => {closeModal()}}>
Перейти в <i className="fas fa-shopping-basket fa-lg"></i>
</button>
</Link>
</div>
</Modal>
</>
);
}}
</ProductConsumer>
);
}
export default MyModal;
|
function shiftToRight(x, y) {
return Math.floor(x / 2 ** y);
}
const result = shiftToRight(4666, 6);
console.log(result);
// shiftToRight(80, 3) ➞ 10
// shiftToRight(-24, 2) ➞ -6
// shiftToRight(-5, 1) ➞ -3
// shiftToRight(4666, 6) ➞ 72
// shiftToRight(3777, 6) ➞ 59
// shiftToRight(-512, 10) ➞ -1
|
Backbone.Router.prototype._swapView = function (newView, callback) {
newView.hide(function () {
this._currentView = newView;
this.$rootEl = this.$rootEl || $('<div>').appendTo($('body'));
this.$rootEl.empty().append(newView.$el);
newView.render().show(callback, 200);
}.bind(this), 200);
};
|
import React, { Component } from 'react';
import {Link} from "react-router-dom";
import {
WraperHeader,
HeaderFenli,
Fenli,
IconTag,
SearchBar,
Inpu ,
KeFu,
IconTags,
Searc
} from "./style.js";
class Header extends Component{
render(){
var styled = {
display:"contents"
}
return(
<WraperHeader>
<Link to="/deatil" style={styled}>
<HeaderFenli>
<Fenli>
<IconTag className="head_icon"></IconTag>分类
</Fenli>
</HeaderFenli>
</Link>
<SearchBar>
<Inpu></Inpu>
<Searc className="search"></Searc>
</SearchBar>
<KeFu>
<Fenli>
<IconTags className="kefu_icon"></IconTags>客服
</Fenli>
</KeFu>
</WraperHeader>
);
}
}
export default Header;
|
//Copyright 2012, John Wilson, Brighton Sussex UK. Licensed under the BSD License. See licence.txt
// An ObserverEvent object is responsible for deciding if an event is triggered.
// tiPoint is duration in seconds the moveable object has to be in the hotspot for.
// eventCh is the % (0-100) chance of the event actually being triggered
// tFunction is the callback function in the event that the event is triggered.
// optCond is optional boolean callback function which needs to return true if event attempts to trigger.
// limit [optional] is the number of times the event can happen
// backoff is the duration in seconds that a next possible event will be held back for
// before testing again.
// rGen is an optional random number generator.
// Johnny - June 2012
function ObserverEventRandom(start,end)
{
return start+Math.random()*(end-start) ;
}
function ObserverEvent(tiPoint,eventCh,tFunction,optCond,limit,backoff,rGen)
{
this.triggerPoint = tiPoint ;
this.eventChance = eventCh ;
this.makeitso = tFunction ;
this.triggered = false ;
this.count = 0 ;
this.limit = limit ;
this.backoff = backoff ;
this.rGen = rGen || ObserverEventRandom ;
this.optCondition = optCond ;
this.className = "ObserverEvent" ;
}
ObserverEvent.Create = function(tiPoint,eventCh,tFunction,optCond,limit,backoff,rGen)
{
return new ObserverEvent(tiPoint,eventCh,tFunction,optCond,limit,backoff,rGen) ;
}
function _debugPrint(s)
{
}
ObserverEvent.prototype = {
constructor: ObserverEvent,
ObjectOutside: function()
{
_debugPrint("RESET STATE "+this.className)
this.triggered = false
},
Inform: function(obj,isinside,ctime,timein,timeout)
{
if (timein > this.triggerPoint && !this.triggered && (!this.optCondition || this.optCondition())
&& (!this.limit || this.count < this.limit)
&& (!this.backoff || (!this.lasttime || ctime - this.lasttime > this.backoff)))
{
this.triggered = true
_debugPrint("Throwing Dice")
if (this.rGen(0,100) < this.eventChance)
{
if (this.makeitso)
{
this.makeitso(obj)
this.count = this.count + 1
this.lasttime = ctime
}
}
else
{
_debugPrint("Dice - says no!")
}
}
},
toString: function()
{
return "ObserverEvent" ;
}
}
|
/* Gulp and plugins */
var gulp = require('gulp');
var concat = require('gulp-concat');
var minify = require('gulp-minify');
var imagemin = require('gulp-imagemin');
var shell = require('gulp-shell');
//var sourcemaps = require('gulp-sourcemaps');
// var uglify = require('gulp-uglify');
// var rename = require('gulp-rename');
/* External libraries to be bundled */
var jquery = './node_modules/jquery/dist/jquery.min.js';
var bootstrap = './node_modules/bootstrap/dist/js/bootstrap.bundle.min.js';
var touchswipe = './node_modules/jquery-touchswipe/jquery.touchSwipe.min.js';
var slick = './node_modules/slick-carousel/slick/slick.min.js';
// var jqueryUi = './assets/js/jquery-ui.min.js';
var vivus = './node_modules/vivus/dist/vivus.min.js';
var extLibs = [jquery, bootstrap, touchswipe, slick, vivus];
/* Gulp tasks */
// Startup task
gulp.task('sass', shell.task('sass --watch assets/sass:assets/css'));
gulp.task('jekyll', shell.task('jekyll serve --watch'));
gulp.task('code', shell.task('code .'));
gulp.task('start', gulp.parallel('sass', 'jekyll', 'code'));
// Concatenate and minify external js
gulp.task('get-ext-js', function() {
return gulp.src(extLibs)
.pipe(concat('ext.js'))
.pipe(minify({
ext: {
src: '.js',
min: '.min.js'
}
}))
.pipe(gulp.dest('./assets/js'));
});
// Minify my own files and images
gulp.task('minify-js', function() {
return gulp.src('assets/js/*.js')
.pipe(minify({
ext: {
src: '.js',
min: '.min.js'
},
ignoreFiles: ['*.min.js']
}))
.pipe(gulp.dest('assets/js'));
});
gulp.task('minify-images', function() {
return gulp.src('assets/img_raw/*')
.pipe(imagemin())
.pipe(gulp.dest('assets/img'));
});
|
var map = function(){
var key = this.actiontype + this.user._id;
var value;
if(this.actiontype != 'purchase'){
value = {
p100: this.price >= 100? 1 : 0,
p50: this.price >= 50? 1 : 0,
view:0
};
}else{
value = {
view: 1,
p100: 0,
p50: 0
};
}
emit( key, value );
}
var reduce = function(key, values){
var reducedObject;
if(key[0] == 'p'){
reducedObject = {
nump100: 0,
nump50: 0
}
values.forEach(function(value){
reducedObject.nump100 = reducedObject.nump100 + value.p100;
reducedObject.nump50 = reducedObject.nump50 + value.p50;
});
}else{
reducedObject = {
totalview: 0
}
reducedObject.totalview = values.length;
}
return reducedObject;
}
db.actions.mapReduce(
map,
reduce,
{
out: "haha"
}
)
|
var data = require("../data.json");
exports.editBudget = function(request, response) {
var budget = request.query.budget;
var savings = request.query.savings;
//edit value to most recent (budget)
data.budget[0] = budget;
//edit value to most recent (percentage of savings)
data.savings[0] = savings;
//edit value to most recent (savings)
var save = data.budget[0] * (data.savings[0]/100);
data.save[0] = save.toFixed(2);
//render changes
response.render('budget', data);
}
|
import React from 'react';
import Paper from '@material-ui/core/Paper';
import Grid from '@material-ui/core/Grid';
import '../styles/grid.scss'
import EventCard from './eventCard';
const CenteredGrid=(props)=>{
if(props){
return (
<div className="root">
<Grid container spacing={3}>
{props.eventData.map((event,index)=>(
<Grid key={index} item md={4} xs={12} >
<Paper className="paper"><EventCard event={event} ></EventCard></Paper>
</Grid>
))}
</Grid>
</div>
);}
else{
console.log(props.length)
return (
<div>
{/* nothing */}
</div>
)
}
}
export default CenteredGrid;
|
// var expect = require('chai').expect;
var request = require('request');
var server = require('../index');
const chai = require("chai");
const chaiHttp = require("chai-http");
const { expect } = chai;
chai.use(chaiHttp);
describe('Local', () => {
it ('Home page local', (done) => {
request('http://localhost:3030', (err, response, body) => {
expect(body).to.equal('{"info":"HOME"}');
done();
})
})
it ('Investors page local', (done) => {
request('http://localhost:3030/investors', (err, response, body) => {
expect(response.statusCode).to.equal(200);
done();
})
})
describe('/POST Validation', () => {
it('it should not POST an investor with address longer than 50 symbols', (done) => {
done();
});
});
})
describe('Remote', () => {
it ('Home page remote', (done) => {
request('https://parallelm.herokuapp.com', (err, response, body) => {
expect(body).to.equal('{"info":"HOME"}');
done();
})
})
})
|
// Main.js used to run and test functions
var firebase = require("../firebase/config");
require("firebase/auth");
var login = require("../model/account/LogIn");
var signup = require("../model/account/SignUp");
var Users = require("../model/Users");
async function main() {
var current_user;
current_user = await signup.SignupAPI.registerUser(
"evanjs2000@gmail.com",
"password11"
);
//current_user = await login.LoginAPI.loginUser("evanjserrano@gmail.com", "password");
console.log(current_user.uid);
Users.UsersAPI.createNewUser(current_user).then(() => console.log("Created"));
Users.UsersAPI.updateUserProfile(
current_user,
"evantwo",
"Evan2",
"Serrano "
).then(() => console.log("Updated"));
}
async function main2() {
var current_user;
current_user = await login.LoginAPI.loginUser(
"evanjserrano@gmail.com",
"password"
);
console.log(current_user.uid);
Users.UsersAPI.getUserProfile(current_user).then((data) => console.log(data));
//console.log(":(");
//console.log(JSON.stringify(data));
//
}
async function main3() {
current_user = await login.LoginAPI.loginUser(
"evanjs2000@gmail.com",
"password11"
);
console.log(current_user.uid);
Users.UsersAPI.getUserProfile(current_user).then((data) => console.log(data));
}
async function main4() {
await main2();
await main3();
console.log(firebase.auth().currentUser.uid);
}
//main();
main4();
|
import React, { useContext, useEffect, useState } from "react";
import Sidebar from "../../../Shared/Sidebar/Sidebar";
import { UserContext } from "../../../../App";
import "./Bookinglist.css";
const Bookinglist = () => {
const [loggedInUser, setLoggedInUser] = useContext(UserContext);
const { name, email } = { ...loggedInUser };
const [bookings, setbookings] = useState([]);
useEffect(() => {
fetch("http://localhost:4000/orderDetail?email=" + loggedInUser.email)
.then((res) => res.json())
.then((data) => {
setbookings(data);
console.log(data);
});
}, []);
return (
<div>
<Sidebar></Sidebar>
<div className="main">
<div className="header">
<h1>Your Bookings</h1>
</div>
</div>
<div className="container checkout">
<table className="table table-striped table-hover shadow mt-5 mb-3 bg-body rounded table-bordered border-primary bookingList">
<thead>
<tr>
<th>Customer Name</th>
<th>Email</th>
<th>Total Booking</th>
</tr>
</thead>
<tbody>
<tr>
<td scope="row">{name}</td>
<td>{email}</td>
<td>{bookings.length}</td>
</tr>
</tbody>
</table>
</div>
{/* Card */}
<div className="container bookingListDetail">
<div class="row row-cols-1 row-cols-md-3 g-4 mt-3 ">
{bookings.map((booking) => (
<div class="col">
<div class="card h-100">
<button class="btn btn-success bookingButton">
<span>{booking.status}</span>
</button>
<div class="card-body">
<p class="card-title">
<strong>
{new Date(booking.orderTime).toDateString("dd/MM/yyyy")}
</strong>
</p>
<h5>
<strong>{booking.serviceInfo.device}</strong>
</h5>
<p class="card-text">{booking.serviceInfo.description}</p>
</div>
</div>
</div>
))}
</div>
</div>
</div>
);
};
export default Bookinglist;
|
import config from './config'
export default class EditorAction {
constructor(editor, adorsList) {
this.editorClass = editor
this.adorsArr = adorsList
this.textArea = $(editor.htmlContainer).find('textarea')
this.codeMirror = null
this.textArea.on('froalaEditor.commands.after', (e, editor, cmd, param1, param2) => {
if (cmd == 'html' && editor.codeView.isActive()) {
this.codeMirror = editor.$box.find(".CodeMirror")[0].CodeMirror;
}
})
}
editorInitEditor(editor, t) {
editor.$el
.on('dragenter', config.allowDrop, (e) => $(e.target).addClass('drag-over'))
.on('dragleave', config.allowDrop, (e) => $(e.target).removeClass('drag-over'))
editor.events.on('drop', (dropEvent) => t.onDrop(editor, dropEvent), true)
}
onBlockClick(block) {
if (this.textArea.froalaEditor('codeView.isActive')) {
const pos = this.codeMirror.doc.getCursor()
this.codeMirror.doc.replaceRange(block.html, pos);
} else {
this.textArea.froalaEditor('undo.saveStep');
this.textArea.froalaEditor('html.insert', block.html, false);
this.textArea.froalaEditor('undo.saveStep');
}
}
onAdoorClick(ador) {
if (this.textArea.froalaEditor('codeView.isActive')) {
const pos = this.codeMirror.doc.getCursor()
this.codeMirror.doc.replaceRange(`${ador.propertyName}="${ador.html}"`, pos);
} else {
this.textArea.froalaEditor('undo.saveStep');
this.textArea.froalaEditor('html.insert', ador.html, false);
this.textArea.froalaEditor('undo.saveStep');
}
}
onDrop(editor, dropEvent) {
editor.markers.insertAtPoint(dropEvent.originalEvent);
var $marker = editor.$el.find('.fr-marker');
$marker.replaceWith($.FroalaEditor.MARKERS);
editor.selection.restore();
// Save into undo stack the current position.
if (!editor.undo.canDo()) {
editor.undo.saveStep();
}
const data = dropEvent.originalEvent.dataTransfer.getData('Text')
if (!data) {
return true;
}
editor.$el.find('.drag-over').removeClass('drag-over')
const obj = JSON.parse(data)
if (obj.propertyName) {
const el = $(dropEvent.target)
el.attr(obj.propertyName, obj.html)
} else {
editor.html.insert(obj.html)
}
editor.undo.saveStep();
dropEvent.preventDefault();
dropEvent.stopPropagation();
return false;
}
onCodeViewDrop(e, event, editor) {
editor.selection.restore();
if (this.editorClass.mySideBar._DragElement) {
let obj = JSON.parse(this.editorClass.mySideBar._DragElement)
let pos = this.codeMirror.doc.cm.coordsChar({ left: event.x, top: event.y })
if (obj.propertyName) {
this.codeMirror.doc.replaceRange(`${obj.propertyName}= "${obj.html}"`, pos);
} else {
this.codeMirror.doc.replaceRange(obj.html, pos);
}
this.editorClass.mySideBar._DragElement = ""
editor.undo.saveStep();
event.preventDefault();
event.stopPropagation();
}
return false;
}
}
|
export default {
// 为当前模块开启命名空间
namespaced: true,
/// 模块的 state 数据
state: () => ({
// 购物车的数组,用来存储购物车中每个商品的信息对象
// 每个商品的信息对象,都包含如下 6 个属性:
// { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
cart: JSON.parse(uni.getStorageSync('cart') || '[]')
}),
// 模块的 mutations 方法
mutations: {
addToCart(state, goods) {
// 根据提交的商品的Id,查询购物车中是否存在这件商品
// 如果不存在,则 findResult 为 undefined;否则,为查找到的商品信息对象
const findResult = state.cart.find((x) => x.goods_id === goods.goods_id)
if (!findResult) {
// 如果购物车中没有这件商品,则直接 push
state.cart.push(goods)
} else {
// 通过 commit 方法,调用 m_cart 命名空间下的 saveToStorage 方法
this.commit('m_cart/saveToStorage')
}
},
// 将购物车中的数据持久化存储到本地
saveToStorage(state) {
uni.setStorageSync('cart', JSON.stringify(state.cart))
}
},
// 模块的 getters 属性
getters: {
// 统计购物车中商品的总数量
total(state) {
let c = 0
// 循环统计商品的数量,累加到变量 c 中
state.cart.forEach(goods => c += goods.goods_count)
return c
}
},
}
|
/*Given a string S and a string T, find the minimum
window in S which will contain all the characters in
T in complexity O(n). */
/*Example:
Input: S = "ADOBECODEBANC",
T = "ABC"
Output: "BANC" */
/*Note:
If there is no such window in S that covers all characters in T, return the empty string "".
If there is such window, you are guaranteed that there will always be only one unique minimum window in S. */
/**
* @param {string} s
* @param {string} t
* @return {string}
*/
var minWindow = function(s, t) {
if (t.length > s.length) {
return "";
}
let hash = {};
for (let i = 0; i < t.length; i++) {
if (hash[t[i]] === undefined) {
hash[t[i]] = 1;
} else {
hash[t[i]] += 1;
}
}
let target = t.length;
let left = 0;
let right = 0;
let minDistance = Number.MAX_VALUE;
let minLeft = 0;
while (right < s.length) {
let char = s[right];
if (hash[char] !== undefined && hash[char] > 0) {
hash[char] = hash[char] - 1;
target--;
}
if (target == 0) {
while (true) {
let windowChar = s[left];
if (hash[windowChar] === undefined) {
left++;
} else {
break;
}
}
if (right - left < minDistance) {
minDistance = right - left;
minLeft = left;
}
while (true) {
let windowChar = s[left];
if (hash[windowChar] !== undefined) {
// restore
hash[windowChar] = hash[char] + 1;
target++;
}
if (target == t.length) {
break;
}
left++;
}
} else {
right++;
}
}
if (minDistance === Number.MAX_VALUE) {
return "";
}
return s.substr(minLeft, minDistance + 1);
};
let input1 = ["ADOBECODEBANC", "ABC"];
let input2 = ["ab", "a"];
let input3 = ["aa", "aa"];
let input4 = ["aa", "aaa"];
let input5 = ["bbaac", "aba"];
let input6 = ["aaflslflsldkalskaaa", "aaa"];
let input7 = ["a", "b"];
let input8 = ["abc", "b"];
let input9 = ["bdab", "ab"];
let result = minWindow(input5[0], input5[1]);
console.log(JSON.stringify(result));
|
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.PORT || 3000;
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
//conexion bdd
const mongoose = require('mongoose');
const user = 'test';
const pwd = 'MuEgUE3GSZ58JV10';
const uri = `mongodb+srv://${user}:${pwd}@test.pfqtg.mongodb.net/veterinaria?retryWrites=true&w=majority`;
mongoose.connect(uri,{useNewUrlParser: true, useUnifiedTopology: true})
.then(()=> console.log('Conectado'))
.catch(e => console.log(e));
//motor de plantillas
app.set('view engine','ejs');
app.set('views',__dirname+'/views');
app.use(express.static(__dirname+"/public"));
//usar router
app.use('/api',require('./router/routes'));
app.use((req,res,next)=>{
res.status(404).render("404");
});
app.listen(port,()=>{
console.log(`listen port ${port}`);
})
|
const body = document.querySelector('body');
const btn = document.querySelector('button');
const colors = ['#36D1DC', '#FF512F', '#b92b27', '#1565C0', '#f12711', '#f5af19', '#52c234', '#DD2476']
const changecolors = function(){
let genColor = Math.trunc(Math.random()*6)
body.style.background = colors[genColor]
}
btn.addEventListener('click', changecolors)
|
class ClienteEspecial extends Cliente {
constructor(nome_cliente, cpf, conta) {
super(nome_cliente, cpf, conta);
this._dependentes = new Array();
}
inserir(dependente) {
this._dependentes.push(dependente);
}
remover(clienteCpf) {
this._dependentes.splice(this._dependentes.findIndex(cliente => cliente.cpf === clienteCpf), 1);
}
toString() {
return `Nome: ${this.nome_cliente} - Cpf: ${this.cpf} - Conta: ${this.conta}`;
}
}
|
import './DinnerSupplies.css';
import SilverWare from '../SilverWare/SilverWare';
function DinnerSupplies ({guestList}) {
console.log('In DinnerSupplies Component with:', guestList);
let count = guestList.length;
return (
<>
<h2>Dinner Supplies</h2>
<SilverWare name="Spoons" count={count} />
<SilverWare name="Forks" count={count} />
<SilverWare name="Knives" count={count} />
</>
);
}
export default DinnerSupplies;
|
/* 🤖 this file was generated by svg-to-ts*/
export const EOSIconsHdrWeak = {
name: 'hdr_weak',
data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M5 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm12-2c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm0 10c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4z"/></svg>`
};
|
import React, { useState } from 'react';
import { connect } from 'react-redux';
import DeleteIcon from '@material-ui/icons/Delete';
import CreateIcon from '@material-ui/icons/Create';
import { editTopic, deleteTopics } from '../actions';
const TopicTitle = (props) => {
const [content, setcontent] = useState({ name: props.topic.title });
const [editing, setediting] = useState(false);
const handleChange = (e) => {
e.preventDefault();
setcontent({ ...content, [e.target.name]: e.target.value });
};
const submitForm = (e) => {
e.preventDefault();
props.editTopic(props.topic.id, content.name);
setcontent({ name: content.name });
setediting(!editing);
};
const renderTopicForm = () => {
return (
<form onSubmit={submitForm}>
<div className='edit-topic-cont'>
<input
className='edit-topic-text-area'
type='text'
name='name'
value={content.name}
onChange={handleChange}
/>
{' '}
<span onClick={() => setediting(!editing)} className='edit-toggle'>
x
</span>
</div>
</form>
);
};
return (
<span>
<h4 className='title'>
{props.topic.title !== 'Drafts' ? (
<span id='topicContainer' className='editTopics'>
<span className='topicIcons'>
<span className={`deleteTopic`}>
<DeleteIcon
style={{ marginRight: '20' }}
onClick={() =>
props.deleteTopics(
props.topic.id,
props.user.currentUser.subject
)
}
/>
</span>
<CreateIcon
className={`editTopic`}
onClick={() => setediting(!editing)}
/>
</span>
{!editing ? (
<span className='topicTitle'>{props.topic.title}</span>
) : (
renderTopicForm()
)}
</span>
) : (
props.topic.title
)}
</h4>
</span>
);
};
const mapStateToProps = (state) => ({
user: state.user,
});
export default connect(mapStateToProps, { editTopic, deleteTopics })(
TopicTitle
);
|
import React from 'react';
import { Button, Checkbox, Modal } from 'semantic-ui-react';
/**
* Displays information about how to use the app and what its purpose is.
*
* @return {*} Jsx to display the component.
* @constructor
*/
const IntroView = () => {
return (
<div
style={{
textAlign: 'center',
}}
>
<Modal.Header as="h1">
Welcome to <b>Pillars!</b>
</Modal.Header>
<Modal.Content>
<h3> Overview </h3>
<p>
This is an app that{"'"}s dedicated to the <i>consistency</i> of
living life in this modern age.
</p>
<p>
This app keeps track of the habits you wish to maintain throughout
your life and helps make sure that you both are trying to continue to
accomplish these things everyday and also are aware about the
analytics of how well you have been accomplishing them.
</p>
<p>
Each <b>pillar</b> indicates a different daily habit to accomplish.
These can be anything from <i>exercising</i> to <i>meditating</i> and
even to maintaining a strong <i>connection</i> to loved ones. It{"'"}s
in my personal opinion that keeping track of these and committing to
the process of accomplishing them will help you have a more fulfilling
and engaging life.
</p>
<h3> How To Use: </h3>
<p>
To use this app, you first have to figure out the things that you want
to keep track of in your day-to-day life. These will make up the
Pillars of your day and will be a frame of reference for your day
went. These can be everything from going to bed early, to meditating,
to eating healthy, even to maintaining a strong relationship with
friends or family.
</p>
<p>
For each one of your pillars, you click the + button at the top of the
screen, which looks like this:
</p>
<Button primary icon="plus" />
<p />
<p>This will get you to the Pillar creation step.</p>
<h3>Creating a Pillar</h3>
<h4>Name</h4>
<p>
The name indicates what the Pillar will be called and what it will show up as.
</p>
<h4>Description</h4>
<p>
The description should basically describe what needs to be done to
accomplish the Pillar each day, along with metrics about how to do it
and why it is important to accomplish.
</p>
<h4>Color</h4>
<p>
This will determine the color of the pillar as it shows up in the
view.
</p>
<h3>Tracking your Progress</h3>
<p>
The Pillars are based on a once-a-day checking system. Every day, as
you complete the Pillars, you will use the app in order to check off
and say that you have completed the Pillar goal. Then, at the end of
the day, the switch for the Pillar will reset and allow you to check
it off for the next day.
</p>
<p>
In order to check off each Pillar for the day, first switch the app
into the checking mode by pressing the check button:
</p>
<Button primary icon="check circle" />
<p />
<p>
Then, you check off each one by clicking on the switch at the bottom
of the Pillar that looks like:
</p>
<Checkbox toggle checked={false} />
<p />
<p>After you check it off, it will be in the checked position like:</p>
<Checkbox toggle checked />
<p />
<h2>Thank You!</h2>
<p>Enjoy using my app and I hope you gain something out of it :)</p>
<p />
</Modal.Content>
</div>
);
};
export default IntroView;
|
let button = document.querySelector("input")
let div = document.querySelectorAll("div")
let tab = [-2, 1, 4]
let result = []
const additionne = (x) => {
for (let i = 0; i < tab.length; i++) {
x = tab[i]
result[i] = x + 2
}
}
const affiche = () => {
additionne()
for (let i = 0; i < tab.length; i++) {
div[i].innerHTML = result[i]
}
}
button.addEventListener("click", affiche)
|
import { Section } from "./App.styled";
import { Form } from "../Form/Form";
import Filter from "../Filter/Filter";
import { useFetchContactsQuery } from "../../redux/contactSlice";
import { ContactItem } from "../ContactItem/ContactItem";
import { useState } from "react";
import { Toaster } from "react-hot-toast";
export default function App() {
const res = useFetchContactsQuery();
const data = res.data;
const [filter, setFilter] = useState("");
const changeFilter = (e) => {
setFilter(e.currentTarget.value);
};
const getVisibleContact = () => {
if (data) {
const normalizeFilter = filter.toLowerCase();
return data.filter((data) =>
data.name.toLowerCase().includes(normalizeFilter)
);
} else {
return data;
}
};
const visibleContact = getVisibleContact();
return (
<Section>
<h1>Phonebook</h1>
<Form data={data} />
<h2>Contacts</h2>
<Filter filter={filter} onChange={changeFilter} />
<ContactItem contacts={visibleContact} />
<Toaster />
</Section>
);
}
|
import React from 'react';
import './AppFooter.scss';
import PropTypes from 'prop-types';
export default function AppFooter({ repoUrl }) {
return (
<footer className="app-footer">
<a
className="app-footer__inner nes-text is-disabled"
target="_blank"
rel="noopener noreferrer"
href={repoUrl}
>
<span>view source code</span>
<i className="nes-icon github" />
</a>
</footer>
);
}
AppFooter.propTypes = {
repoUrl: PropTypes.string,
};
AppFooter.defaultProps = {
repoUrl: 'https://www.github.com/pietersweter/',
};
|
var rexpath = {};
rexpath.init = function(window) {
/* inject global `rexpath`. may be bad manner. */
window.rexpath = rexpath;
/* for node.js unit test... there may be other proper way.. */
rexpath.window = window;
var document = rexpath.window.document;
var HTMLDocument = rexpath.window.HTMLDocument;
var HTMLElement = rexpath.window.HTMLElement;
var XPathResult = rexpath.window.XPathResult;
/* -------------------- inject rexpath to element */
HTMLDocument.prototype.rexpath = function(q) {
var from_node = this;
return rexpath.rexpath_internal(q, from_node, false);
};
HTMLDocument.prototype.rexpath_all = function(q) {
var from_node = this;
return rexpath.rexpath_internal(q, from_node, true);
};
// Sync method from html-document to html-element.
['rexpath_raw_find_all'
,'rexpath'
,'rexpath_all'].forEach(method=>{
HTMLElement.prototype[method] = HTMLDocument.prototype[method];
});
/* -------------------- compiler */
Function.prototype.rexpath_compile = function (cont=rexpath.rexpath_return) {
// already compiled function.
return this;
};
String.prototype.rexpath_compile = function (cont=rexpath.rexpath_return) {
// string is xpath.
var q = this;
return function(node, env) {
if (!env.allp && env.foundp) { return; }
var found = node.rexpath_raw_find_all(q);
var found_len = found.length;
for (var i=0; i<found_len; i++) {
var xnode = found[i];
cont(xnode, env);
}
};
};
Array.prototype.rexpath_compile = function (cont=rexpath.rexpath_return){
// array(list) is dispatched with head.
var q = this;
var head = q[0];
if (! head) {
throw 'rexpath_compile cannot accept blank array.';
}
if (head == '@~') {
return rexpath.rexpath_compile_regex_attribute(q, cont);
} else if (head == '~') {
return rexpath.rexpath_compile_regex_text(q, cont);
} else if (head == 'and') {
return rexpath.rexpath_compile_and(q, cont);
} else if (head == 'or') {
return rexpath.rexpath_compile_or(q, cont);
}
};
this.use_xpath();
};
/* -------------------- inject rexpat_raw_find_all. as xpath or querySelector */
rexpath.use_xpath = function() {
var document = rexpath.window.document;
var HTMLDocument = rexpath.window.HTMLDocument;
var HTMLElement = rexpath.window.HTMLElement;
var XPathResult = rexpath.window.XPathResult;
HTMLElement.prototype.rexpath_raw_find_all =
HTMLDocument.prototype.rexpath_raw_find_all =
function(q) {
var xp = document.evaluate(q, this, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var ar = new Array(xp.snapshotLength);
for (var i=0; i<xp.snapshotLength; i++) {
ar[i] = xp.snapshotItem(i);
}
return ar;
};
};
rexpath.use_css_selector = function() {
var document = rexpath.window.document;
var HTMLDocument = rexpath.window.HTMLDocument;
var HTMLElement = rexpath.window.HTMLElement;
var XPathResult = rexpath.window.XPathResult;
HTMLElement.prototype.rexpath_raw_find_all =
HTMLDocument.prototype.rexpath_raw_find_all =
function(q) {
var self = this;
try {
var ar = self.querySelectorAll(q) || [];
return ar;
} catch (e) {
console.log(`querySelectorAll error. self:${self} e:${e}`);
return [];
}
};
};
/* -------------------- top level continuation */
rexpath.rexpath_return = function(node, env) {
if (!env.allp && env.foundp) { return; }
env.foundp = true;
env.found = env.found || new Map;
env.found.set(node, true);
};
rexpath.rexpath_compile_regex_attribute = function(q, cont) {
const attribute_key = q[1];
const regex = q[2]; /* RegExp Object. */
if (!attribute_key || !regex) {
throw 'rexpath_compile_regex_attribute accept blank input.';
}
return function(node, env) {
if (!env.allp && env.foundp) { return; }
const attribute_value = node.getAttribute(attribute_key);
if (!attribute_value) { return; }
const match = attribute_value.match(regex);
if (match) {
cont(node, env);
}
};
};
rexpath.rexpath_compile_regex_text = function(q, cont) {
const regex = q[1];
if (!regex) {
throw 'rexpath_compile_regex_text accept blank input.';
}
return function(node, env) {
if (!env.allp && env.foundp) { return; }
const text_value = node.textContent;
if (!text_value) { return; }
const match = text_value.match(regex);
if (match) {
cont(node, env);
}
};
};
rexpath.rexpath_compile_and = function(q, cont) {
let xcont = cont;
const qlen = q.length;
for(var i = qlen - 1; 1 <= i; i--) {
const qpart = q[i];
xcont = qpart.rexpath_compile(xcont);
}
return xcont;
};
rexpath.rexpath_compile_or = function(q, cont) {
const qlen = q.length;
const or_branch = q.slice(1).map( qpart=>qpart.rexpath_compile(cont) );
const or_branch_len = qlen - 1;
return function(node, env) {
if (!env.allp && env.foundp) {return;}
for (var i = 0; i <= or_branch_len-1; i++) {
(or_branch[i])(node, env);
}
};
};
/* -------------------- driver */
rexpath.rexpath_internal = function(q, from_node, allp=false) {
var aout = q.rexpath_compile(rexpath.rexpath_return);
var env = {};
env.allp = allp;
aout(from_node, env);
if (! env.foundp) { return; }
var found_array = Array.from(env.found.keys()) || [];
if (allp) {
return found_array;
} else {
return found_array[0];
}
};
export default rexpath;
|
module.exports = function() {
var a = document.createElement('div');
a.textContent = "Hello word !";
return a;
};
|
import React, { Component } from 'react';
import { View, Dimensions } from 'react-native';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { NavigationActions } from 'react-navigation';
import Animation from 'lottie-react-native';
import anim from 'kitsu/assets/animation/kitsu.json';
import * as colors from 'kitsu/constants/colors';
class SplashScreen extends Component {
static navigationOptions = {
header: null,
};
componentDidMount() {
this.animation.play();
const { isAuthenticated, completed } = this.props;
if (this.props.rehydratedAt) {
this.init(isAuthenticated, completed);
}
}
componentWillReceiveProps(nextProps) {
const { isAuthenticated, completed } = nextProps;
this.init(isAuthenticated, completed);
}
init(authorized, completed) {
const { dispatch } = this.props.navigation;
let resetAction = null;
if (authorized && completed) {
resetAction = NavigationActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: 'Tabs' })],
key: null,
});
} else if (authorized) {
resetAction = NavigationActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: 'Onboarding' })],
key: null,
});
} else {
resetAction = NavigationActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: 'Intro' })],
key: null,
});
}
dispatch(resetAction);
}
render() {
return (
<View
style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: colors.darkPurple,
}}
>
<View>
<Animation
ref={(animation) => {
this.animation = animation;
}}
style={{
width: Dimensions.get('window').width,
height: Dimensions.get('window').height,
}}
loop
source={anim}
/>
</View>
</View>
);
}
}
const mapStateToProps = ({ auth, onboarding }) => {
const { isAuthenticated, rehydratedAt } = auth;
const { completed } = onboarding;
return { isAuthenticated, rehydratedAt, completed };
};
SplashScreen.propTypes = {
isAuthenticated: PropTypes.bool.isRequired,
navigation: PropTypes.object.isRequired,
};
export default connect(mapStateToProps)(SplashScreen);
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import { toastr } from 'react-redux-toastr';
import {
Modal as BSModal,
FormGroup,
FormControl,
ControlLabel,
InputGroup,
Button,
} from 'react-bootstrap';
import { sendSMS, verifySmsToken } from '../../actions/authentication';
import C from '../../constants/actions';
import VerifySmsIcon from './verifyPhoneNumber.svg';
import s from './SmsVerificationModal.css';
import Modal from '../Modal';
import { validatePhoneNumber } from '../../validation';
import FieldError from '../FieldError/FieldError';
/* eslint-disable css-modules/no-undef-class */
let timerInterval = null;
class SmsVerificationModal extends React.Component {
constructor(props) {
super(props);
this.startCountDownTimer = this.startCountDownTimer.bind(this);
this.handleSendSms = this.handleSendSms.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
this.verifyToken = this.verifyToken.bind(this);
this.reset = this.reset.bind(this);
this.state = {
isSmsSent: false,
selectedCountryCode: props.countries[0].phoneCode,
phoneNumber: null,
token: null,
showResendSMS: false,
timer: 60,
showFieldError: false,
};
}
componentWillReceiveProps(nextProps) {
if (this.props.smsEnabled !== nextProps.smsEnabled) this.reset();
}
startCountDownTimer = () => {
timerInterval = setInterval(() => {
if (this.state.timer === 1) {
clearInterval(timerInterval);
this.setState({ showResendSMS: true, timer: 60 });
return;
}
this.setState({ timer: this.state.timer - 1 });
}, 1000);
};
verifyToken = () => {
if (!this.state.token) {
toastr.error('Validation Error!', 'token is empty!');
return;
}
this.props.verifySmsToken(this.state.token);
};
handleSendSms = () => {
if (this.props.smsEnabled) {
this.setState({ isSmsSent: true, showResendSMS: false }, () =>
this.startCountDownTimer(),
);
this.props.disableSendSms(this.props.phoneNumber);
return;
}
if (!this.state.phoneNumber) {
toastr.error(
'Validation Error!',
'you are not entered your phone number.',
);
return;
}
if (
validatePhoneNumber(
this.state.phoneNumber,
this.state.selectedCountryCode,
)
) {
this.setState({ showFieldError: true });
return;
}
this.setState({ showFieldError: false });
this.setState({ isSmsSent: true, showResendSMS: false }, () =>
this.startCountDownTimer(),
);
this.props.enableSendSms(
this.state.phoneNumber,
this.state.selectedCountryCode,
);
};
handleInputChange = event => {
const { target } = event;
const value = target.type === 'checkbox' ? target.checked : target.value;
const { name } = target;
this.setState({
[name]: value,
});
};
reset() {
clearInterval(timerInterval);
this.setState({ timer: 60 });
this.setState({
isSmsSent: false,
selectedCountryCode: this.props.countries[0].phoneCode,
phoneNumber: null,
token: null,
});
}
render() {
return (
<div>
<Modal
show={this.props.show}
onHide={() => {
this.reset();
this.props.showToggle();
}}
>
<BSModal.Header closeButton />
<BSModal.Body style={{ paddingBottom: 30 }}>
{this.state.isSmsSent || this.props.smsEnabled ? (
<div>
<p className={s.headerTitle}>{`${
this.props.smsEnabled ? 'Disable' : 'Enable'
} SMS authentication`}</p>
{this.state.isSmsSent ? (
<div className={s.formContainer}>
<br />
<p className={s.description} style={{ width: '80%' }}>
Please enter the six digit code we just sent to your
mobile
<br />
{!this.props.smsEnabled && this.state.phoneNumber
? ` ${
this.state.selectedCountryCode
} xxxxxxxx ${this.state.phoneNumber.substr(
this.state.phoneNumber.length - 2,
)}.`
: `xxxxxxxx ${this.props.phoneNumber.substr(
this.props.phoneNumber.length - 2,
)}.`}
</p>
<br />
<div className={s.formInline}>
<img alt="sms verification icon" src={VerifySmsIcon} />
<FormGroup
className={s.customInput}
style={{ marginTop: 10, width: '90%' }}
controlId="selectCountry"
>
<FormControl
onChange={this.handleInputChange}
type="text"
name="token"
placeholder="Enter token"
/>
</FormGroup>
</div>
<br />
{this.state.showResendSMS ? (
<p>
Didn’t receive the SMS?
<span
role="presentation"
onClick={this.handleSendSms}
style={{
color: '#7577ff',
fontWeight: 'bold',
cursor: 'pointer',
}}
>
Re-send SMS
</span>
</p>
) : (
<p>{`Token sent ${this.state.timer}`}</p>
)}
<br />
{!this.props.smsEnabled && (
<p
role="presentation"
onClick={() =>
this.setState(
{ isSmsSent: false, phoneNumber: null, timer: 60 },
() => clearInterval(timerInterval),
)
}
style={{
color: '#7577ff',
fontWeight: 'bold',
cursor: 'pointer',
}}
>
Use another phone number
</p>
)}
<br />
<Button
style={{ width: '80%' }}
onClick={this.verifyToken}
className={s.customBtn}
block
>
{this.props.smsEnabled ? 'Disable' : 'Enable'}
</Button>
</div>
) : (
this.props.smsEnabled && (
<div className={s.formContainer}>
<p className={s.description} style={{ width: '80%' }}>
if you want to disable SMS authentication please click
on send button to send a token to your phone number.
</p>
<br />
<Button
style={{ width: '80%' }}
onClick={this.handleSendSms}
className={s.customBtn}
block
>
Send
</Button>
</div>
)
)}
</div>
) : (
<div>
<p className={s.headerTitle}>Enter phone number</p>
<div className={s.formContainer}>
<FormGroup
className={s.customInput}
style={{ width: '80%' }}
controlId="selectCountry"
>
<ControlLabel>Country</ControlLabel>
<FormControl
onChange={event =>
this.setState({
selectedCountryCode: event.target.value,
})
}
value={this.state.selectedCountryCode}
componentClass="select"
placeholder="Select Country"
>
{this.props.countries &&
this.props.countries.map(item => (
<option key={item.phoneCode} value={item.phoneCode}>
{item.name}
</option>
))}
</FormControl>
<br />
<ControlLabel>Your Phone Number</ControlLabel>
<InputGroup>
<InputGroup.Button>
<Button style={{ height: 45 }}>
{this.state.selectedCountryCode}
</Button>
</InputGroup.Button>
<FormControl
onChange={this.handleInputChange}
type="text"
name="phoneNumber"
placeholder="Enter Phone Number"
/>
</InputGroup>
<FieldError
color="red"
error={validatePhoneNumber(
`${this.state.phoneNumber}` || '',
this.state.selectedCountryCode,
)}
show={this.state.showFieldError}
/>
</FormGroup>
<p className={s.description} style={{ width: '80%' }}>
This will secure your account by texting a short
confirmation code to your phone when logging in.
</p>
<Button
style={{ width: '80%' }}
onClick={this.handleSendSms}
className={s.customBtn}
block
>
Send SMS
</Button>
</div>
</div>
)}
</BSModal.Body>
</Modal>
</div>
);
}
}
SmsVerificationModal.propTypes = {
countries: PropTypes.arrayOf(PropTypes.object).isRequired,
enableSendSms: PropTypes.func.isRequired,
disableSendSms: PropTypes.func.isRequired,
verifySmsToken: PropTypes.func.isRequired,
show: PropTypes.bool,
showToggle: PropTypes.func,
// onDisable: PropTypes.func.isRequired,
smsEnabled: PropTypes.bool.isRequired,
phoneNumber: PropTypes.string,
};
SmsVerificationModal.defaultProps = {
show: false,
showToggle: () => {},
phoneNumber: '',
};
const mapState = state => ({
countries: state.countries,
show: state.showSMSAuthenticationModal,
smsEnabled: state.userInfo.authStatus.smsEnabled,
phoneNumber: state.userInfo.authStatus.phoneNumber,
});
const mapDispatch = dispatch => ({
showToggle() {
dispatch({ type: C.TOGGLE_SHOW_SMS_AUTHENTICATION_MODAL });
},
enableSendSms(phoneNumber, countryCode) {
dispatch(sendSMS(countryCode + phoneNumber));
},
disableSendSms(phoneNumber) {
dispatch(sendSMS(phoneNumber));
},
verifySmsToken(token) {
dispatch(verifySmsToken(token));
},
});
export default connect(
mapState,
mapDispatch,
)(withStyles(s)(SmsVerificationModal));
export const WithoutRedux = withStyles(s)(SmsVerificationModal);
|
// import _ from 'lodash'
import { actionTypes } from './actions'
const state = {
data: [],
paginatedData: [],
current_page: 1,
page_size: 10
}
export default (state = {}, action) => {
switch(action.type) {
case actionTypes.GET_PRODUCTS:
return { ...state, data: action.payload.data }
case actionTypes.SET_PAGINATE:
return { ...state, currentPage: action.payload }
default:
return state
}
}
|
//tabs.js
import React from 'react';
import {
View, Text,
TouchableOpacity
} from 'react-native';
import s from './style'
const tw = (omanagerTab,tab)=>omanagerTab===tab?[s.bfwTap,s.bfw]:s.bfw
const bf = (omanagerTab,tab)=>omanagerTab===tab?[s.bf,s.bfTap]:s.bf
const Tabs = ({omanagerTab,switchOmanagerTab}) => (
<View style={s.ctnr}>
<View><TouchableOpacity onPress={()=>switchOmanagerTab(1)} style={s.btn}>
<View style={tw(omanagerTab,1)}><Text style={bf(omanagerTab,1)}>待发货</Text></View>
</TouchableOpacity></View>
<View><TouchableOpacity onPress={()=>switchOmanagerTab(2)} style={s.btn}>
<View style={tw(omanagerTab,2)}><Text style={bf(omanagerTab,2)}>待支付</Text></View>
</TouchableOpacity></View>
<View><TouchableOpacity onPress={()=>switchOmanagerTab(3)} style={s.btn}>
<View style={tw(omanagerTab,3)}><Text style={bf(omanagerTab,3)}>已发货</Text></View>
</TouchableOpacity></View>
</View>
);
export default Tabs
|
$(document).ready(function() {
"use strict";
var av_name = "CFLPumpingEx3FS";
var av = new JSAV(av_name);
var Frames = PIFRAMES.init(av_name);
// Frame 1
av.umsg("Prove that $L = \\{a^jb^k: k = j^2\\}$ is not a CFL.");
av.displayInit();
// Frame 2
av.umsg(Frames.addQuestion("winL"));
av.step();
// Frame 3
av.umsg(Frames.addQuestion("cases"));
av.step();
// Frame 4
av.umsg(Frames.addQuestion("case1"));
av.step();
// Frame 5
av.umsg(Frames.addQuestion("asnopump"));
av.step();
// Frame 6
av.umsg(Frames.addQuestion("case2"));
av.step();
// Frame 7
av.umsg(Frames.addQuestion("absnopump"));
av.step();
// Frame 8
av.umsg(Frames.addQuestion("case3"));
av.step();
// Frame 9
av.umsg(Frames.addQuestion("csnopump"));
av.step();
// Frame 10
av.umsg("We have now considered all the variations on possible substrings with $|vxy| \\le m$, and found that there is no decomposition of $w$ into $uvxyz$ such that $|vy| \\ge 1$, $|vxy| \\le m$, and for all $i \\ge 0$, $uv^ixy^iz$ is in $L$. This is a contradiction of the Pumping Lemma. Thus, L is not a CFL. Done.");
av.step();
// Frame 11
av.umsg("Congratulations! Frameset completed.");
av.recorded();
});
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.globalErrorHandler = void 0;
var enums_1 = require("../enums");
var custom_errors_1 = require("../errors/custom-errors");
exports.globalErrorHandler = function (err, req, res, next) {
if (err instanceof custom_errors_1.CustomError) {
return res.status(err.statusCode).json({ errors: err.serializeErrors() });
}
res.status(enums_1.HttpStatusCodes.INTERNAL_SERVER_ERROR).send({
errors: [{ message: 'Something went wrong' }],
});
};
|
import React, { useState, useContext } from "react";
import { TokenContext } from "../contexts/TokenContext";
import { PageHeader, Typography, Avatar, Menu, Dropdown, Space } from "antd";
import { UserOutlined, DownOutlined } from "@ant-design/icons";
import { Redirect } from "react-router-dom";
const { Text } = Typography;
const HeaderTitle = ({ title, username, isTodo, logout }) => {
const [isClicked, setIsClicked] = useState(false);
const [token, setToken] = useContext(TokenContext);
const menu = (
<Menu>
<Menu.Item danger>
<a onClick={() => logout()}>Logout</a>
</Menu.Item>
</Menu>
);
return (
<>
{isClicked ? <Redirect to="/home" /> : ""}
<PageHeader
backIcon={isTodo}
onBack={() => setIsClicked(true)}
style={styles.title}
title={title}
extra={
token ? (
<>
<Avatar
style={{
backgroundColor: "#87d068",
}}
icon={<UserOutlined />}
/>
<Dropdown overlay={menu}>
<Text>
<Space>
{username}
<DownOutlined />
</Space>
</Text>
</Dropdown>
</>
) : (
""
)
}
/>
</>
);
};
const styles = {
title: {
height: "8vh",
marginTop: "-4px",
},
};
export default HeaderTitle;
|
// const { workerData, parentPort } = require('worker_threads');
var speech = require('@google-cloud/speech');
var path = require('path');
var ffmpeg = require('fluent-ffmpeg');
const client = new speech.SpeechClient({
projectId: 'aja-transcriber',
keyFilename: './aja.json'
});
let transcribe = function (toTranscribe) {
ffmpeg(toTranscribe).output('./media/temp.wav')
.setDuration(30)
.setStartTime('00:00:00')
.noVideo()
.format('wav')
.outputOptions('-ab', '192k')
.on('end', function () {
const fileName = 'temp.wav';
const file = fs.readFileSync(fileName);
const audioBytes = file.toString('base64');
const audio = {
content: audioBytes,
};
const config = {
encoding: 'LINEAR16',
sampleRateHertz: 48000,
languageCode: 'en-US',
audioChannelCount: 2,
enableSeparateRecognitionPerChannel: true
};
const request = {
audio: audio,
config: config,
};
client
.recognize(request)
.then(data => {
const response = data[0];
const transcription = response.results
.map(result => result.alternatives[0].transcript);
return transcription
})
.catch(err => {
console.error('ERROR:', err);
});
})
.run();
}();
transcribe(workerData);
parentPort.postMessage(workerData);
|
import React,{ useState, useEffect } from 'react'
import {Link} from 'react-router-dom'
import { useHistory } from 'react-router-dom'
const Signup = ()=>{
const history=useHistory()
const [name,setname]=useState("")
const [email,setemail]=useState("")
const [password,setpassword]=useState("")
const [msg,setmsg]=useState("")
const [image,setimage]=useState("")
const [url,seturl]=useState(undefined)
useEffect(()=>{
if(url){
uploadfields();
}
},[url])
const uploadpic=()=>{
const data=new FormData()
data.append("file",image )
data.append("upload_preset","image-sharing")
data.append("cloud_name","abcdab123")
fetch("https://api.cloudinary.com/v1_1/abcdab123/image/upload",{
method:"post",
body:data
})
.then(res=>res.json())
.then(data=>{
seturl(data.url)
}).catch(err=>{
console.log(err)
})
}
const uploadfields=()=>{
fetch("http://localhost:5000/signup",{
method:"post",
headers:{
"Content-Type":"application/json"
},
body:JSON.stringify({
name,
email,
password,
pic:url
})
}).then(res=>res.json())
.then(data=>{
if(data.error){
setmsg(data.error)
}
else{
history.push('/signin')
}
})
}
const postdata=()=>{
if(image){
uploadpic()
}else{
}
}
return(
<div>
<input value={msg} />
<input type='text' placeholder='name' value={name} onChange={(e)=>setname(e.target.value)} />
<input type='text' placeholder='email' value={email} onChange={(e)=>setemail(e.target.value)} />
<input type='password' placeholder='password' value={password} onChange={(e)=>setpassword(e.target.value)} />
< input type='file' onChange={(e)=>setimage(e.target.files[0])} />
<button onClick={()=>postdata()}>sign up</button>
<Link to='/signin'>sign in</Link>
</div>
)
}
export default Signup
|
/*********************新房日志***************************/
import {onPost,onGet} from "../main";
//新房平台【添加操作】记录日志
export const houseAddLog = params =>{
return onPost('sso/main/newHouseAddLog',params);
}
//新房【修改操作】记录日志
export const houseUpdateLog = params =>{
return onPost('sso/main/newHouseUpdateLog',params);
}
// 新房【查询操作】记录日志
export const houseQueryLog = params =>{
return onPost('sso/main/newHouseQueryLog',params);
}
// 新房【删除操作】记录日志
export const houseDelLog = params =>{
return onPost('sso/main/newHouseDelLog',params);
}
|
var cc = require('couch-client');
var coll = cc("http://localhost:4000/coll");
for (var i=32; i<=126; i++) {
coll.save({"x": String.fromCharCode(i)}, function(err, doc) {
if (err) throw err;
console.log("saved %s", JSON.stringify(doc));
});
};
|
import React, { useContext, useMemo, useState } from 'react';
import queryString from 'query-string';
import { useLocation } from 'react-router-dom';
import { useForm } from '../../../hooks/useForm';
import { ProductCard } from '../products/ProductCard'
import { getProducts } from '../../../selectors/getProducts';
import { AddProduct } from '../products/AddProduct';
import { Context } from '../../../context/Context';
export const Search = ({ history }) => {
const {values} = useContext(Context);
const [renderNewProduct,setRenderNewProduct] = useState(false);
const location = useLocation();
const { q = '' } = queryString.parse(location.search);
const [{ searchText }, handleInputChange] = useForm({
searchText: ''
});
let ProductsFiltered = useMemo(() => getProducts(q), [q]);
const [nuevoProduct, setNuevoProduct] = useState(false)
const handleNuevoProducto = () => {
history.push(`?q=`)
setNuevoProduct(true);
}
const handleSearch = (e) => {
e.preventDefault();
history.push(`?q=${searchText}`)
setRenderNewProduct(false)
setNuevoProduct(false)
};
const setSaveNewProduct = () => {
ProductsFiltered = []
setRenderNewProduct(true)
}
return (
<div>
<h1>Buscar</h1>
<hr />
<div className="row">
<div className="col-5">
<form>
<input
name='searchText'
type="text"
placeholder="Encuentra tu producto"
className="form-control"
autoComplete="off"
value={searchText}
onChange={handleInputChange}
/>
<br />
<div style={{display: 'flex', justifyContent: 'flex-start'}}>
<button
type="submit"
className="btn m-1 btn-block btn-outline-primary"
onClick={handleSearch}
>
Buscar...
</button>
<button
type="button"
className="btn m-1 btn-block btn-outline-primary"
onClick={handleNuevoProducto}
>
Nuevo Producto...
</button>
</div>
</form>
</div>
<div className="col-7">
<h4>Resultado</h4>
<br />
{
(q === '')
&&
<div className="alert alert-info">
Buscar un producto
</div>
}
{
(q !== '' && ProductsFiltered.length === 0)
&&
<div className="alert alert-danger">
No hay un producto con {q}
</div>
}
{
renderNewProduct
? <ProductCard
key={values.id}
{...values}
/>
:
(ProductsFiltered.id !== undefined)
? <ProductCard
key={ProductsFiltered.id}
{...ProductsFiltered}
/>
: ProductsFiltered.map(producto => (
<ProductCard
key={producto.id}
{...producto}
/>
))
}
</div>
</div>
{nuevoProduct &&
<React.Fragment>
<div className="row">
<div className="col-5" >
<AddProduct
nuevoproduct={setSaveNewProduct}
setNuevoProduct={setNuevoProduct}
/>
</div>
</div>
</React.Fragment>
}
</div>
)
}
|
import React from "react";
import { Link } from "react-router-dom";
import Login from "./Login";
const Register = (props) => {
const onsubmit = () => {
// localStorage.setItem();
props.history.push("/login");
};
return (
<div>
<form style={{ border: "1px solid #ccc" }}>
<div className="container">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr />
<label htmlFor="email">
<b>Email</b>
</label>
<input type="text" placeholder="Enter Email" name="email" />
<label htmlFor="psw">
<b>Password</b>
</label>
<input type="password" placeholder="Enter Password" name="psw" />
<label htmlFor="psw-repeat">
<b>Repeat Password</b>
</label>
<input
type="password"
placeholder="Repeat Password"
name="psw-repeat"
/>
<label>
<input
type="checkbox"
defaultChecked="checked"
name="remember"
style={{ marginBottom: "15px" }}
/>
Remember me
</label>
<p>
By creating an account you agree to our
<a href="#" style={{ color: "dodgerblue" }}>
Terms & Privacy
</a>
.
</p>
<div className="clearfix">
<button type="submit" className="signupbtn">
<Link to="./Login">Login</Link>
</button>
<button type="submit" className="cancelbtn" onClick={onsubmit}>
Submit
</button>
</div>
</div>
</form>
</div>
);
};
export default Register;
|
const VueCompColors = {
template: `
<div style="height: 100%">
<i class="fa fa-arrow-left back-arrow" @click="router.go(-1)"></i>
<centered>
<div style="height: 60vh; width: 60vw; border-radius: 20px" v-bind:style="{ 'background-color': backgroundColor }"></div>
</centered>
</div>
`,
data: function () {
return {
backgroundColor: 'blue',
displayController: undefined,
}
},
methods: {
updateColor: function (newVal) {
this.backgroundColor = newVal;
},
keyUpEventListener: function (event) {
// console.log(event);
if (event.key == ' ') {
this.displayController.togglePause();
} else if (event.key == "ArrowRight") {
this.displayController.displayNext();
} else if (event.key == "ArrowLeft") {
this.displayController.displayPrev();
}
},
},
created: function () {
console.log('Created');
const colors = new CircularIterator([
'blue', 'red', 'black',
'sienna', // The brown doesn't look very brown. We'll do sienna instead for brown.
'grey', 'green', 'orange',
'purple', 'yellow',
]);
this.displayController = new DisplayController(colors, this.updateColor);
document.addEventListener('keyup', this.keyUpEventListener);
},
destroyed: function () {
console.log('Removing keyup event listener');
document.removeEventListener('keyup', this.keyUpEventListener);
this.displayController.pause();
}
};
Vue.component('colors-page', VueCompColors);
|
export default {
apiKey: "AIzaSyAhWJ6CzJL3kLcJvZB2nsN-aodarnn7iFc",
authDomain: "pupigram.firebaseapp.com",
databaseURL: "https://pupigram.firebaseio.com",
projectId: "pupigram",
storageBucket: "pupigram.appspot.com",
messagingSenderId: "1045620088441",
appId: "1:1045620088441:web:b5a23d41d8147f503a3ea8",
measurementId: "G-4EG95KM5H2"
}
|
$(document).ready(function() {
/// Collapser
if($(window).width() < 767) {
let x = $("#cut");
x.collapser({
mode: 'lines',
truncate: 8
});
}
///Animate Scroll
$(".container-dots>ul>li>a").on('click.smothscroll',function(e){
e.preventDefault();
var hash = $(this).attr('href');
var offset = $(hash).offset().top-10;
$('body,html').animate({scrollTop: offset},1000);
$('.container-dots>ul>li>a').removeClass('active');
$(this).addClass('active');
});
$(document).on("scroll", onScroll);
function onScroll(){
var scroll_top = $(document).scrollTop();
$('.container-dots>ul>li>a').each(function(){
var hash = $(this).attr("href");
var target = $(hash);
if (target.position().top <= scroll_top && target.position().top + target.outerHeight() >= scroll_top) {
$(".container-dots>ul>li>a.active").removeClass("active");
$(this).addClass("active");
} else {
$(this).removeClass("active");
}
});
}
///Slick slider
let title = [];
$('.sliderItem').each(function(i){
title[i] = $(this).attr('data');
});
var customslick = $('.slick-slider');
customslick.on("init", function(event, slick){
$(".slick-title").text( title[slick.currentSlide] );
$(".slick-counter").text(parseInt(slick.currentSlide + 1) + ' / ' + slick.slideCount);
});
customslick.on("afterChange", function(event, slick, currentSlide){
$(".slick-title").text( title[slick.currentSlide] );
$(".slick-counter").text(parseInt(slick.currentSlide + 1) + ' / ' + slick.slideCount);
});
customslick.slick({
slidesToShow: 1,
arrows: true,
adaptiveHeight: true,
prevArrow: '<button type="button" class="slick-prev"></button>',
nextArrow: '<button type="button" class="slick-next"></button>'
});
var currentSlide = customslick.slick('slickCurrentSlide');
});
$(window).on('resize',function(){
if($(window).width() < 767) {
let x = $("#cut");
x.collapser({
mode: 'lines',
truncate: 8,
dynamic: true
});
}
});
|
function getFirstSelector(selector) {
return document.querySelector(selector);
}
function nestedTarget() {
return document.querySelector('#nested .target')
}
function increaseRankBy(n) {
const ranks = document.querySelectorAll('.ranked-list li')
for (var i = 0, l = ranks.length; i < l; i++) {
var integer = parseInt(ranks[i].innerHTML) + n;
ranks[i].innerHTML = integer.toString()
}
}
function deepestChild(argument) {
const deepdivs = document.querySelectorAll('#grand-node div');
return deepdivs[deepdivs.length - 1];
}
|
export const API_KEY = "AIzaSyC1Q8T48RfHH5LZxp9D-Fer7y3wRkoAt94";
export default API_KEY;
|
import React from 'react';
import { connect } from 'react-redux';
import { filterAnecdotes } from '../reducers/filterReducer';
const Filter = (props) => {
const handleChange = (event) => {
event.preventDefault();
const filterText = event.target.value;
props.filterAnecdotes(filterText);
};
const style = {
marginBottom: 10,
};
return (
<div style={style}>
filter <input name="filterInput" onChange={handleChange} />
</div>
);
};
const mapDispatchToProps = {
filterAnecdotes,
};
export default connect(null, mapDispatchToProps)(Filter);
|
// Variables
// Selecting the form element
const form = document.querySelector("#form");
// Get the value from the input
const imageInput = document.querySelector("#image");
const topTextInput = document.querySelector("#top-text");
const bottomTextInput = document.querySelector("#bottom-text");
form.addEventListener("submit", (e) => {
e.preventDefault();
// Creates an empty div
let memeDiv = document.createElement("div");
memeDiv.classList.add("container");
document.body.appendChild(memeDiv);
// Creates div for top text
let topTextDiv = document.createElement("div");
topTextDiv.classList.add("top");
memeDiv.append(topTextDiv);
// Creates div for bottom text
let bottomTextDiv = document.createElement("div");
bottomTextDiv.classList.add("bottom");
memeDiv.append(bottomTextDiv);
// Creates an empty img tag
let newMeme = document.createElement("img");
newMeme.src = imageInput.value;
imageInput.value = "";
memeDiv.append(newMeme);
// Creates empty paragraph tag
let topText = document.createElement("p");
topText = topTextInput.value;
topTextInput.value = "";
topTextDiv.append(topText);
// Creates empty paragraph tag
let bottomText = document.createElement("p");
bottomText = bottomTextInput.value;
bottomTextInput.value = "";
bottomTextDiv.append(bottomText);
// Creates the button to delete
let deleteMeme = document.createElement("button");
deleteMeme.innerText = "Delete";
deleteMeme.className = "delete";
memeDiv.append(deleteMeme);
memeDiv.addEventListener("click", function (e) {
console.log(e.target.className);
if (e.target.className === "delete") {
e.target.parentElement.remove();
}
});
});
|
define(['phaser', 'js/models/System.js'],
function (Phaser, System) {
var missions = function () {
};
missions.prototype = {
init: function (configFromStates, mapsFromStates, skillsFromStates) {
// On récupère les informations depuis le JSON
this.gameObject = JSON.parse(configFromStates);
this.mapsObject = JSON.parse(mapsFromStates);
this.skillsObject = JSON.parse(skillsFromStates);
},
create: function () {
this.buttonReturn = this.game.add.button(10, 653, 'buttonReturn', () => {
this.game.state.start('Play', true, false, JSON.stringify(this.gameObject), JSON.stringify(this.mapsObject), JSON.stringify(this.skillsObject));
}, this, 1, 0);
this.policier = this.game.add.sprite(100, 428, 'policier');
this.bulle = this.game.add.sprite(200, 10, 'bulle');
this.missionDisplay = this.game.add.text(270, 100, '- Débloquer toutes les compétences', {fontSize: '25px', fill: '#000000'})+
this.game.add.text(705, 100, 'rouges', {fontSize: '25px', fill: '#ff0000'})+
this.game.add.text(270, 130, '- Débloquer toutes les compétences', {fontSize: '25px', fill: '#000000'})+
this.game.add.text(705, 130, 'vertes', {fontSize: '25px', fill: '#00ff00'})+
this.game.add.text(270, 160, '- Débloquer toutes les compétences', {fontSize: '25px', fill: '#000000'})+
this.game.add.text(705, 160, 'orange', {fontSize: '25px', fill: '#ffa500'})+
this.game.add.text(270, 190, '- Débloquer toutes les compétences', {fontSize: '25px', fill: '#000000'});
this.system = new System(this.game);
this.system.createFullScreen();
},
update: function () {
}
};
return missions;
});
|
require('../config');
const db = require('../db/db');
const express = require('express');
const app = express();
const path = require('path');
// routes
app.use(require('./routes/index'));
app.use(express.static(path.resolve(__dirname, '../public')));
// Conectar a la BD
db.conectar().then((resp) => {
console.log(resp);
})
.catch((err) => {
console.log(err);
})
// Puerto del restServer
app.listen(PORT, () => {
console.log(`RestServer escuchando puerto ${PORT}`);
});
|
const request = require("supertest");
const app = require("../src/preloadSetup");
const User = require("../models/user");
const {
preloadDatabaseSetup,
userOne,
userOneId
} = require("./fixtures/dbPreload");
// jests global lifecycle methods beforeEach(() => {...}) and afterEach(() => {...})
beforeEach(preloadDatabaseSetup);
// afterEach(() => {
// console.log("after each test ends");
// });
test("should sign up new user", async () => {
const response = await request(app)
.post("/users")
.send({
name: "userThree",
email: "user@three.com",
password: "userThreePass"
})
.expect(201);
// assert that db was changed correctly
const user = await User.findById(response.body.user._id);
// https://jestjs.io/docs/en/expect#not
expect(user).not.toBeNull();
// assertions about the response
expect(response.body).toMatchObject({
user: {
name: "userThree",
email: "user@three.com"
},
token: user.tokens[0].token
});
// assertion about password stored correctly
expect(user.password).not.toBe("userThreePass");
});
test("Should not signup user with invalid name/email/password", async () => {
await request(app)
.post("/users")
.send({
name: "",
email: "user@four.com",
password: "something111!"
})
.expect(400);
await request(app)
.post("/users")
.send({
name: "userFour",
email: "userfour.com",
password: "something111!"
})
.expect(400);
await request(app)
.post("/users")
.send({
name: "userFour",
email: "user@four.com",
password: "PassworD"
})
.expect(400);
});
test("Should not update user if unauthenticated", async () => {
await request(app)
.patch("/users/profile")
.send({
exp: 2
})
.expect(401);
});
test("Should not delete user if unAuth", async () => {
await request(app)
.delete("/users/profile")
.send()
.expect(401);
});
test("Should not update user with invalid name/email/password", async () => {
await request(app)
.patch("/users/profile")
.set("Authorization", `Bearer ${userOne.tokens[0].token}`)
.send({
name: ""
})
.expect(400);
await request(app)
.patch("/users/profile")
.set("Authorization", `Bearer ${userOne.tokens[0].token}`)
.send({
email: "user.com"
})
.expect(400);
await request(app)
.patch("/users/profile")
.set("Authorization", `Bearer ${userOne.tokens[0].token}`)
.send({
password: "password"
})
.expect(400);
});
test("should login existing user", async () => {
const response = await request(app)
.post("/users/login")
.send({
email: userOne.email,
password: userOne.password
})
.expect(200);
const user = await User.findById(userOneId);
expect(user.tokens[1].token).toBe(response.body.token);
});
test("should not login unexisting user", async () => {
await request(app)
.post("/users/login")
.send({
email: userOne.email,
password: "unexistingUserPass"
})
.expect(400);
});
test("should get user profile", async () => {
await request(app)
.get("/users/profile")
.set("Authorization", `Bearer ${userOne.tokens[0].token}`)
.send()
.expect(200);
});
test("should not get profile for not authenticated user", async () => {
await request(app)
.get("/users/profile")
.send()
.expect(401);
});
test("should not delete account for unauthenticated user", async () => {
await request(app)
.delete("/users/profile")
.send()
.expect(401);
});
test("should delete account for user", async () => {
const res = await request(app)
.delete("/users/profile")
.set("Authorization", `Bearer ${userOne.tokens[0].token}`)
.send()
.expect(200);
const user = await User.findById(userOneId);
expect(user).toBeNull();
});
test("should upload avatar image", async () => {
// .attach() - method that allows to specify
// files variable in the header
// takes 2 arguments
// 1 - form filed name, 2 - path to the file
await request(app)
.post("/users/profile/avatar")
.set("Authorization", `Bearer ${userOne.tokens[0].token}`)
.attach("avatar", "tests/fixtures/anon2.jpg")
.expect(200);
const user = await User.findById(userOneId);
// .toBe() uses === operator. and {} === {} gonna fail
// to compare objects in JEST need to use .toEqual()
// expect.any() - type constructor String, Number, Buffer...
expect(user.avatar).toEqual(expect.any(Buffer));
});
test("should change valid field for auth user", async () => {
await request(app)
.patch("/users/profile")
.set("Authorization", `Bearer ${userOne.tokens[0].token}`)
.send({
name: "updatedName"
})
.expect(200);
const user = await User.findById(userOneId);
expect(user.name).toBe("updatedName");
});
test("should not change invalid field for auth user", async () => {
await request(app)
.patch("/users/profile")
.set("Authorization", `Bearer ${userOne.tokens[0].token}`)
.send({
location: "some location"
})
.expect(400);
});
|
import React, { Component } from "react";
import axios from "axios";
class Contact extends Component {
state = { name: "" };
memberInsert = () => {
const send_param = {
name: this.nameE.value,
email: this.emailE_Contact.value,
pw: this.pwE_Contact.value,
comments: this.commentsE.value
};
axios
.post("http://localhost:8080/member/insert", send_param)
.then(returnData => {
if (returnData.data.message) {
this.setState({
name: returnData.data.message
});
} else {
alert("회원가입오류");
}
})
.catch(err => {
console.log(err);
});
};
render() {
if (this.state.name) {
return (
<div>
<h2>{this.state.name}님 회원가입 되셨습니다.</h2>
</div>
);
} else {
return (
<div>
<h2>Contact</h2>
<p>회원가입</p>
이름
<input ref={ref => (this.nameE = ref)} />
<br />
이메일
<input ref={ref => (this.emailE_Contact = ref)} />
<br />
비밀번호
<input ref={ref => (this.pwE_Contact = ref)} />
<br />
comments
<input ref={ref => (this.commentsE = ref)} />
<br />
<button onClick={this.memberInsert}>회원가입</button>
</div>
);
}
}
}
export default Contact;
|
'use strict'
/*
* Create the function `cutFirst` that takes a string and remove the 2 first characters
* Create the function `cutLast` that takes a string and remove the 2 last charcters
* Create the function `cutFirstLast` that takes a string
* and remove the 2 first charcters and 2 last characters
*
* @notions String methods
* https://github.com/nan-academy/refs/blob/master/js-training/methods.md#string---transform
*/
const cutFirst = str => str.slice(2)
const cutLast = str => str.slice(0, str.length - 2)
const cutFirstLast = str => {
let result = cutFirst(str)
return cutLast(result)
}
//* Begin of tests
const assert = require('assert')
assert.strictEqual(typeof cutFirst, 'function')
assert.deepStrictEqual(cutFirst("justine"), "stine")
assert.strictEqual(typeof cutLast, 'function')
assert.deepStrictEqual(cutLast("justine"), "justi")
assert.strictEqual(typeof cutFirstLast, 'function')
assert.deepStrictEqual(cutFirstLast("justine"), "sti")
// End of tests */
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.