text
stringlengths 7
3.69M
|
|---|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function RGBAverage(image) {
var resized = image.resize(1, 512 * 512);
var imageBuffer = resized.getData();
var ui8 = new Uint8Array(imageBuffer);
var iRed = 2;
var iGreen = 1;
var iBlue = 0;
var totalRed = 0;
var totalGreen = 0;
var totalBlue = 0;
for (var i = 0; i < ui8.length; i += 3) {
totalRed += ui8[i + iRed];
totalGreen += ui8[i + iGreen];
totalBlue = ui8[i + iBlue];
}
var avgRed = totalRed / ui8.length;
var avgGreen = totalGreen / ui8.length;
var avgBlue = totalBlue / ui8.length;
return [
Number(avgRed.toFixed(4)),
Number(avgGreen.toFixed(4)),
Number(avgBlue.toFixed(4))
];
}
exports.default = RGBAverage;
|
import React from "react";
import styles from "./Board.module.scss";
import cx from "clsx";
const ScoreCell = props => (
<td>
<div
onClick={e =>
props.value == null && props.hintValue != null && props.onSelect(e)
}
className={cx(
styles.score,
styles.scoreLarge,
props.value == null && props.hintValue <= 0 && styles.hintZero,
props.value == null && props.hintValue > 0 && styles.hint,
props.selected && styles.selected,
props.disabled && styles.scoreDisabled
)}
>
{props.value == null ? props.hintValue : props.value}
</div>
</td>
);
const ScoreRow = props => {
const {
className,
index,
values,
disabled,
hintValues,
smallLabel,
label,
boardState,
summarize,
onCellClick
} = props;
const isValidHint = !disabled && [
boardState.throwIndex > 0 &&
boardState.announcementIndex == null &&
boardState.downIndex >= index,
boardState.throwIndex > 0 &&
boardState.announcementIndex == null &&
boardState.upIndex <= index,
boardState.throwIndex > 0 && boardState.announcementIndex == null,
boardState.throwIndex > 0 &&
((boardState.throwIndex <= 1 && boardState.announcementIndex == null) ||
boardState.announcementIndex === index)
];
const handleSelect = i => {
if (!isValidHint[i]) return;
if (i < 3 || boardState.announcementIndex === index) {
// Fill
values[i] = hintValues[i];
onCellClick({ row: index, column: i, value: hintValues[i] });
} else if (boardState.announcementIndex == null) {
// Announcement
onCellClick({ row: index, column: i, value: null, isAnnouncement: true });
}
};
return (
<tr className={className}>
<td>
<div className={cx(styles.score, !smallLabel && styles.scoreLarge)}>
{label}
</div>
</td>
<ScoreCell
value={values[0]}
disabled={disabled}
hintValue={isValidHint[0] && hintValues[0]}
onSelect={() => handleSelect(0)}
/>
<ScoreCell
value={values[1]}
disabled={disabled}
hintValue={isValidHint[1] && hintValues[1]}
onSelect={() => handleSelect(1)}
/>
<ScoreCell
value={values[2]}
disabled={disabled}
hintValue={isValidHint[2] && hintValues[2]}
onSelect={() => handleSelect(2)}
/>
<ScoreCell
value={values[3]}
disabled={disabled}
hintValue={isValidHint[3] && hintValues[3]}
selected={!disabled && boardState.announcementIndex === index}
onSelect={() => handleSelect(3)}
/>
{summarize && (
<ScoreCell value={values.reduce((sum, val) => sum + val, 0)} disabled />
)}
</tr>
);
};
const Board = props => {
const { boardValues, onBoardValuesChanged } = props;
const diceValues = boardValues.diceValues;
const handleCellClick = action => {
onBoardValuesChanged(action, boardValues);
};
const numberScores = Array(6)
.fill(0)
.map((_, i) => diceValues.filter(d => d === i + 1).length * (i + 1));
const diceValuesSum = diceValues.reduce((a, b) => a + b, 0);
const minMaxScore = diceValuesSum;
const diceValuesCount = Array(6)
.fill()
.map((_, i) => {
return {
value: i + 1,
count: diceValues.filter(dv => dv === i + 1).length
};
});
const diceValuesAboveTwo = diceValuesCount.filter(dvc => dvc.count >= 2);
const diceValuesAboveThree = diceValuesCount.filter(dvc => dvc.count >= 3);
const diceValuesAboveFour = diceValuesCount.filter(dvc => dvc.count >= 4);
const diceValuesAboveFive = diceValuesCount.filter(dvc => dvc.count >= 5);
const twoPairsScore =
diceValuesAboveTwo.length >= 2
? diceValuesAboveTwo[0].value * 2 + diceValuesAboveTwo[1].value * 2 + 10
: diceValuesAboveTwo.length === 1 && diceValuesAboveTwo[0].count >= 4
? diceValuesAboveTwo[0].value * 4 + 10
: 0;
const smallScaleScore =
diceValuesAboveTwo.length <= 0 && diceValuesSum === 15 ? 35 : 0;
const largeScaleScore =
diceValuesAboveTwo.length <= 0 && diceValuesSum === 20 ? 45 : 0;
const fullScore =
diceValuesAboveThree.length > 0 && diceValuesAboveTwo.length > 1
? diceValuesAboveThree[0].value * 3 +
diceValuesAboveTwo.filter(
dvat => dvat.value !== diceValuesAboveThree[0].value
)[0].value *
2 +
20
: diceValuesAboveFive.length >= 1
? diceValuesAboveFive[0].value * 5 + 20
: 0;
const pokerScore =
diceValuesAboveFour.length > 0 ? diceValuesAboveFour[0].value * 4 + 40 : 0;
const yambScore =
diceValuesAboveFive.length > 0 ? diceValuesAboveFour[0].value * 5 + 50 : 0;
const boardState = {
downIndex: boardValues.downIndex,
upIndex: boardValues.upIndex,
announcementIndex: boardValues.announcementIndex,
throwIndex: boardValues.throwIndex
};
// Sum
const numbersSum = Array(4)
.fill()
.map((_, i) => {
const sum = boardValues.numberScores.reduce(
(sum, item) => sum + item[i],
0
);
return sum >= 60 ? sum + 30 : sum;
});
const minMaxSum = Array(4)
.fill()
.map((_, i) =>
boardValues.max[i] != null &&
boardValues.min[i] != null &&
boardValues.numberScores[0][i] != null
? (boardValues.max[i] - boardValues.min[i]) *
boardValues.numberScores[0][i]
: null
);
const specialSum = Array(4)
.fill()
.map(
(_, i) =>
boardValues.twoPairs[i] +
boardValues.scale[i] +
boardValues.poker[i] +
boardValues.full[i] +
boardValues.yamb[i]
);
let rowIndex = 0;
const diceStyles = [
styles.dice1,
styles.dice2,
styles.dice3,
styles.dice4,
styles.dice5,
styles.dice6
];
return (
<div className={styles.tableContainer}>
<table className={styles.jambTable}>
<tbody>
<tr>
<td></td>
<td>
<div className={cx(styles.score, styles.scoreLarge)}>⬇</div>
</td>
<td>
<div className={cx(styles.score, styles.scoreLarge)}>⬆</div>
</td>
<td>
<div className={cx(styles.score, styles.scoreLarge)}>⬇⬆</div>
</td>
<td>
<div className={styles.score}>NAJAVA</div>
</td>
</tr>
{Array(6)
.fill()
.map((_, i) => (
<ScoreRow
index={rowIndex++}
label={<div className={cx(styles.dice, diceStyles[i])}></div>}
values={boardValues.numberScores[i]}
hintValues={Array(4).fill(numberScores[i])}
boardState={boardState}
onCellClick={handleCellClick}
/>
))}
<ScoreRow
disabled
label="∑"
className={styles.sum}
values={numbersSum}
/>
<ScoreRow
index={rowIndex++}
label={"MAX"}
smallLabel
values={boardValues.max}
hintValues={Array(4).fill(minMaxScore)}
boardState={boardState}
onCellClick={handleCellClick}
/>
<ScoreRow
index={rowIndex++}
label={"MIN"}
smallLabel
values={boardValues.min}
hintValues={Array(4).fill(minMaxScore)}
boardState={boardState}
onCellClick={handleCellClick}
/>
<ScoreRow
disabled
label="RAZLIKA X1"
smallLabel
className={styles.sum}
values={minMaxSum}
/>
<ScoreRow
index={rowIndex++}
label={"2 PARA"}
smallLabel
values={boardValues.twoPairs}
hintValues={Array(4).fill(twoPairsScore)}
boardState={boardState}
onCellClick={handleCellClick}
/>
<ScoreRow
index={rowIndex++}
label={"SKALA"}
smallLabel
values={boardValues.scale}
hintValues={Array(4).fill(largeScaleScore || smallScaleScore)}
boardState={boardState}
onCellClick={handleCellClick}
/>
<ScoreRow
index={rowIndex++}
label={"FULL"}
smallLabel
values={boardValues.full}
hintValues={Array(4).fill(fullScore)}
boardState={boardState}
onCellClick={handleCellClick}
/>
<ScoreRow
index={rowIndex++}
label={"POKER"}
smallLabel
values={boardValues.poker}
hintValues={Array(4).fill(pokerScore)}
boardState={boardState}
onCellClick={handleCellClick}
/>
<ScoreRow
index={rowIndex++}
label={"JAMB"}
smallLabel
values={boardValues.yamb}
hintValues={Array(4).fill(yambScore)}
boardState={boardState}
onCellClick={handleCellClick}
/>
<ScoreRow
disabled
label="∑"
className={styles.sum}
values={specialSum}
/>
<tr className={styles.sum}>
<td></td>
<td></td>
<td></td>
<td colSpan="2">
<div
className={cx(
styles.score,
styles.scoreDisabled,
styles.scoreLarge
)}
>
{numbersSum.reduce((sum, val) => sum + val, 0) +
minMaxSum.reduce((sum, val) => sum + val, 0) +
specialSum.reduce((sum, val) => sum + val, 0)}
</div>
</td>
</tr>
</tbody>
</table>
</div>
);
};
export default Board;
|
import { ProxyState } from "../AppState.js"
import Pokemon from "../Models/Pokemon.js";
import { pokemonsApiService } from "../Services/PokemonsApiService.js"
//PRIVATE
function _draw() {
let template = ''
ProxyState.allPokemon.forEach(p => {
template += `<li onclick="app.pokemonsApiController.getPokemon('${p.name}')">${p.name}</li>`
});
document.getElementById("getAllPokemonApi").innerHTML = template
}
function _drawActive() {
document.getElementById("activePokemon").innerHTML = ProxyState.activePokemon ? ProxyState.activePokemon.Template : ""
}
//PUBLIC
export default class PokemonsApiController {
constructor() {
ProxyState.on('allPokemon', _draw)
ProxyState.on('activePokemon', _drawActive)
this.getAllPokemon()
}
async getAllPokemon() {
try {
await pokemonsApiService.getAllPokemon()
} catch (error) {
console.error(error)
}
}
async getPokemon(name) {
try {
await pokemonsApiService.getPokemon(name)
} catch (error) {
console.error(error)
}
}
}
// import { ProxyState } from "../AppState.js";
// import { dndSpellApiService } from "../Services/dndSpellApiService.js";
// //Private
// function _draw() {
// let template = ""
// ProxyState.apiSpells.forEach(s => {
// template += `<li class="action hover-action" onclick="app.dndSpellApiController.getSpell('${s.index}')">${s.name}</li>`
// })
// document.getElementById('api-spells').innerHTML = template
// }
// function _drawActive() {
// document.getElementById('active-spell').innerHTML = ProxyState.activeSpell ? ProxyState.activeSpell.Template : "<p> no active spell</p>"
// }
// //Public
// export default class DndSpellApiController {
// constructor() {
// ProxyState.on("apiSpells", _draw);
// ProxyState.on("activeSpell", _drawActive);
// // NOTE Call to get all spells at start of app
// this.getAllApi()
// }
// async getAllApi() {
// try {
// await dndSpellApiService.getAllSpells()
// } catch (error) {
// console.error(error)
// }
// }
// async getSpell(index) {
// try {
// await dndSpellApiService.getSpell(index)
// } catch (error) {
// console.error(error)
// }
// }
// }
|
$(document).ready(function(){
/*
$(document).ready(function(){
$('div.slider img:gt(0)').hide();
setInterval(function(){
var current = $('div.slider img:visible');
var next = current.next().length ? current.next() : $('div.slider img:eq(0)');
current.fadeOut(3000);
next.fadeIn(4000);
},10000)
})
*/
$('.bxslider').bxSlider();
});
|
import Controller from '@ember/controller';
import { computed } from '@ember/object';
import config from 'kredits-web/config/environment';
export default Controller.extend({
ipfsGatewayUrl: computed(function() {
return config.ipfs.gatewayUrl;
})
});
|
// Function used to turn a string to a url string
// Input: String with space for extra chars and a count for the real word length
const urlify = (str, count) => {
// creae a pointer to traverse the string backwards starting from the last character
let point = count - 1;
// create a pointer to swap characters in place
let posPointer = str.length - 1;
// split the string into an array of characters
str = str.split('');
// while there are characters to traverse
while (point >= 0) {
// if the current pointed at character is a space replace the next 3 indexes with %20
if (str[point] == ' ') {
str[posPointer] = '0';
posPointer--;
str[posPointer] = '2';
posPointer--;
str[posPointer] = '%';
posPointer--;
point--;
} else {
// If the character is not a space put it in the position
str[posPointer] = str[point];
posPointer--;
point--;
}
}
// return the character array joined as a string
return str.join('');
};
console.log(urlify('Mr John Smith ', 13)); // Mr%20John%20Smith
|
var searchData=
[
['getfilename',['getFileName',['../classInput.html#abb4311267ded94768e6df9cb88b179bb',1,'Input']]],
['getoptions',['getOptions',['../classInput.html#af0a5bad322752da31bcd7b1e2d99d611',1,'Input']]]
];
|
module.exports = require('./dist/node/server/index')
|
// 请求数据库名字是否重复验证
module.exports = function(req,res){
const public = require('../public');
var sql = "delete from `questions` where `id`='"+ req.query.id +"'";
public.query(sql,function(error,result){
if(error==null){
res.json({
error:0,
message:'删除成功',
data:result,
})
}else{
res.json({
error: 1,
message: '删除失败',
data:error
})
}
})
}
|
class User {
constructor(user) {
this.first_name = user.first_name;
this.last_name = user.last_name;
this.username = user.username;
this.password = user.password;
this.userId = user.userId;
}
}
module.exports = User;
|
this.VelhaMania.module('UsersApp.List', function (List, App, Backbone, Marionette) {
List.Layout = Marionette.LayoutView.extend({
template: 'users/list/templates/layout',
regions: {
listRegion: '.list-region'
}
});
List.UserView = Marionette.ItemView.extend({
template: 'users/list/templates/user',
tagName: 'li',
className: 'user-item',
triggers: {
'click': 'user:clicked'
},
modelEvents: {
'change:isPlaying' : 'visibleToggle'
},
visibleToggle: function () {
if (this.model.isPlaying()) {
this.$el.hide();
} else {
this.$el.show();
}
this.trigger('user:view:toggled');
}
});
List.EmptyView = Marionette.ItemView.extend({
template: 'users/list/templates/empty',
className: 'empty',
tagName: 'span'
});
List.UsersView = Marionette.CollectionView.extend({
childView: List.UserView,
emptyView: List.EmptyView,
className: 'user-list',
tagName: 'ul',
collectionEvents: {
'change': 'render'
},
isEmpty: function () {
return this.collection.isEmpty();
},
addChild: function (child, ChildView, index) {
if (!child.itsMe()) {
List.UsersView.__super__.addChild.call(this, child, ChildView, index);
}
}
});
});
|
$(document).ready(function(){
setInterval(function(){
$.getJSON($SCRIPT_ROOT + "_JSONSensorRead/" + $SENSOR_NAME, {}, function(data) {
$("#value").text("Value: " + data.value);
})
}, 3000);
$('.updateButton').on('click', function() {
var limit_id = $(this).attr('limit_id');
var value = $('#limitInput'+limit_id).val();
console.log(limit_id);
req = $.ajax({
url: 'http://127.0.0.1:80/update/',
type: 'POST',
data: { id: limit_id, value: value}
});
console.log(limit_id);
});
});
|
import * as types from 'kitsu/store/types';
const INITIAL_STATE = {
media: {},
loading: false,
reactions: {},
loadingReviews: false,
castings: {},
loadingCastings: false,
};
export const mediaReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case types.FETCH_MEDIA:
return {
...state,
loading: true,
error: '',
};
case types.FETCH_MEDIA_SUCCESS:
return {
...state,
loading: false,
media: { ...state.media, [action.payload.mediaId]: action.payload.media },
error: '',
};
case types.FETCH_MEDIA_FAIL:
return {
...state,
loading: false,
error: action.payload,
};
case types.FETCH_MEDIA_REACTIONS:
return {
...state,
loadingReactions: true,
error: '',
};
case types.FETCH_MEDIA_REACTIONS_SUCCESS:
return {
...state,
loadingReactions: false,
reactions: { [action.payload.mediaId]: action.payload.reactions },
error: '',
};
case types.FETCH_MEDIA_REACTIONS_FAIL:
return {
...state,
loadingReactions: false,
error: action.payload,
};
case types.FETCH_MEDIA_CASTINGS:
return {
...state,
loadingCastings: true,
castings: {},
error: '',
};
case types.FETCH_MEDIA_CASTINGS_SUCCESS:
return {
...state,
loadingCastings: false,
castings: { [action.payload.mediaId]: action.payload.castings },
error: '',
};
case types.FETCH_MEDIA_CASTINGS_FAIL:
return {
...state,
loadingCastings: false,
error: action.payload,
};
default:
return state;
}
};
|
"use strict";
/**
* @class
*/
DIC.define('DemoApp.test.tool.DateTimeTest', new function () {
/**
* @description test {@link DemoApp.tool.DateTime.layout} is setted
* @memberOf DemoApp.test.tool.DateTimeTest
* @param {EquivalentJS.test.Unit.assert} assert
* @param {DemoApp.tool.DateTime} moduleClass
*/
this.testHasLayout = function (assert, moduleClass) {
assert.ok(moduleClass.layout, 'has layout');
};
});
|
import FadeIn from "../FadeIn";
import Link from "next/link";
import Chip from "@material-ui/core/Chip";
export default function DM() {
const tech = [
"Next.js",
"React",
"PHP",
"Axios",
"Bootstrap",
"MariaDB",
"AJAX",
"jQuery",
];
return (
<>
<FadeIn>
<hr className="mt-4" />
<div>
<div>
<h6 className="middle-underline d-inline">Daniel Mark</h6>
</div>
<p className="mt-2">
Bunch of personal websites and developer portfolio sites for myself,
ranging from the maximal to super minimal design philosophy.
</p>
{/* <h6 className="mt-4">Releases</h6> */}
<div className="d-none">
<ul className="nav">
<li className="nav-item">
<a
className="nav-link grey-to-white"
style={{ paddingLeft: "0px" }}
>
v1
</a>
</li>
<li className="nav-item">
<Link
passHref
href="https://github.com/thedanielmark/dannyWebsiteNew"
>
<a
className="nav-link grey-to-white"
style={{ paddingLeft: "0px" }}
>
<i class="fab fa-github"></i>
</a>
</Link>
</li>
<li className="nav-item">
<Link passHref href={"https://v1.thedanielmark.com"}>
<a
className="nav-link grey-to-white"
style={{ paddingLeft: "0px" }}
>
<i class="fas fa-globe-asia"></i>
</a>
</Link>
</li>
</ul>
<ul className="nav">
<li className="nav-item">
<a
className="nav-link grey-to-white"
style={{ paddingLeft: "0px" }}
>
v2
</a>
</li>
<li className="nav-item">
<Link
passHref
href={"https://github.com/thedanielmark/danielmark-grey"}
>
<a
className="nav-link grey-to-white"
style={{ paddingLeft: "0px" }}
>
<i class="fab fa-github"></i>
</a>
</Link>
</li>
<li className="nav-item">
<Link passHref href={"https://v2.thedanielmark.com"}>
<a
className="nav-link grey-to-white"
style={{ paddingLeft: "0px" }}
>
<i class="fas fa-globe-asia"></i>
</a>
</Link>
</li>
</ul>
<ul className="nav">
<li className="nav-item">
<a
className="nav-link grey-to-white"
style={{ paddingLeft: "0px" }}
>
v3
</a>
</li>
<li className="nav-item">
<Link
passHref
href={"https://github.com/thedanielmark/daniel-mark-dark"}
>
<a
className="nav-link grey-to-white"
style={{ paddingLeft: "0px" }}
>
<i class="fab fa-github"></i>
</a>
</Link>
</li>
<li className="nav-item">
<Link passHref href={"https://v3.thedanielmark.com"}>
<a
className="nav-link grey-to-white"
style={{ paddingLeft: "0px" }}
>
<i class="fas fa-globe-asia"></i>
</a>
</Link>
</li>
</ul>
<ul className="nav">
<li className="nav-item">
<a
className="nav-link grey-to-white"
style={{ paddingLeft: "0px" }}
>
v4
</a>
</li>
<li className="nav-item">
<Link
passHref
href={"https://github.com/thedanielmark/danielmark-v4"}
>
<a
className="nav-link grey-to-white"
style={{ paddingLeft: "0px" }}
>
<i class="fab fa-github"></i>
</a>
</Link>
</li>
<li className="nav-item">
<Link passHref href={"https://thedanielmark.com"}>
<a
className="nav-link grey-to-white"
style={{ paddingLeft: "0px" }}
>
<i class="fas fa-globe-asia"></i>
</a>
</Link>
</li>
<li className="nav-item">
<a
className="nav-link grey-to-white"
style={{ paddingLeft: "0px" }}
>
(latest)
</a>
</li>
</ul>
{/* <ul className="nav">
<li className="nav-item">
<a
className="nav-link grey-to-white"
style={{ paddingLeft: "0px" }}
>
v5
</a>
</li>
<li className="nav-item">
<Link
passHref
href={"https://github.com/thedanielmark/calculator"}
>
<a
className="nav-link grey-to-white"
style={{ paddingLeft: "0px" }}
>
<i class="fab fa-github"></i>
</a>
</Link>
</li>
<li className="nav-item">
<Link passHref href={"https://v5.thedanielmark.com"}>
<a
className="nav-link grey-to-white"
style={{ paddingLeft: "0px" }}
>
<i class="fas fa-globe-asia"></i>
</a>
</Link>
</li>
</ul> */}
</div>
<h6 className="mt-4">Technologies</h6>
<div class="tech-badges">
{tech.map((chip) => {
return <Chip size="small" key={chip} label={chip} />;
})}
</div>
</div>
</FadeIn>
</>
);
}
|
const Markov = require("node-markov")
const getRandomWords = require("../src/getRandomWords.js")
const getCuttings = require("../src/getCuttings.js")
const argv = require("minimist")(process.argv.slice(2))
const fs = require("fs")
var mark = new Markov(argv.order || 2)
mark.nullChar = "\n"
//getCuttings("bible", 100)
getRandomWords(100000000)
.then(words => {
console.log(words.length)
//words = words.map(word => word.split(" "))
try {
for(var i in words)
mark.feed(words[i])
var imaginaryWords = []
for(var i=0; i<10000; i++)
imaginaryWords[i]=( mark.walk("", 100) )
imaginaryWords = imaginaryWords.filter(word => word.length > 5).sort()
var out = imaginaryWords.join(", ")
console.log(out)
if(argv.o)
fs.writeFile(argv.o, out, console.log)
console.log(mark.evaluate("cat"))
} catch(e) {
console.log(e)
}
})
|
import { connect } from 'react-redux';
import SignUp from './SignUp';
import {
updateSignUpEmailActionCreator,
updateSignUpPasswordActionCreator,
updateSignUpFirstNameActionCreator,
updateSignUpLastNameActionCreator,
updateSignUpCountryActionCreator,
updateSignUpCityActionCreator,
updateSignUpGenderActionCreator,
signUpActionCreator
} from "./../../../redux/reducers/authenticationReducer";
let mapStateToProps = (state) => {
return {
token: state.authenticationPage.token,
email: state.authenticationPage.signUpEmail,
password: state.authenticationPage.signUpPassword,
firstName: state.authenticationPage.signUpFirstName,
lastName: state.authenticationPage.signUpLastName,
country: state.authenticationPage.signUpCountry,
city: state.authenticationPage.signUpCity,
gender: state.authenticationPage.signUpGender
};
};
let mapDispatchToProps = (dispatch) => {
return {
updateEmail: (text) => {
dispatch(updateSignUpEmailActionCreator(text));
},
updatePassword: (text) => {
dispatch(updateSignUpPasswordActionCreator(text));
},
updateFirstName: (text) => {
dispatch(updateSignUpFirstNameActionCreator(text));
},
updateLastName: (text) => {
dispatch(updateSignUpLastNameActionCreator(text));
},
updateCountry: (text) => {
dispatch(updateSignUpCountryActionCreator(text));
},
updateCity: (text) => {
dispatch(updateSignUpCityActionCreator(text));
},
updateGender: (text) => {
dispatch(updateSignUpGenderActionCreator(text));
},
signUp: (token) => {
dispatch(signUpActionCreator(token));
}
};
};
const SignUpContainer = connect(mapStateToProps, mapDispatchToProps)(SignUp);
export default SignUpContainer;
|
var url = window.location.search;
console.log(url);
var authorId = url.split("?")[1];
console.log(authorId);
function previewFile() {
var preview = document.querySelector("img"); //selects the query named img
var file = document.querySelector("input[type=file]").files[0]; //sames as here
var reader = new FileReader();
reader.onloadend = function() {
preview.src = reader.result;
};
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "";
}
}
previewFile(); //calls the function named previewFile()
var url = window.location.search;
var authorId = url.split("?")[1];
console.log(authorId);
$("#submit").click(function(event) {
event.preventDefault();
var imgSrc = $("img").attr("src");
var newItem = {
userId: authorId,
name: $("#name").val(),
description: $("#desc").val(),
price: $("#price").val(),
category: $("#cat").val(),
image: imgSrc
};
console.log(newItem);
$.post("/api/new", newItem).then(function() {
console.log("success");
document.location.href="/";
});
});
|
var searchData=
[
['log_2ec',['log.c',['../log_8c.html',1,'']]],
['log_5ftest_5fhelpers_2ec',['log_test_helpers.c',['../log__test__helpers_8c.html',1,'']]]
];
|
import React, { useEffect, useState } from 'react';
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
import Paper from '@material-ui/core/Paper';
import bankingInfoApi from '../../api/bankingInfoApi';
function PaperComponent(props) {
return <Paper {...props} />;
}
export default function ModalDepositMoney(props) {
const { isOpen, onClose } = props;
const [bankingInfo, setBankingInfo] = useState([]);
useEffect(() => {
const fetchBankingInfo = async () => {
const res = await bankingInfoApi.getBankingInfo();
console.log(res);
setBankingInfo(res.data);
};
fetchBankingInfo();
}, []);
console.log(bankingInfo);
return (
<Dialog
open={isOpen}
onClose={onClose}
PaperComponent={PaperComponent}
aria-labelledby='draggable-dialog-title'
>
<DialogTitle
style={{
cursor: 'move',
textAlign: 'center',
textTransform: 'uppercase',
}}
id='draggable-dialog-title'
>
Thông tin chuyển khoản
</DialogTitle>
<DialogContent>
<DialogContentText>
<div className='infoAccount'>
<p>Ngân hàng: {bankingInfo[0] && <b>{bankingInfo[0].bank}</b>}</p>
<p>
Số tài khoản: {bankingInfo[0] && <b>{bankingInfo[0].number}</b>}
</p>
<p>
Chủ tài khoản: {bankingInfo[0] && <b>{bankingInfo[0].name}</b>}
</p>
<p>
Nội dung chuyển khoản:{' '}
<span
style={{
color: '#f50057',
fontWeight: 'bold',
}}
>
NAP TIEN - Ten - SĐT - Email
</span>{' '}
( Trong đó: Ten là tên người dùng, SĐT là số điện thoại đăng nhập,
Email là email của tài khoản )
</p>
<p
style={{
fontWeight: 'bold',
}}
>
Sau khi nhận được thông tin chuyển khoản, chúng tôi sẽ kiểm tra và
nạp tiền vào tài khoản trong vòng tối đa 2 tiếng (từ 8h30 sáng đến
18h chiều)
</p>
</div>
</DialogContentText>
</DialogContent>
<DialogActions style={{ justifyContent: 'space-around' }}>
<Button onClick={onClose} color='secondary' variant='contained'>
Đóng
</Button>
</DialogActions>
</Dialog>
);
}
|
//= require ./fancybox/index.js
//= require ./fullcalendar/moment.min.js
//= require ./fullcalendar/fullcalendar.min.js
//= require ./waterfall.js
//= require ./colorbox/jquery.colorbox.js
|
'use strict';
/**
* Returns the bank account number parsed from specified string.
*
* You work for a bank, which has recently purchased an ingenious machine to assist in reading letters and faxes sent in by branch offices.
* The machine scans the paper documents, and produces a string with a bank account that looks like this:
*
* _ _ _ _ _ _ _
* | _| _||_||_ |_ ||_||_|
* ||_ _| | _||_| ||_| _|
*
* Each string contains an account number written using pipes and underscores.
* Each account number should have 9 digits, all of which should be in the range 0-9.
*
* Your task is to write a function that can take bank account string and parse it into actual account numbers.
*
* @param {string} bankAccount
* @return {number}
*
* Example of return :
*
* ' _ _ _ _ _ _ _ \n'+
* ' | _| _||_||_ |_ ||_||_|\n'+ => 123456789
* ' ||_ _| | _||_| ||_| _|\n'
*
* ' _ _ _ _ _ _ _ _ _ \n'+
* '| | _| _|| ||_ |_ ||_||_|\n'+ => 23056789
* '|_||_ _||_| _||_| ||_| _|\n',
*
* ' _ _ _ _ _ _ _ _ _ \n'+
* '|_| _| _||_||_ |_ |_||_||_|\n'+ => 823856989
* '|_||_ _||_| _||_| _||_| _|\n',
*
*/
function parseBankAccount(bankAccount) {
let result = '';
let str = bankAccount.split('\n');
let pattern = RegExp(/(.{3})/);
str = str.map(item => item.split(pattern));
for (let i = 0; i < str[0].length; i++) {
if (str[0][i] === ' _ ' && str[1][i] === '| |' && str[2][i] === '|_|') result += 0;
if (str[0][i] === ' ' && str[1][i] === ' |' && str[2][i] === ' |') result += 1;
if (str[0][i] === ' _ ' && str[1][i] === ' _|' && str[2][i] === '|_ ') result += 2;
if (str[0][i] === ' _ ' && str[1][i] === ' _|' && str[2][i] === ' _|') result += 3;
if (str[0][i] === ' ' && str[1][i] === '|_|' && str[2][i] === ' |') result += 4;
if (str[0][i] === ' _ ' && str[1][i] === '|_ ' && str[2][i] === ' _|') result += 5;
if (str[0][i] === ' _ ' && str[1][i] === '|_ ' && str[2][i] === '|_|') result += 6;
if (str[0][i] === ' _ ' && str[1][i] === ' |' && str[2][i] === ' |') result += 7;
if (str[0][i] === ' _ ' && str[1][i] === '|_|' && str[2][i] === '|_|') result += 8;
if (str[0][i] === ' _ ' && str[1][i] === '|_|' && str[2][i] === ' _|') result += 9;
}
return result;
}
/**
* Returns the string, but with line breaks inserted at just the right places to make sure that no line is longer than the specified column number.
* Lines can be broken at word boundaries only.
*
* @param {string} text
* @param {number} columns
* @return {Iterable.<string>}
*
* @example :
*
* 'The String global object is a constructor for strings, or a sequence of characters.', 26 => 'The String global object',
* 'is a constructor for',
* 'strings, or a sequence of',
* 'characters.'
*
* 'The String global object is a constructor for strings, or a sequence of characters.', 12 => 'The String',
* 'global',
* 'object is a',
* 'constructor',
* 'for strings,',
* 'or a',
* 'sequence of',
* 'characters.'
*/
function* wrapText(text, columns) {
let result = '';
if (text.length <= columns) {
return yield text;
}
while (text) {
let edge = text.slice(0, columns + 1).lastIndexOf(' ');
if (edge > 0) {
result = text.slice(0, edge);
yield result.trim();
text = text.slice(edge).trim();
} else {
return yield text;
}
}
}
/**
* Returns the rank of the specified poker hand.
* See the ranking rules here: https://en.wikipedia.org/wiki/List_of_poker_hands.
*
* @param {array} hand
* @return {PokerRank} rank
*
* @example
* [ '4♥','5♥','6♥','7♥','8♥' ] => PokerRank.StraightFlush
* [ 'A♠','4♠','3♠','5♠','2♠' ] => PokerRank.StraightFlush
* [ '4♣','4♦','4♥','4♠','10♥' ] => PokerRank.FourOfKind
* [ '4♣','4♦','5♦','5♠','5♥' ] => PokerRank.FullHouse
* [ '4♣','5♣','6♣','7♣','Q♣' ] => PokerRank.Flush
* [ '2♠','3♥','4♥','5♥','6♥' ] => PokerRank.Straight
* [ '2♥','4♦','5♥','A♦','3♠' ] => PokerRank.Straight
* [ '2♥','2♠','2♦','7♥','A♥' ] => PokerRank.ThreeOfKind
* [ '2♥','4♦','4♥','A♦','A♠' ] => PokerRank.TwoPairs
* [ '3♥','4♥','10♥','3♦','A♠' ] => PokerRank.OnePair
* [ 'A♥','K♥','Q♥','2♦','3♠' ] => PokerRank.HighCard
*/
const PokerRank = {
StraightFlush: 8,
FourOfKind: 7,
FullHouse: 6,
Flush: 5,
Straight: 4,
ThreeOfKind: 3,
TwoPairs: 2,
OnePair: 1,
HighCard: 0
}
function getPokerHandRank(hand) {
throw new Error('Not implemented');
/*let SF = true, FK = true, FH = true, F = true, S = true, TK = true, TP = true, OP = true, HC = true;
let card = ['A♣','2♣','3♣','4♣','5♣','6♣','7♣','8♣','9♣','10♣','J♣','Q♣','K♣',
'A♦','2♦','3♦','4♦','5♦','6♦','7♦','8♦','9♦','10♦','J♦','Q♦','K♦',
'A♥','2♥','3♥','4♥','5♥','6♥','7♥','8♥','9♥','10♥','J♥','Q♥','K♥',
'A♠','2♠','3♠','4♠','5♠','6♠','7♠','8♠','9♠','10♠','J♠','Q♠','K♠'];
hand.sort(
(a, b) => card.indexOf(a) - card.indexOf(b)
);
for (let i=1; i < hand.length; i++) {
if(SF && (card.indexOf(hand[i - 1]) - card.indexOf(hand[i])) != 1) {
SF = false;
}
if(FK) {
}
}
return PokerRank.HighCard;*/
}
/**
* Returns the rectangles sequence of specified figure.
* The figure is ASCII multiline string comprised of minus signs -, plus signs +, vertical bars | and whitespaces.
* The task is to break the figure in the rectangles it is made of.
*
* NOTE: The order of rectanles does not matter.
*
* @param {string} figure
* @return {Iterable.<string>} decomposition to basic parts
*
* @example
*
* '+------------+\n'+
* '| |\n'+
* '| |\n'+ '+------------+\n'+
* '| |\n'+ '| |\n'+ '+------+\n'+ '+-----+\n'+
* '+------+-----+\n'+ => '| |\n'+ , '| |\n'+ , '| |\n'+
* '| | |\n'+ '| |\n'+ '| |\n'+ '| |\n'+
* '| | |\n' '+------------+\n' '+------+\n' '+-----+\n'
* '+------+-----+\n'
*
*
*
* ' +-----+ \n'+
* ' | | \n'+ '+-------------+\n'+
* '+--+-----+----+\n'+ '+-----+\n'+ '| |\n'+
* '| |\n'+ => '| |\n'+ , '| |\n'+
* '| |\n'+ '+-----+\n' '+-------------+\n'
* '+-------------+\n'
*/
function* getFigureRectangles(figure) {
throw new Error('Not implemented');
}
module.exports = {
parseBankAccount : parseBankAccount,
wrapText: wrapText,
PokerRank: PokerRank,
getPokerHandRank: getPokerHandRank,
getFigureRectangles: getFigureRectangles
};
|
const getJSON = stream => {
return new Promise((resolve, reject) => {
const chunks = []
stream.on('data', chunk => chunks.push(chunk))
stream.on('error', reject)
stream.on('end', () => {
resolve(JSON.parse(Buffer.concat(chunks).toString()))
})
})
}
module.exports = getJSON
|
// public/scripts/reportController.js
(function() {
'use strict';
var ReportController = [
'$http',
'$scope',
'$state',
'$stateParams',
'$document',
'$anchorScroll',
'$location',
'$rootScope',
'noteService',
'usersService',
'spinnerService',
function ReportController(
$http,
$scope,
$state,
$stateParams,
$document,
$anchorScroll,
$location,
$rootScope,
noteService,
usersService,
spinnerService)
{
var ctrl = this;
$scope.currentUser = $scope.$parent.currentUser;
$scope.notes = [];
$scope.jobs = [];
$scope.date = [];
$scope.mansioni = [];
$scope.today = new Date();
$scope.assignees = [];
ctrl.period = 'week';
$scope.searchUsers = function(query) {
usersService.getUsers(query).then(function (data){
$scope.assignees = data;
})
}
$scope.filterUser = function(user) {
$scope.assignee = user;
$scope.notes = [];
$scope.date = [];
$scope.jobs = [];
ctrl.getReport(ctrl.period, user);
}
$scope.openJobs = function(index) {
$scope.mansioni[index] = !$scope.mansioni[index];
}
ctrl.getReport = function(period, user) {
spinnerService.show('notesSpinner');
ctrl.period = period;
noteService.getReport(ctrl.period, user).then(function(data) {
spinnerService.hide('notesSpinner');
$scope.notes = data.notes;
$scope.date = data.date;
$scope.jobs = data.jobs;
});
};
$scope.loadReport = function(){
ctrl.getReport();
}
}];
angular
.module('touchpoint')
.controller('ReportController', ReportController);
})();
|
const db = require('../config/database');
const Sequelize = require('sequelize');
const Item = db.define('item', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
name: {
type: Sequelize.STRING(255),
allowNull: false
},
imageUrl: {
type: Sequelize.STRING(255),
allowNull: false
},
price: {
type: Sequelize.INTEGER,
allowNull: false
},
description: {
type: Sequelize.STRING(500)
},
category: {
type: Sequelize.STRING
},
size_qty: {
type: Sequelize.JSON
}
}, {
freezeTableName: true,
timestamps: false
});
Item.associate = function (models) {
Item.belongsToMany(models.Order, {through: 'order_item', foreignKey: 'item_id'});
};
module.exports = Item;
|
import React from 'react'
import {CommentWrap,ComListWrap} from './Comments.styled'
const Comments = (props) => {
return (
<CommentWrap>
<div className='title'>
<h1>精彩评论</h1>
<span>{props.data.length }条</span>
</div>
<ul >
{
props.data.map((value,index) => {
return (
<ComListWrap width="0 0 1px 0"
key = {value.remake.rid}>
<div className='profile'><img src={value.uport} alt="" /></div>
<div className='content'>
<div className='header'>
<span>{value.petname}</span>
<div className="date">{value.remake.comm_time}</div>
</div>
<p>{value.remake.rmsg}</p>
<div className='image'>
<div><img src={value.remake.rpic} alt=""/></div>
{/* {
value.rpic && value.rpic((value,index) => {
return (
<div key ={index}><img src={value} alt="" /></div>
)
})
} */}
</div>
</div>
</ComListWrap>
)
})
}
</ul>
</CommentWrap>
)
}
export default Comments
|
window.sberCareChat.init({
mode: 'full',
withBot: true,
jsonSrc: '/data/json/',
// botScenarioUrl: '/data/json/trouble.json',
crossOrigin: true,
videoSrc: '/data/video/',
videoQuality: 'sd',
startForm: "Chat", // 'Chat' | 'Icon'
mainBundlePath: "./preview/2.1.8/",
mountContainerId: 'chat_container',
theme: {
name: 'default' // "default" | "light" | "dark"
},
chatVersion: '2.1.8',
headerIsEnabled: false,
domain: "test2.sberbank.ru", // по умолчанию location.host
applicationName: "sberCare",
firstMessage: {
enable: false,
text: 'Здравствуйте! Я виртуальный помощник. С радостью отвечу на ваши вопросы!',
format: 'markdown', // plain | markdown
},
apiRestUrl: 'https://messenger-t.sberbank.ru/api/device',
apiWSUrl: 'wss://messenger-t.sberbank.ru/api/',
dictionary: {
headerTitle: "Связь с банком",
connectionError: "Пожалуйста, обратитесь в контактный центр, позвоните на номер 900 или +7 495 500-55-50 - для звонков из любой точки мира",
botName: "Помощник от Сбербанка"
}
});
|
import React from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
const cityTimeData = [
['서울',10],
['베이징',9],
['시드니',12],
['LA',17],
['부산',10],
]
const WorldClockList = cityTimeData.map((citytime)=>
<WorldClock city={citytime[0]} time={citytime[1]}/>)
</WorldClock>
return (
<div className="App">
<header className="App-header">
<h1 className={'myStyle'}>안녕~~</h1>
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<WorldClock city={'서울'} time={10}/>
<WorldClock city={'베이징'} time={10}/>
<WorldClock city={'시드니'} time={10}/>
<WorldClock city={'LA'} time={10}/>
{WorldClockList}
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
function WorlClock(props){
return(
<div className={"WorldClock"}>
<h2>도시: {props.city}</h2>
<p>시간: {props.time}시</p>
</div>
)
}
export default App;
|
/**
* 给定一个二叉树,判断其是否是一个有效的二叉搜索树。
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isValidBST = function (root) {
// 中序遍历后的树结果
var bstArray = [];
// 中序遍历
var traverse = function (root) {
if (!root) return;
traverse(root.left);
bstArray.push(root.val);
traverse(root.right);
};
traverse(root);
let isValid = true;
// 比较中序遍历后的前后值,应该为顺序排列,出现非顺序时为异常
for (let i = 0; i < bstArray.length - 1; i++) {
if (bstArray[i] >= bstArray[i + 1]) {
isValid = false;
}
}
return isValid;
};
|
/**
* Created by hugo on 2018/8/29.
*/
// 检查浏览器是否对 serviceWorker 有原生支持
if ('serviceWorker' in navigator) {
// 有原生支持时,在页面加载后开启新的 Service Worker 线程,从而优化首屏加载速度
window.addEventListener('load', function () {
// register 方法里第一个参数为 Service Worker 要加载的文件;第二个参数 scope 可选,用来指定 Service Worker 控制的内容的子目录
navigator.serviceWorker.register('/js/workbox-injectManifest-config.js').then(function (registration) {
// Service Worker 注册成功
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}).catch(function (err) {
// Service Worker 注册失败
console.log('ServiceWorker registration failed: ', err);
});
});
}
|
let req = require.context('./', true, /([a-z])\.js/)
let grapherList = req.keys().filter( (item) => {
return (
item.includes('index') === false &&
item.includes('style') === false &&
item.includes('storeMap') === false &&
item.includes('snapshot') === false)
})
let list = {}
grapherList.map( (item) => {
let len = item.length
let lastIndex = item.lastIndexOf('.')
let name = item.substr(2, lastIndex - 2)
let modules = require(`./${name}.js`)
let key = name.split('/')[0]
list[key] = modules.default ? modules.default : modules
})
export default list
|
var searchData=
[
['def_5ftemp_385',['DEF_TEMP',['../proj_8c.html#a851f5027f3ded5455c1308f2d86664a2',1,'proj.c']]]
];
|
const express = require("express")
const firstApp = express()
firstApp.get('/', (req, res) => {
res.send('First App...')
})
firstApp.get('/first', (req, res) => {
res.send('First Section...')
})
module.exports = firstApp
|
import React, { useState, useEffect, useContext } from "react";
import { DataContext } from "../App";
import $ from "jquery";
import { FaAngleUp } from "react-icons/fa";
function ShowJobs() {
const allJobs = useContext(DataContext);
const [title, changeTitle] = useState("");
const [location, changeLocation] = useState("");
const [type, changeType] = useState("");
const [page, changePage] = useState(1);
const [showData, changeShowData] = useState([]);
function calcDate(created_at) {
let date = new Date(Date.parse(created_at));
return `${date.getDate()}/${date.getMonth()}/${date.getFullYear()}`;
}
function changebgc() {
$(`#num${page}`).css("background-color", "yellow");
$(`#num${page}`).siblings().css("background-color", "aqua");
}
function countPages() {
let arr = [];
if (Math.ceil(showData.length / 30) === 1) return [];
for (let j = 1; j <= Math.ceil(showData.length / 30); j++) {
arr.push(
<p
key={j}
id={`num${j}`}
onClick={(e) => {
document.documentElement.scrollTo(0, 0);
changePage(j);
}}
>
{" "}
{j}
</p>
);
}
return arr;
}
useEffect(() => {
// changeshowdata(allJobs);
changeShowData(
allJobs
.filter((job) => {
return (
job.title.toLowerCase().indexOf(title.toLowerCase()) !== -1 &&
job.location.toLowerCase().indexOf(location.toLowerCase()) !== -1 &&
job.type.toLowerCase().indexOf(type.toLowerCase()) !== -1
);
})
.map((job, index) => {
return (
<div id="indi-job" key={index}>
<p id="role">
{job.title}{" "}
<a
href={job.company_url}
target="_blank"
rel="noreferrer"
id="company"
>
({job.company})
</a>
</p>
<p id="time">
Job created on <span>{calcDate(job.created_at)}</span>
</p>
<div id="labels">
<p>{job.location}</p>
<p>{job.type}</p>
</div>
<a id="job_info" href={job.url} rel="noreferrer" target="_blank">
View job details
</a>
{job.company_logo ? (
<img src={job.company_logo} alt="loading" />
) : (
""
)}
</div>
);
})
);
changePage(1);
}, [allJobs, title, location, type]);
function titleChange(e) {
changeTitle(e.target.value);
}
function locationChange(e) {
changeLocation(e.target.value);
}
function typeChange(e) {
changeType(e.target.value);
}
return (
<div id="container">
<div id="search">
<div id="title">
<p>Title :</p>
<input
type="text"
placeholder="search by title"
onChange={titleChange}
/>
</div>
<div id="location">
<p>Location :</p>
<input
type="text"
placeholder="search by location"
onChange={locationChange}
/>
</div>
<select id="type" onChange={typeChange}>
<option value=""> Select</option>
<option value="Full Time"> Full Time</option>
<option value="Part Time"> Part Time</option>
</select>
</div>
{/* ----------------jobs portion ------------*/}
<div id="jobs">
<p id="found">{showData.length} results found</p>
{showData.length ? (
showData.slice((page - 1) * 30, page * 30)
) : (
<p id="no_data">No Data Found</p>
)}
</div>
<div id="pageNum">{countPages()}</div>
{changebgc()}
<p id="goTop" onClick={() => document.documentElement.scrollTo(0, 0)}>
<FaAngleUp id="arrow" />
</p>
<p id="end">Built and Designed with ❤️ </p>
</div>
);
}
export default ShowJobs;
|
const cardsContainer = document.getElementById('cards-container');
const prevBtn = document.getElementById('prev');
const nextBtn = document.getElementById('next');
const currentEl = document.getElementById('current-card-number');
const showBtn = document.getElementById('show');
const hideBtn = document.getElementById('hide');
const questionEl = document.getElementById('question');
const answerEl = document.getElementById('answer');
const addCardBtn = document.getElementById('add-card');
const clearBtn = document.getElementById('clear');
const addContainer = document.getElementById('add-container');
// GLOBAL VARIABLES
// ================
let currentActiveCard = 0;
const cardsData = getCardsData(); // The Card Data in local storage
const cardsArray =[]; // Array Holding the Cards to be used for export to local storage. And Counting Number of Cards
// DUMMY DATA
// ==========
// const cardsData = [
// {
// question: 'What must a variable begin with?',
// answer: 'A letter, $ or _'
// },
// {
// question: 'What is a variable?',
// answer: 'Container for a piece of data'
// },
// {
// question: 'Example of Case Sensitive Variable',
// answer: 'thisIsAVariable'
// }
// ];
// FUNCTIONS
// =========
// createCards() - iterates through the card data Array to create a card in the DOM
// =============
function createCards(){
cardsData.forEach((data, index)=>createCard(data, index));
}
createCards(); // Automatic load of cards.
// createCard()
// ============
// 1. Create div element
// 2. Add Classes
// 3. Add Html
// 4. Add an EventListener to swith the card over
// 5. Append card to parent div in the DOM
// 6. Push onto Cards array.
function createCard(data , index){
const card = document.createElement('div');
card.classList.add('card');
if(index === 0) {
card.classList.add('active');
}
card.innerHTML = `
<div class="inner-card">
<div class="inner-card-front">
<p>${data.question}</p>
</div>
<div class="inner-card-back">
<p>${data.answer}</p>
</div>
</div>
`;
card.addEventListener('click', ()=> {card.classList.toggle('show-answer')});
cardsContainer.appendChild(card);
cardsArray.push(card);
updateCardNumber();
}
// updateCardNumber() - Update the Card's order Number shown in the DOM
// =================
function updateCardNumber(){
currentEl.innerText = `
${currentActiveCard+1}/${cardsArray.length}
`;
}
// getCardsData() - get Data from Local Storage
// ==============
function getCardsData(){
const cards = JSON.parse(localStorage.getItem('cards'));
return cards === null ? [] : cards;
}
// setCardsData() - Put data into local storage
// ==============
function setCardsData(cards) {
localStorage.setItem('cards', JSON.stringify(cards));
window.location.reload();
}
// EVENT LISTENERS
// ===============
showBtn.addEventListener('click',()=>{
addContainer.classList.add('show');
});
hideBtn.addEventListener('click', ()=>{
addContainer.classList.remove('show');
});
// Opens up input form for user to create a Card
addCardBtn.addEventListener('click',() =>{
const question = questionEl.value;
const answer = answerEl.value;
if(question.trim() && answer.trim()){
const newCard = {question, answer}
createCard(newCard);
questionEl.value ='';
answerEl.value = '';
addContainer.classList.remove('show'); // close form using CSS
cardsData.push(newCard); // Add to card Data Array
setCardsData(cardsData); // Update local storage
}
});
// Next Card Btn
nextBtn.addEventListener('click',()=> {
cardsArray[currentActiveCard].className = 'card left';
currentActiveCard++;
if(currentActiveCard > cardsArray.length -1 ){
currentActiveCard = cardsArray.length -1;
}
cardsArray[currentActiveCard].className = 'card active';
updateCardNumber();
});
// Prev Card Btn
prevBtn.addEventListener('click',()=> {
cardsArray[currentActiveCard].className = 'card right';
currentActiveCard--;
if(currentActiveCard < 0 ){
currentActiveCard = 0;
}
cardsArray[currentActiveCard].className = 'card active';
updateCardNumber();
});
// Wipes All Cards in DOM and local storage
clearBtn.addEventListener('click', ()=>{
localStorage.clear();
cardsContainer.innerHTML = '';
window.location.reload();
});
|
//*****************************************************************************
//********************************** GET **************************************
//*****************************************************************************
var token = localStorage.getItem('MonToken');
//****************getCurrentUser************************
$(document).ready(function () {
//****************getMyTrainings*****************************
//$(document).on('click', '#home-tab', function () {
$(document).ready(function () {
$.ajax({
url: BACKEND_URL + 'teacher/getMyTrainings',
type: 'get',
dataType: 'json',
contentType: 'application/json',
headers: {
Authorization: `Bearer ${ token }`
},
success: function (response) {
console.log("success");
$("#cours").empty();
$.each(response, function (i, training) {
$("#cours").append('<tr>' +
'<td>' + training.subject + '</td>' +
'<td>' + new Date(training.startDatetime).toLocaleString() + '</td>' +
'<td>' + new Date(training.endDatetime).toLocaleString() + '</td>' +
'<td><button id=' + i + ' type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#myModalDisplayTeacher"><i class="fas fa-eye"></i> Afficher</button> <button id=' + i + ' type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#myModalUpdateTraining"><i class="fas fa-pen"></i> Editer</button> <button id=' + i + ' type="button" class="btn btn-danger btn-sm"><i class="fas fa-trash"></i> Supprimer</button><br /></td>' +
'</tr>')
});
$('#tabcours').DataTable({
"paging": true,
"lengthChange": true,
"searching": true,
"ordering": true,
"info": true,
"autoWidth": false,
"responsive": true,
"language": {
"url": "vendor/datatable.french.json"
}
});
},
error: function (jqxhr) {
$('#errorTeacher').fadeIn();
$('#errorTeacher').delay(6000).fadeOut();
},
});
});
//****************getTrainingById*****************************
$(document).on('click', ".btn-success", function (e) {
e.preventDefault();
console.log($(this).attr('id'));
$.ajax({
url: BACKEND_URL + 'training/getTrainingById?id=' + $(this).attr('id'),
type: 'GET',
dataType: 'json',
contentType: 'application/json',
headers: {
Authorization: `Bearer ${ token }`
},
success: function (response) {
$("h1[name=NameTeacher]").empty().append(response.teacher['lastname'] + " " + response.teacher['firstname']);
$("p[name=training_id]").empty().append(response.id);
$('p[name=start_training]').empty().append(new Date(response.startTraining.substring(0, 19)).toLocaleString());
$('p[name=end_training]').empty().append(new Date(response.endTraining.substring(0, 19)).toLocaleString());
$('p[name=max_student]').empty().append(response.maxStudent);
$('p[name=price_per_student]').empty().append(response.pricePerStudent);
$('p[name=training_description]').empty().append(response.trainingDescription);
$('p[name=subject]').empty().append(response.subject);
},
error: function (jqXhr) {
$('#errorTeacher').fadeIn();
$('#errorTeacher').delay(6000).fadeOut();
},
});
});
//****************getTrainingById (pour récuperer les Students)***********************
//$(document).on('click', "#profile-tab", function (e) {
$(document).ready(function () {
$.ajax({
url: BACKEND_URL + 'teacher/getMyTrainings',
type: 'get',
dataType: 'json',
contentType: 'application/json',
headers: {
Authorization: `Bearer ${ token }`
},
success: function (response) {
console.log("success");
$("#students").empty();
$.each(response, function (i, training) {
$.ajax({
url: BACKEND_URL + 'training/getTrainingById?id=' + i,
type: 'get',
dataType: 'json',
contentType: 'application/json',
headers: {
Authorization: `Bearer ${ token }`
},
success: function (response) {
console.log("success");
$.each(response.participants, function (i, student) {
$("#students").append('<tr>' +
'<td>' + student.firstname + '</td>' +
'<td>' + student.lastname + '</td>' +
'<td>' + response.subject + '</td>' +
//'<td><button id=' + student.id + ' type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#myModalDisplayStudent">Afficher</button></td>' +
'</tr>')
});
// table = $('#tabstudents').DataTable();
// //table.destroy();
// $('#tabstudents').DataTable({
// "retrieve": true,
// "paging": true,
// "lengthChange": true,
// "searching": true,
// "ordering": true,
// "info": true,
// "autoWidth": false,
// "responsive": true,
// "language": {
// "url": "vendor/datatable.french.json"
// }
// });
},
error: function (jqxhr) {
$('#errorTeacher').fadeIn();
$('#errorTeacher').delay(6000).fadeOut();
},
});
});
},
error: function (jqxhr) {
$('#errorTeacher').fadeIn();
$('#errorTeacher').delay(6000).fadeOut();
},
});
});
//*****************************************************************************
//********************************** POST *************************************
//*****************************************************************************
//****************addTraining**************************
$("#submit_training").click(function (e) {
e.preventDefault();
console.log(currentUser.id);
$.ajax({
url: BACKEND_URL + 'training/addTraining',
type: 'POST',
data: {
teacher_id: currentUser.id,
start_training: $('input[name = start_training]').val(),
end_training: $('input[name = end_training]').val(),
max_student: $('input[name = max_student]').val(),
price_per_student: $('input[name = price_per_student]').val(),
training_description: $('input[name = training_description]').val(),
subject: $('input[name = subject]').val()
},
headers: {
Authorization: `Bearer ${ token }`
},
success: function () {
$('#successTeacher').fadeIn();
$('#successTeacher').delay(6000).fadeOut();
//location.reload(true);
table = $('#tabcours').DataTable();
table.destroy();
RefreshTab();
},
error: function (jqXhr) {
$('#errorTeacher').fadeIn();
$('#errorTeacher').delay(6000).fadeOut();
},
});
});
//****************createUser******************************
$(document).on('click', '#submit_s', function (e) {
e.preventDefault();
$("span[style^='color:red']").empty();
if ($("#email").val().length === 0) {
$("#email").after('<span style="color:red"> Merci de remplir ce champ !</span>');
} else if (!$("#email").val().match(/^[a-zA-Z0-9\.\-_]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,5}$/i)) { //Regex validation mail
$("#email").after('<span style="color:red"> Mail invalide !</span>');
} else if ($("#password").val().length === 0) {
$("#password").after('<span style="color:red"> Merci de remplir ce champ !</span>');
} else if (!$("#password").val().match(/^(?=.*[a-z])(?=.*[0-9]).{6,}$/i)) { //Regex=> 6 caractéres au moins une lettre et un chiffre
$("#password").after('<span style="color:red"> 6 caractéres minimum dont un [a-b] et un [0-9] !</span>');
} else {
var form = $("#formS")[0]; //On récupére le formulaire par son id
var data = new FormData(form); //On le passe en param dans l'objet FormData
console.log(data);
$.ajax({
url: BACKEND_URL + 'admin/createUser',
type: 'POST',
data: data,
contentType: false,
cache: false,
processData: false, //Important
enctype: 'multipart/form-data',
headers: {
Authorization: `Bearer ${ token }`
},
success: function (jqXhr) {
//alert(jqXhr.responseText);
$('#successTeacher').fadeIn();
$('#successTeacher').delay(6000).fadeOut();
//location.reload(true);
},
error: function (jqXhr) {
$('#errorTeacher').fadeIn();
$('#errorTeacher').delay(6000).fadeOut();
//location.reload(true);
},
});
}
});
//*****************************************************************************
//********************************** DELETE ***********************************
//*****************************************************************************
//****************deleteTraining****************************
$(document).on('click', ".btn-danger", function (e) {
e.preventDefault();
console.log($(this).attr('id'));
if (confirm("Etes-vous sûr de vouloir supprimer ce Training ?")) {
$.ajax({
url: BACKEND_URL + 'admin/deleteTraining?id = ' + $(this).attr('id'),
type: 'DELETE',
headers: {
Authorization: `Bearer ${ token }`
},
success: function (response) {
$('#successTeacher').fadeIn();
$('#successTeacher').delay(6000).fadeOut();
//location.reload(true);
},
error: function (jqXhr) {
$('#errorTeacher').fadeIn();
$('#errorTeacher').delay(6000).fadeOut();
},
});
}
});
//*****************************************************************************
//********************************** PUT **************************************
//*****************************************************************************
//****************updateTraining*************************
$(document).on('click', ".btn-primary", function (e) {
e.preventDefault();
console.log($(this).attr('id'));
if (confirm("Etes-vous sûr de vouloir modifier ce Training ?")) {
$.ajax({
url: BACKEND_URL + 'training/getTrainingById?id=' + $(this).attr('id'),
type: 'GET',
dataType: 'json',
contentType: 'application/json',
headers: {
Authorization: `Bearer ${ token }`
},
success: function (response) {
var chnStart = response.startTraining;
var start = chnStart.substring(0, 19);
var chnEnd = response.endTraining;
var end = chnEnd.substring(0, 19);
$("input[name=training_id]").val(response.id);
$('#start_training').val(start);
$('#end_training').val(end);
$('#max_student').val(response.maxStudent);
$('#price_per_student').val(response.pricePerStudent);
$('#training_description').val(response.trainingDescription);
$('#subject').val(response.subject);
$('#formUpdateTraining').toggle("slide");
$("#submit_u").click(function (e) {
e.preventDefault();
data = {
"id": $('#training_id').val(),
"startTraining": $('#start_training').val(),
"endTraining": $('#end_training').val(),
"maxStudent": $('#max_student').val(),
"pricePerStudent": $('#price_per_student').val(),
"trainingDescription": $('#training_description').val(),
"subject": $('#subject').val()
};
$.ajax({
url: BACKEND_URL + 'teacher/updateTraining',
type: 'PUT',
dataType: 'json', //type de données qu'on attend en réponse du serveur
contentType: "application/json",
processData: false, //Définit à false permet d'eviter => application / x-www-form-urlencoded(par default)
data: JSON.stringify(data),
headers: {
Authorization: `Bearer ${ token }`
},
success: function () {
$('#successTeacher').fadeIn();
$('#successTeacher').delay(6000).fadeOut();
//location.reload(true);
table = $('#tabcours').DataTable();
table.destroy();
RefreshTab();
},
error: function (jqXhr) {
$('#errorTeacher').fadeIn();
$('#errorTeacher').delay(6000).fadeOut();
},
});
});
},
error: function (jqXhr) {
$('#errorTeacher').fadeIn();
$('#errorTeacher').delay(6000).fadeOut();
},
});
} else {
location.reload(true);
//location.href = 'teacher.html';
}
});
//****************updateCurrentUser*****************************
$(document).on('click', "#modalUpdateProfil", function (e) {
//e.preventDefault();
if (confirm("Etes-vous sûr de vouloir modifier votre profil ?")) {
$.ajax({
url: BACKEND_URL + 'user/getCurrentUser',
type: 'GET',
dataType: 'json',
contentType: 'application/json',
headers: {
Authorization: `Bearer ${ token }`
},
success: function (response) {
$("input[name=email]").val(response.email);
$('input[name=lastname]').val(response.lastname);
$('input[name=firstname]').val(response.firstname);
$('input[name=phone]').val(response.phone);
$('input[name=address]').val(response.address);
$('input[name=postcode]').val(response.postcode);
$('input[name=city]').val(response.city);
$("#submit_up").click(function (e) {
e.preventDefault();
data = {
"email": $("input[name=email]").val(),
"lastname": $('input[name=lastname]').val(),
"firstname": $('input[name=firstname]').val(),
"phone": $('input[name=phone]').val(),
"address": $('input[name=address]').val(),
"postcode": $('input[name=postcode]').val(),
"city": $('input[name=city]').val()
};
$.ajax({
url: BACKEND_URL + 'user/updateCurrentUser',
type: 'PUT',
dataType: 'json', //type de données qu'on attend en réponse du serveur
contentType: "application/json",
processData: false, //Définit à false permet d'eviter => application / x-www-form-urlencoded(par default)
data: JSON.stringify(data),
headers: {
Authorization: `Bearer ${ token }`
},
success: function () {
$('#successTeacher').fadeIn();
$('#successTeacher').delay(6000).fadeOut();
//location.reload(true);
},
error: function (jqXhr) {
$('#errorTeacher').fadeIn();
$('#errorTeacher').delay(6000).fadeOut();
},
});
});
},
error: function (jqXhr) {
$('#errorTeacher').fadeIn();
$('#errorTeacher').delay(6000).fadeOut();
},
});
} else {
location.reload(true);
//$('#bodyTeacher').reload(' #bodyTeacher');
//location.href = 'teacher.html';
}
});
//****************updatePassword*****************************
$("#submit_mdp").click(function (e) {
e.preventDefault();
if ($("#oldpassword").val().length === 0) {
$("#credsMissing").fadeIn();
} else if ($("#newpassword").val().length === 0) {
$("#credsMissing").fadeIn();
} else if (!$("#newpassword").val().match(/^(?=.*[a-z])(?=.*[0-9]).{6,}$/i)) { //Regex=> 6 caractéres au moins une lettre et un chiffre
$("#logerror").fadeIn();
} else {
$("#credsMissing").fadeOut();
$("#logerror").fadeOut();
data = {
"oldPassword": $("input[name=oldpassword]").val(),
"newPassword": $('input[name=newpassword]').val(),
};
$.ajax({
url: BACKEND_URL + 'user/passwordUpdate',
type: 'PUT',
dataType: 'json', //type de données qu'on attend en réponse du serveur
contentType: "application/json",
processData: false, //Définit à false permet d'eviter => application / x-www-form-urlencoded(par default)
data: JSON.stringify(data),
headers: {
Authorization: `Bearer ${ token }`
},
success: function () {
$('#successUpdatePassword').fadeIn();
//location.reload(true);
},
error: function (jqXhr) {
$('#errorUpdatePassword').fadeIn();
//$('#formPass').load('teacher.html #inputMdp');
//alert(jqXhr.responseText);
//location.reload(true);
},
});
}
});
});
//*******************************FONCTIONS**************************************
function RefreshTab() {
$.ajax({
url: BACKEND_URL + 'teacher/getMyTrainings',
type: 'get',
dataType: 'json',
contentType: 'application/json',
headers: {
Authorization: `Bearer ${ token }`
},
success: function (response) {
console.log("success");
$("#cours").empty();
$.each(response, function (i, training) {
$("#cours").append('<tr>' +
'<td>' + training.subject + '</td>' +
'<td>' + new Date(training.startDatetime).toLocaleString() + '</td>' +
'<td>' + new Date(training.endDatetime).toLocaleString() + '</td>' +
'<td><button id=' + i + ' type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#myModalDisplayTeacher"><i class="fas fa-eye"></i> Afficher</button> <button id=' + i + ' type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#myModalUpdateTraining"><i class="fas fa-pen"></i> Editer</button> <button id=' + i + ' type="button" class="btn btn-danger btn-sm"><i class="fas fa-trash"></i> Supprimer</button><br /></td>' +
'</tr>')
});
$('#tabcours').DataTable({
//"retrieve": true,
"paging": true,
"lengthChange": true,
"searching": true,
"ordering": true,
"info": true,
"autoWidth": false,
"responsive": true,
"language": {
"url": "vendor/datatable.french.json"
}
});
},
error: function (jqxhr) {
$('#errorTeacher').fadeIn();
$('#errorTeacher').delay(6000).fadeOut();
},
});
}
|
import database from './database.config'
import server from './server.config'
class Config {
constructor() {
this._databaseConfig = database
this._serverConfig = server
}
get databaseConfig () {
return this._databaseConfig
}
get serverConfig () {
return this._serverConfig
}
}
const config = new Config()
export const databaseConfig = config._databaseConfig
export const serverConfig = config._serverConfig
|
class Notification {
constructor(kind, value, error) {
this.kind = kind
this.value = value
this.error = error
}
subscribe(subscriber) {
switch (this.kind) {
case 'N':
return subscriber.sendNext(this.value)
case 'E':
return subscriber.sendError(this.error)
case 'C':
return subscriber.sendComplete()
}
}
static createNext(value) {
return new Notification('N', value)
}
static createError(err) {
return new Notification('E', undefined, err)
}
static createComplete() {
return new Notification('C')
}
}
module.exports = Notification
|
//Selectors
let toDoContainer = document.querySelector("#todo-list");
let inputField = document.querySelector(".form-control")
let ticks = document.querySelectorAll('i:last-child');
let deletes = document.querySelectorAll('i:first-child');
let liTicksDeleteContainer = document.querySelectorAll('li');
let addNewTodoContainer = document.querySelector('.add-todo')
let ulEntire = document.querySelectorAll('ul')
let btnDelete = document.querySelector('.btn__delete')
// These are the same todos that currently display in the HTML
// You will want to remove the ones in the current HTML after you have created them using JavaScript
let todos = [
{ task: "Wash the dishes", completed: false },
{ task: "Do the shopping", completed: false },
{ task: "Wash the dishes", completed: false },
{ task: "Do the shopping", completed: false },
{ task: "Wash the dishes", completed: false },
{ task: "Do the shopping", completed: false },
{ task: "Wash the dishes", completed: false },
{ task: "Do the shopping", completed: false },
{ task: "Wash the dishes", completed: false },
{ task: "Do the shopping", completed: false },
];
// This function is creating new todo element
function addNewTodo(event) {
if (inputField.value.length) {
// The code below prevents the page from refreshing when we click the 'Add Todo' button.
event.preventDefault();
let newToDo = inputField.value;
toDoContainer.insertAdjacentHTML('beforeend', paternOfToDo(newToDo));
let lastTodo = document.querySelector('li:last-child')
lastTodo.addEventListener("click", deleteLineTick)
inputField.value = '';
}
}
// pater of todo element in html
const paternOfToDo = function (item) {
let text = ` <li class="list-group-item d-flex justify-content-between align-items-center">${item}
<span class="badge bg-primary rounded-pill">
<!-- each of these <i> tags will need an event listener when we create them in Javascript -->
<i data-role="0" class="fa fa-check" aria-hidden="true" ></i>
<i data-role="1" class="fa fa-trash" aria-hidden="true" ></i>
</span>
</li>`
return text
}
// function to delete and line-through
const deleteLineTick = function (e) {
e.preventDefault();
if (e.target.dataset.role === "0") {
if (e.target.parentNode.parentNode.style.textDecoration !== "line-through") {
e.target.parentNode.parentNode.style.textDecoration = "line-through"
} else {
e.target.parentNode.parentNode.style.textDecoration = ""
}
} else if (e.target.dataset.role === "1") {
e.target.parentNode.parentNode.remove()
}
}
//function creating todo from the list of objects
function populateTodoList(todos) {
// let list = document.getElementById("todo-list");
for (let item of todos) {
let tempText = paternOfToDo(item.task)
toDoContainer.insertAdjacentHTML('beforeend', tempText);
let lastTodo = document.querySelector('li:last-child')
lastTodo.addEventListener("click", deleteLineTick)
}
}
let container
// Advanced challenge: Write a fucntion that checks the todos in the todo list and deletes the completed ones
//(we can check which ones are completed by seeing if they have the line-through styling applied or not).
function deleteAllCompletedTodos(e) {
e.preventDefault();
let tempLiList = document.querySelectorAll('li');
for (let item of tempLiList) {
if (item.style.textDecoration === "line-through") item.remove()
}
}
btnDelete.addEventListener('click', deleteAllCompletedTodos)
addNewTodoContainer.addEventListener('click', deleteLineTick)
populateTodoList(todos);
|
/* jshint esversion: 6 */
var express = require('express');
var shell = require('shelljs');
var path = require('path');
const sdkmanager = path.normalize(`${process.env.ANDROID_HOME}/tools/bin/sdkmanager`);
const images = path.normalize(`${process.env.ANDROID_HOME}/system-images/`);
var router = express.Router();
router.get('/', (req, res) => {
let installedImages = shell.ls(images);
res.json(installedImages);
});
router.post('/:version', (req, res) => {
const androidVersion = `android-${req.params.version}`;
shell.exec(`${sdkmanager} "system-images;${androidVersion};google_apis;x86"`, (code, stdout, stderr) => {
console.log('Exit code:', code);
console.log('Program output:', stdout);
console.log('Program stderr:', stderr);
});
res.json({
message: `Trying to install: ${androidVersion}`
});
});
module.exports = router;
|
import imgJumbotron from '../../images/jumbotron.jpg'
class JumboTron extends HTMLElement{
connectedCallback(){
this.render();
}
set clickEvent(event) {
this._clickEvent = event;
this.render();
}
render() {
this.innerHTML = `
<style>
.jumbotron{
background: url(${imgJumbotron});
background-size: cover;
color: white;
text-shadow: 0px 3px 6px black;
border-radius: 0px;
margin-bottom: 0px;
}
.jumbotron h1 span{
font-weight: 500;
}
.jumbotron .input-group{
display: flex;
box-shadow: 0px 3px 6px black;
width: 75%;
z-index: 0;
}
.jumbotron .btn{
background-color: #FF1F71;
color: white;
}
.jumbotron .btn:hover{
background-color: #ff0055;
}
@media screen and (max-width: 767px) {
.jumbotron{
margin-top: 50px !important;
}
.jumbotron h1{
font-size: 24pt;
}
.jumbotron .input-group{
width: 100%;
}
}
</style>
<div class="jumbotron text-center mt-1">
<div class="container mt-5">
<h1 class="display-4 mb-5">Temukan Berjuta Film dan siaran TV. <br><span>Jelajahi sekarang!</span></h1>
<div class="input-group mb-3 ml-auto mr-auto">
<input type="text" class="form-control" id="searchFilm" placeholder="Cari film berdasarkan judul..." aria-label="Cari film berdasarkan judul..." aria-describedby="button-addon2">
<div class="input-group-append">
<button class="btn" type="submit" id="searchButtonElement">Search</button>
</div>
</div>
</div>
</div>`;
this.querySelector("#searchButtonElement").addEventListener("click", this._clickEvent);
}
}
customElements.define('jumbo-tron', JumboTron);
|
var searchData=
[
['x',['x',['../structei__placer__params__t.html#ae8562a49f17673cd02409d34fdc81154',1,'ei_placer_params_t::x()'],['../structei__point__t.html#a6ec4a8846bae4b9694506dae039047b3',1,'ei_point_t::x()']]],
['x_5fdata',['x_data',['../structei__placer__params__t.html#ae6078f805f079c2ac6e54ecfbe321c50',1,'ei_placer_params_t']]]
];
|
import './_bootstrap';
import createServer from 'lib/createServer';
const PORT = process.env.PORT || 3000;
createServer().then(app => {
app.listen(PORT, () => {
const mode = process.env.NODE_ENV;
console.log('Server is ready on', PORT);
});
}, err => {
console.log(err);
});
|
import React, { Component } from 'react'
import { Text, View } from 'react-native'
import Button from './Button';
import Icon from './Icon';
export default class IconButton extends Component {
render() {
const { style, source, title, subtitle, titleStyle, subtitleStyle, size, iconStyle, onPress, buttonContainerStyle, type = "link" } = this.props;
return <Button type={type} style={buttonContainerStyle} onPress={onPress}>
<Icon style={style} iconStyle={iconStyle} source={source} title={title} subtitle={subtitle} titleStyle={titleStyle} subtitleStyle={subtitleStyle} size={size}></Icon>
</Button>
}
}
|
/*
在字符串中找到第一个只出现一次的字符,返回它的位置
1<=字符串长度<=10000,全部由字母组成
*/
/*
思路一:用对象存储每个字符出现的次数(最好)
思路二:从头遍历字符串,对于每个字符,从后开始判断是否出现了相同的字符
*/
// 思路一
function FirstNotRepeatingChar(str) {
var obj = {}
var result = 0
for (var i = 0, len = str.length; i < len; i++) {
if (!obj[str.charAt(i)]) {
obj[str.charAt(i)] = 1
} else {
obj[str.charAt(i)]++
}
}
Object.keys(obj).some((val) => {
if (obj[val] === 1) {
result = val
return true
}
})
return str.indexOf(result)
}
// 思路二
function FirstNotRepeatingChar2(str) {
for (var i = 0, len = str.length; i < len; i++) {
if (str.indexOf(str.charAt(i)) === str.lastIndexOf(str.charAt(i))) {
return i
}
}
return -1
}
var result = FirstNotRepeatingChar('google')
console.log(result.toString())
|
const {createUser, loginUser} = require('./services')
exports.createUser = async(req, res, next) => {
let {userName, email, password, country, state, city, timeZone } = req.body;
try {
let userObj = {
userName, email, password, country, state, city, timeZone
}
let user = await createUser(userObj);
res.json(user);
} catch (error) {
}
}
exports.loginUser = async(req, res, next) =>{
let {username, password} = req.body;
console.log(req.body)
try {
let response = await loginUser(username, password);
res.json(response)
} catch (error) {
throw error
}
}
|
import React, { Component } from 'react';
import './App.css';
import TodoInput from './TodoInput'
import TodoItem from './TodoItem'
import 'normalize.css'
import './reset.css'
import AV from './leancloud'
import UserDialog from './UserDialog'
import {getCurrentUser, signOut, createTodoList, saveDataIdToUser, downloadTodoList} from './leancloud'
// var TodoFolder = AV.Object.extend("TodoFolder")
// var todoFolder = new TodoFolder()
class App extends Component {
constructor(props){
super(props)
this.state={
user: getCurrentUser() || {},
newTodo: '',
todoList: []
}
}
render() {
let todos = this.state.todoList
.filter((item)=> !item.deleted)
.map((item,index)=>{
return (
<li key={index} className>
<TodoItem todo={item} onToggle={this.toggle.bind(this)}
onDelete={this.delete.bind(this)} />
</li>
)
})
return (
<div className="App">
<h1>{this.state.user.username||'我'}的待办
{this.state.user.id ? <button onClick={this.onSignOut.bind(this)}>登出</button> : null}</h1>
<div>
<TodoInput content={this.state.newTodo}
onSubmit={this.addTodo.bind(this)}
onChange={this.changeTitle.bind(this)} />
</div>
<ol className="todoList">
{todos}
</ol>
{this.state.user.id ? null : <UserDialog onSignUp={this.onSignUp.bind(this)}
onSignIn={this.onSignIn.bind(this)} />}
</div>
);
}
componentWillMount(){
let user = this.state.user
let hasProp = false
for(let key in user){
hasProp = true
}
if(hasProp){
downloadTodoList.call(this,user)
}else {
return
}
}
componentDidUpdate(){
}
onSignIn(user){
downloadTodoList.call(this,user)
}
onSignUp(user){
let stateCopy = JSON.parse(JSON.stringify(this.state))
stateCopy.user = user
createTodoList.call(null,saveDataIdToUser.bind(this))
// this.setState(stateCopy) 等todoListId存在user之后,再setState
}
onSignOut(e){
let stateCopy = JSON.parse(JSON.stringify(this.state))
stateCopy.user = ''
stateCopy.todoList = []
signOut.call(null)
this.setState(stateCopy)
}
addTodo(e){
let _this = this
let stateCopy = JSON.parse(JSON.stringify(this.state))
stateCopy.newTodo='';
stateCopy.todoList.push({
id: idMaker(),
title: e.target.value,
status: null,
deleted: false
})
this.saveToCloud.call(this,stateCopy)
}
saveToCloud(data){
let _this = this
let todoListId = this.state.user.todoList
var todo = new AV.Object.createWithoutData('TodoList',todoListId)
todo.set('todoList',data.todoList)
todo.save().then(function(todo){
_this.setState(data)
})
}
changeTitle(e){
this.setState({
newTodo: e.target.value,
todoList: this.state.todoList
})
}
toggle(e,todo,item){
let index = this.state.todoList.indexOf(todo)
let stateCopy = JSON.parse(JSON.stringify(this.state))
let todoCopy = JSON.parse(JSON.stringify(todo))
todoCopy.status = todo.status === 'completed' ? '' : 'completed'
stateCopy.todoList[index] = todoCopy
this.saveToCloud.call(this,stateCopy)
}
delete(e,todo){
let index = this.state.todoList.indexOf(todo)
let stateCopy = JSON.parse(JSON.stringify(this.state))
let todoCopy = JSON.parse(JSON.stringify(todo))
todoCopy.deleted = true
stateCopy.todoList[index] = todoCopy
this.saveToCloud.call(this,stateCopy)
}
}
export default App;
let id = 0
function idMaker(){
id += 1
return id
}
|
var ApiError = require('libs/ApiError');
var Promise = require('bluebird');
exports.monkeyPatch = function( app ){
app.response.sendSuccess = function( data, message ){
var out = {
success: true,
},
res = this;
if( data.constructor.name == 'String' ){
out.message = data;
out.data = {};
} else {
out.message = message || 'Success';
out.data = data;
}
if( data.$redirect ){
return this.format({
html: function(){
return res.redirect( data.$redirect );
},
json: function(){
return res.json( out );
}
});
}
return this.json( out );
};
app.response.sendError = function( err, status ){
err = ApiError.create( err )
this.status( err.status || status || 400 );
this.json({
success: false,
message: err.message,
data:{},
errors: err.errors,
});
};
}
exports.reject = function( message, status ){
return Promise.reject( new ApiError( message, status ));
}
exports.transormMiddlewares = function( arr ){
arr = arr.slice();
var fn = arr.pop();
return function(data, req, res ){
return Promise.mapSeries( arr, function( mware ){
return Promise.fromCallback(function(done){
mware(req, res, done );
});
})
.then(function(){
return fn(data, req, res);
})
}
}
|
const path = require('path')
const Webpack = require('webpack')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')//将CSS提取为独立的文件的插件,对每个包含css的js文件都会创建一个CSS文件,支持按需加载css和sourceMap
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin')//webpack4使用optimize-css-assets-webpack-plugin压缩css
const HtmlWebpackPlugin = require('html-webpack-plugin')//html压缩
const {CleanWebpackPlugin} = require('clean-webpack-plugin')//清理构建目录
const glob = require('glob')
const HtmlWebpackExternalsPlugin = require('html-webpack-externals-plugin')
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin')
const SpeedMeasureWebpackPlugin = require('speed-measure-webpack-plugin')
const smp = new SpeedMeasureWebpackPlugin()
const {BundleAnalyzerPlugin} = require("webpack-bundle-analyzer")
const HappyPack = require('happypack')
const ThreadLoader = require('thread-loader')
const TerserPlugin = require('terser-webpack-plugin');
const PurgeCSSPlugin = require('purgecss-webpack-plugin');
const PATHS = {
src:path.join(__dirname,'src')
}
// 动态设置html和entry
const setMPA = () => {
const entry = {}
const htmlWebpackPlugins = []
const entryFiles = glob.sync(path.join(__dirname, './src/*/index.js'))
Object.keys(entryFiles).map((index) => {
const entryFile = entryFiles[index]
//match() 方法可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。
var reg = /src(.*)\/index\.js/
const match = entryFile.match(/src\/(.*)\/index\.js/)//[ 'src/search/index.js','/search',index: 36,input: '/Users/wumao/学习/webpack/my-project1/src/search/index.js',groups: undefined ]
const pageName = match && match[1];
entry[pageName] = entryFile;
htmlWebpackPlugins.push(
new HtmlWebpackPlugin({//html压缩
template: path.join(__dirname, `src/${pageName}/index.html`),
filename: `${pageName}.html`,//要将HTML写入的文件。默认为index.html索引. 您也可以在这里指定子目录(例如:assets/管理.html)
chunks: ['vendors', pageName],//文件要引入的js
inject: true,//true | |“head”| |“body”| | false将所有资产注入给定的模板或模板内容。当传递true或body时,所有javascript资源都将放在body元素的底部head'将脚本放在head元素中-请参见注入:错误示例
minify: {//控制是否以及以何种方式缩小输出
html5: true,
preserveLineBreaks: false,//保留换行符
collapseWhitespace: true,//折叠空白
removeComments: false,//删除注释:true,
minifyCSS: true,
// minifyJS: true,
// removeRedundantAttributes: true,//删除冗余属性:true,
// removeScriptTypeAttributes: true,//删除脚本类型属性:true,
// removeStyleLinkTypeAttributes: true,//删除样式链接类型属性:true,
// useShortDoctype: true//使用短文档类型:true
}
})
)
})
return {
entry,
htmlWebpackPlugins
}
}
const {entry, htmlWebpackPlugins} = setMPA()
module.exports = smp.wrap({
entry: entry,
// entry:{index:"./src/index/index.js",search:"./src/search/index.js"},//key值index.js文件名称
// entry:glob.sync,//多页面打包通用方案
output: {
path: path.join(__dirname, "dist"),
filename: "[name]_[chunkhash:8].js"//js使用chunkhash设置
},
module: {
rules: [
{
test: /\.html$/,
use: 'raw-loader'
},
{
test: /.js$/,
use: [{
loader: 'thread-loader',
options: {
workers: 3
}
}, 'babel-loader'],
include: path.resolve('src')
// exclude:[/*...*/],
// use: ['babel-loader','eslint-loader']
},
{
test: /.css$/,
use: [
'style-loader',
MiniCssExtractPlugin.loader,
'css-loader',
"postcss-loader",
]
},
{
test: /.less$/,
use: [
{
loader: 'style-loader',
options: {
insert: 'top',
injectType: 'singletonStyleTag',
}
},
MiniCssExtractPlugin.loader,
'css-loader',
// {
// loader:"postcss-loader",
// options: {
// plugins:()=>[
// require('autoprefixer')({//指定兼容浏览器最新的两个版本,版本使用人数》1%
// browsers:['last 2 version','>1%','ios 7']
// })
// ]
// }
// },
{
loader: 'px2rem-loader',
options: {
remUnit: 75,//1rem=75px
remPrecesion: 8//px转换成rem的小数点位数
}
},
'less-loader',
"postcss-loader",
]
},
{
test: /\.(png|gif|jpg|jpeg)$/,
use: [{
loader: 'file-loader',
options: {
name: 'img/[name]_[hash:8].[ext]'//图片的文件指纹,设置file-loader的name使用[hash],打包到img目录下
}
},
{
loader: 'image-webpack-loader',
options: {
mozjpeg: {
progressive: true,
},
// optipng.enabled: false will disable optipng
optipng: {
enabled: false,
},
pngquant: {
quality: [0.65, 0.90],
speed: 4
},
gifsicle: {
interlaced: false,
},
// the webp option will enable WEBP
webp: {
quality: 75
}
}
}
]
},
{
test: /.(woff|woff2|eot|ttf|otf)/,
use: "file-loader"
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name]_[contenthash:8].css'//css使用contenthash设置
}),
new OptimizeCssAssetsWebpackPlugin({//css压缩
assetNameRegExp: /\.css$/g,
cssProcessor: require('cssnano')
}),
new PurgeCSSPlugin({
paths: glob.sync(`${PATHS.src}/**/*`, { nodir: true }),
}),
new CleanWebpackPlugin(),//会清理旧的构建内容,不会使文件增多
new FriendlyErrorsWebpackPlugin(),
function () {
//this指向compile
this.hooks.done.tap('done', (stats) => {
if (stats.compilation.errors && stats.compilation.errors.length && process.argv.indexOf('--watch') == -1) {
console.log('build error')
process.exit(14)
}
})
},
// new BundleAnalyzerPlugin(),
new HappyPack({
id: 'js',
use: [{ // 将js的具体规则放置在此处
loader: 'babel-loader?cacheDirectory=true',
options: {
presets: [
'@babel/preset-env',
'@babel/preset-react'
]
}
}]
}),
// new webpack.DllReferencePlugin({
//
// })
].concat(htmlWebpackPlugins),//.concat(htmlWebpackPlugins)
optimization: {//通过splitChunks提取react|react-dom公共包,提取后名字叫vendors
splitChunks: {
minSize: 0,
cacheGroups: {
commons: {
test: /(react|react-dom)/,
name: 'vendors',
chunks: 'all'
}
}
},
minimizer: [
new TerserPlugin({
parallel: true,
cache: true
})
]
},
// mode:'production',
mode: 'none',//webpack4 当mode设置为production的时候,默认开启了uglifyjs插件压缩js
// devtool:"source-map",
// mode:'development'//热更新只在开发环境使用所以暂时改成development
resolve: {
alias: {
'react': path.resolve(__dirname, './node_modules/react/umd/react.production.min.js'),
'react-dom': path.resolve(__dirname, './node_modules/react-dom/umd/react-dom.production.min.js'),
},
extensions: ['.js'],
mainFields: ['main']
},
// stats: "errors-only"
})
|
// @flow
import React from 'react';
import MUIListItem from '@material-ui/core/ListItem';
import type { ListItemProps } from '../types';
const ListItem = ({ theme, onClick, onKeyPress, children }: ListItemProps) => (
<MUIListItem
button
onClick={onClick}
onKeyPress={onKeyPress}
style={theme.listItemStyle}
className={theme.listItemClassName}
>
{children}
</MUIListItem>
);
export default ListItem;
|
// @flow
import React from 'react';
import {View} from 'react-native';
import {Icon} from 'react-native-elements';
type Props = {
name: string,
focused: boolean,
tintColor: string,
};
export default function NavbarIcon(props: Props) {
// eslint-disable-next-line no-unused-vars
let {focused, tintColor, ...otherProps} = props;
return (
<View>
<Icon {...otherProps} color={tintColor} />
</View>
);
}
|
const fs = require('fs');
//import * as fs from 'fs';
module.exports = {
devServer(configFunction) {
return function (proxy, allowedHost) {
const config = configFunction(proxy, allowedHost);
config.disableHostCheck = true
config.https = {
key: fs.readFileSync('codi.jrds.key'),
cert: fs.readFileSync('codi.jrds.crt'),
ca: fs.readFileSync('codiCA.pem'),
}
//config.headers = config.headers || {}
//config.headers['Access-Control-Allow-Origin'] = '*'
return config
}
}
}
|
var dgram = require('dgram');
var events = require('events');
var util = require('util');
var net = require('net');
var PocketMineProxy = function (options) {
"use strict";
var settings = { UDP_TYPE: 'udp4',
IP_FAMILY: 'IPv4' };
var proxy = this;
this.servers = [];
this.index = 0;
for (var i=0; i < options.servers.length; i++) {
this.servers.push(options.servers[i]);
}
var proxyPort = options.proxyPort || 19132;
var proxyHost = options.proxyHost || '0.0.0.0';
this.timeOutTime = options.timeOutTime || 10000;
this.family = settings.IP_FAMILY;
this.udpType = settings.UDP_TYPE;
this.connections = {};
this._proxy = dgram.createSocket(this.udpType);
this._proxy.on('listening', function () {
// setImmediate(function() {
// proxy.emit('listening', details);
// });
console.log("listening on port " + proxyPort);
}).on('message', function (msg, rinfo) {
//console.log("msg from "+ JSON.stringify(rinfo));
var conn = proxy.createConnection(msg, rinfo);
if (!conn._bound) conn.bind();
//console.log("sending to "+ conn.server.serverHost + ':' + conn.server.serverPort);
conn.send(msg, 0, msg.length, conn.server.serverPort, conn.server.serverHost , function (err, bytes) {
if (err) console.log('proxyError: '+ err);
});
}).on('error', function (err) {
console.log("error; closing connection");
this.close();
// proxy.emit('error', err);
}).on('close', function () {
// proxy.emit('close');
});
this._proxy.bind(proxyPort, proxyHost);
}
util.inherits(PocketMineProxy, events.EventEmitter);
PocketMineProxy.prototype.addServer = function addServer(server) {
this.servers.push(server);
};
PocketMineProxy.prototype.send = function send(msg, port, address, callback) {
this._proxy.send(msg, 0, msg.length, port, address, callback);
};
PocketMineProxy.prototype.strip = function strip(address) {
return (address.address + address.port).replace(/\./g, '');
};
PocketMineProxy.prototype.createConnection = function getConnection(msg, rinfo) {
var clientId = this.strip(rinfo);
var self = this;
if (this.connections.hasOwnProperty(clientId)) {
//console.log("Found connection for " + clientId);
var conn = this.connections[clientId];
//clearTimeout(conn.t);
//conn.t = null;
return conn;
}
console.log("Creating new connection for "+ rinfo.address + ":" + rinfo.port);
this.index++;
if (this.index > self.servers.length -1) this.index = 0;
conn = dgram.createSocket(this.udpType);
conn.server = this.servers[this.index];
console.log("Server set to "+conn.server.serverHost+":"+conn.server.serverPort);
conn.once('listening', function () {
//var details = proxy.getDetails({route: this.address(), peer: sender});
//console.log("sending to " + JSON.stringify(proxy.servers[0]));
conn.send(msg, 0, msg.length, conn.server.serverPort, conn.server.serverHost, function (err, bytes) {
if (err) {
self.emit('proxyError', err);
console.log("error initial send " + err);
}
});
conn._bound = true;
self.emit('bound', rinfo);
}).on('message', function (msg, rinfoo) {
self.send(msg, rinfo.port, rinfo.address, function (err, bytes) {
if (err) {
self.emit('proxyError', err);
console.log("error send " + err);
}
});
clearTimeout(conn.t);
conn.t = setTimeout(function() {
conn.close();
console.log("timed out. closing connection");
}, self.timeOutTime);
}).on('close', function () {
//proxy.emit('proxyClose', this.peer);
conn.removeAllListeners();
delete self.connections[clientId];
console.log("connection closed for " + rinfo.address +":"+rinfo.port);
}).on('error', function (err) {
conn.close();
self.emit('proxyError', err);
});
this.connections[clientId] = conn;
return conn;
};
exports.start = function (options) {
return new PocketMineProxy(options);
};
|
// filter.js
"use strict";
let numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log("numberArray: ", numberArray);
function filterFive(value) {
return value > 5;
}
let filteredNumberArray = numberArray.filter(filterFive);
console.log("filteredNumberArray: ", filteredNumberArray);
let shoppingList = [
"Milk",
"Milk",
"Donuts",
"Cookies",
"Chocolate",
"Peanut Butter",
"Pepto Bismol",
"Pepto Bismol (1)",
"Pepto Bismol (2)"
];
const searchedValue = "Bismol";
function searchedValueList(value) {
return value.indexOf(searchedValue) !== -1;
}
console.log("shoppingList: ", shoppingList);
let filteredShoppingList = shoppingList.filter(searchedValueList);
console.log("filteredShoppingList: ", filteredShoppingList);
|
var variables________________________________e________________8js________8js____8js__8js_8js =
[
[ "variables________________e________8js____8js__8js_8js", "variables________________________________e________________8js________8js____8js__8js_8js.html#aac1a5dadd5c3289a24326608a26dfb87", null ]
];
|
//跨域代理前缀
const API_PROXY_PREFIX = '/api'
const BASE_URL = process.env.NODE_ENV === 'production' ?
process.env.VUE_APP_API_BASE_URL :
API_PROXY_PREFIX
// 不用代理,要注释掉vue.config.js 中的proxy{}
// const BASE_URL = process.env.NODE_ENV === 'production' ?
// '/spring-boot-api-seeding' :
// process.env.VUE_APP_API_BASE_URL
module.exports = {
BASE_URL,
// LOGIN: `${BASE_URL}/login`,
LOGIN: `${BASE_URL}/account/token`,
// ROUTES: `${BASE_URL}/routes`,
GOODS: `${BASE_URL}/goods`,
GOODS_COLUMNS: `${BASE_URL}/columns`,
DEPARTMENT: `${BASE_URL}/department`, // method CRUD
ROLE: `${BASE_URL}/role`, // method CRUD
PERMISSION: `${BASE_URL}/permission`, // method CRUD
EMPLOYEE: `${BASE_URL}/employee`, // method CRUD
DICTIONARY_CONTENTS: `${BASE_URL}/dictionary/contents`, // method CRUD
DICTIONARY_DETAILS: `${BASE_URL}/dictionary/details`, // method CRUD
CUSTOMER_MANAGER: `${BASE_URL}/customer/manager`, // method CRUD
CUSTOMER_HANDOVER: `${BASE_URL}/customer/handover`, // method CRUD
CUSTOMER_FOLLOW_UP_HISTORY: `${BASE_URL}/customer/follow/up/history`, // method CRUD
ANALYSIS: `${BASE_URL}/analysis`, // method CRUD
UPLOADFILE: `${BASE_URL}/attachment/upload/file`, //文件上传
GETFILEINFO: `${BASE_URL}/attachment/findFiles`, //获取附件信息
DOWNLOADFILE: `${BASE_URL}/attachment/downLoad`, //下载附件
DELETEFILE: `${BASE_URL}/attachment/delete`, //删除附件
}
|
const KoaRouter = require('koa-router');
const jwt = require('koa-jwt');
const { Op } = require('sequelize');
const router = new KoaRouter();
const PERMITTED_FIELDS = [
'name',
'ubicacion',
'horarioA',
'horarioC',
'precio',
'capacidad',
];
async function allLocals(ctx, next) {
ctx.state.localsApp = await ctx.orm.locals.findAll();
return next();
}
async function loadLocal(ctx, next) {
console.log('here');
ctx.state.local = await ctx.orm.locals.findByPk(ctx.params.localId, {
include: {
association: ctx.orm.locals.ownerLocals,
as: 'owners',
},
});
console.log('local', ctx.state.local);
return next();
}
async function checkOwnerUpdate(ctx, next) {
const { local } = ctx.state;
const { user: { sub } } = ctx.state;
if (local) {
let isAdmin = false;
local.users.forEach((user) => {
if (user.id === sub) { isAdmin = true; }
});
if (isAdmin) {
const fields = ctx.request.body;
console.log('Fields', fields);
try {
await local.update(fields);
ctx.body = { local };
} catch (error) {
ctx.body = { error };
}
} else { ctx.body = { error: 'Insufficient permission' }; }
} else {
ctx.body = { error: 'Unexistant local' };
}
return next();
}
async function loadOwnedLocals(ctx, next) {
const { user: { sub } } = ctx.state;
ctx.state.user = await ctx.orm.users.findByPk(sub, {
include: {
association: ctx.orm.users.ownerLocals,
as: 'locals',
},
});
return next();
}
async function checkData(ctx, next) {
PERMITTED_FIELDS.forEach((field) => {
if (!(field in ctx.request.body)) {
ctx.body = null;
ctx.state.message = `${field} faltante`;
}
});
return next();
}
async function createLocal(ctx, next) {
try {
const { user: { sub } } = ctx.state;
const local = await ctx.orm.locals.build(ctx.request.body);
await local.save({ fields: PERMITTED_FIELDS });
const ownerLocal = await ctx.orm.ownerlocal.build({
ownerid: sub,
localid: local.id,
});
await ownerLocal.save({ fields: ['ownerid', 'localid'] });
ctx.body = { local };
} catch (error) {
ctx.body = null;
ctx.state.message = error;
}
return next();
}
async function checkLocalDeleteId(ctx, next) {
const { localId } = ctx.params;
const { user: { sub } } = ctx.state;
ctx.state.statusRequest = true;
if (!localId) {
ctx.state.statusRequest = false;
ctx.body = 'No localId';
} else {
try {
ctx.state.local = await ctx.orm.locals.findOne({ where: { id: localId } });
ctx.state.ownerLocal = await ctx.orm.ownerlocal.findOne({
where: {
localid: localId,
},
});
if (ctx.state.local && ctx.state.ownerLocal && (ctx.state.ownerLocal.ownerid === sub)) {
ctx.state.localId = localId;
} else {
ctx.state.statusRequest = false;
ctx.body = 'Unexistant local or insufficient permissions';
}
} catch (error) {
ctx.state.statusRequest = false;
ctx.body = 'Unexistant localId';
}
}
return next();
}
async function deleteActUser(ctx, next) {
if (ctx.state.statusRequest) {
const activitiesIds = [];
const activitiesLocal = await ctx.orm.activities.findAll({
where: { localId: ctx.state.localId },
});
activitiesLocal.forEach((activity) => {
activitiesIds.push(activity.id);
});
await ctx.orm.userAct.destroy({
where: {
actid: {
[Op.or]: activitiesIds,
},
},
});
await ctx.orm.activities.destroy({
where: {
localId: ctx.state.localId,
},
});
}
return next();
}
async function deletelocalRequest(ctx, next) {
if (ctx.state.statusRequest) {
await ctx.orm.requests.destroy({ where: { localId: ctx.state.localId } });
}
return next();
}
async function deleteLocalUser(ctx, next) {
if (ctx.state.statusRequest) {
await ctx.orm.userlocal.destroy({ where: { localid: ctx.state.localId } });
await ctx.state.ownerLocal.destroy();
await ctx.state.local.destroy();
}
return next();
}
async function activities(ctx, next) {
ctx.state.activitiesList = await ctx.orm.activities.findAll({ where: { localId: ctx.params.localId } });
return next();
}
router.get('locals', '/all', allLocals, async (ctx) => {
const { localsApp } = ctx.state;
ctx.body = { localsApp };
ctx.status = 200;
});
router.use(jwt({ secret: process.env.JWT_SECRET, key: 'user' }));
router.get('getOwnedLocal', '/owner', loadOwnedLocals, async (ctx) => {
const { user: { locals } } = ctx.state;
ctx.body = { locals };
ctx.status = 200;
});
router.get('getLocalActivities', '/:localId/activities', activities, async (ctx) => {
const { activitiesList } = ctx.state;
if (activitiesList) {
ctx.body = { activitiesList };
ctx.status = 200;
} else {
ctx.body = { activitiesList: [] };
ctx.status = 200;
}
});
router.post('createLocal', '/create', checkData, createLocal, async (ctx) => {
if (ctx.body) {
ctx.status = 200;
} else {
ctx.status = 400;
ctx.body = ctx.state.message;
}
});
router.del('deleteLocal', '/delete/:localId', checkLocalDeleteId, deleteActUser, deletelocalRequest, deleteLocalUser, async (ctx) => {
if (!ctx.state.statusRequest) {
ctx.status = 400;
} else {
ctx.status = 200;
ctx.body = `Local id: ${ctx.state.localId} succesfully deleted`;
}
});
router.patch('editLocal', '/edit/:localId', loadLocal, checkOwnerUpdate, async (ctx) => {
const { error } = ctx.body;
if (error) {
ctx.status = 400;
} else {
ctx.status = 200;
}
});
module.exports = router;
|
const gulp = require('gulp')
gulp.task('reload', () => {
nodemon({
script: 'mac.js'
})
})
|
import React from "react";
import "./style.css";
import Navbar from "../../components/Navbar";
import Header from "../../components/Header";
import AboutContainer from "../../components/AboutContainer";
import BackgroundImage from "../../components/BackgroundImage";
import imageURL from "../../images/background.jpg";
import Footer from "../../components/Footer"
function About() {
return (
<BackgroundImage image={imageURL}>
<Navbar />
{/* <Header /> */}
<AboutContainer />
<Footer />
</BackgroundImage>
)
};
export default About;
|
// Валидация формы связи с компанией
// Форма
var submitForm = document.getElementById('contactForm');
// Поле Имя
var user_name = document.getElementById('contact-name');
// Поле e-mail
var user_email = document.getElementById('contact-email');
// Поле тема
var subject = document.getElementById('contact-subject');
// Поле Сообщение
var message = document.getElementById('contact-message');
// Кнопка Отправить
// var submit_btn = document.getElementById('contact-submit');
// Валидация
// Валидация обязательного поля
function validateField(u_data, params) {
var validity = false;
if (u_data && u_data.length >= params.min_length && u_data.length <= params.max_length) {
validity = true;
}
return validity;
};
// Обработка нажатия на кнопку "Отправить"
function validateForm(evt) {
evt.preventDefault();
var elems = Array.from(submitForm.elements);
var name_rule = {
min_length: 2,
max_length: 140
};
var email_rule = {
min_length: 6,
max_length: 140
};
// Объект с данными полей
var user_data = {
name: user_name.value.trim(),
email: user_email.value.trim(),
subject: subject.value.trim(),
message: message.value.trim()
};
// Чекбокс отмечен?
var aggree = elems[4].checked;
// Проверяем поля на правильность
var name_validity = validateField(user_data.name, name_rule);
var email_validity = validateField(user_data.email, email_rule);
if (name_validity && email_validity) {
if (aggree) {
alert('Отправлено');
submitForm.submit();
} else {
alert('Подтвердите, пожалуйста, согласие на обработку персональных данных');
}
}
// if (aggree) {
// console.log(user_data);
// console.log(name_validity, email_validity);
// if (name_validity && email_validity) {
// // Отправляем форму:
// alert('Отправлено');
// submitForm.submit();
// }
// alert('Отправлено');
// submitForm.submit();
// } else {
// alert('Подтвердите, пожалуйста, согласие на обработку персональных данных');
// }
};
// Обработчик нажатия на кнопку отправить
// document.getElementById('contact-submit').addEventListener('click', validateForm);
// Слушаем событие submit на форме
// submitForm.addEventListener('submit', function(submitEvt) {
// submitEvt.preventDefault();
// var formData = new FormData(submitForm);
// console.log(submitEvt.type, formData);
// });
|
let express = require('express');
let router = express.Router();
let PayType = require('../models/PayType');
let Ids = require('../models/IdsNext');// 引入模型
// --------------------------新增支付类型--------------------------
router.post('/add', (req,res)=>{
console.log('-------------添加支付类型-----------------------')
let cn = req.body;
let id = Ids.findByIdAndUpdate(
{_id: 'payTypeId'},
{$inc: {sequence_value: 1}});
id.then(data => {
let payType = new PayType({
_id: data.sequence_value,
payType: cn.payType,
})
payType.save((err) => {
if (err) {
res.send({msg: '添加失败!', state: '99'})
} else {
res.send({msg: '添加成功!', state: '200'})
}
})
})
});
// --------------------------显示支付列表-------------------------
router.get('/list', (req, res) => {
console.log('----------显示支付类型列表---------')
let cn = req.query;
if(!cn){
let page = cn.curPage;
let rows = cn.rows;
let query = PayType.find({});
query.skip((page-1)*rows);
query.limit(parseInt(rows));
let result = query.exec();
result.then((data)=>{
// 获取总条数
PayType.find({},(err,rs)=>{
res.send({msg: 'sucess', state: '200', data: data,total:rs.length})
})
})
}else{
PayType.find({},(err,doc)=>{
res.send({msg: 'sucess', state: '200', data: doc})
})
}
});
// --------------------------查询支付类型-----------------------
router.get('/findById', (req,res)=>{
console.log('-----------------根据Id查询收入类型------------------')
let query = {
_id: req.query._id
}
PayType.findById(query, (err,doc)=>{
res.send({msg: 'sucess', state: '200', data: doc})
})
});
// --------------------------更新支付类型-------------------------
router.post('/update',(req,res) =>{
console.log('-----------------更新支付类型------------------');
let cn = req.body;
let query = {
_id: req.body._id
}
let param = {
payType: cn.payType,
}
PayType.findOneAndUpdate(query,{ $set: param},(err,doc)=>{
res.send({msg: 'sucess', state: '200'})
})
});
//---------------------------删除支付类型--------------------------
router.post('/delete', (req,res) =>{
console.log('-------------删除支付类型--------------');
let ids = req.body._ids.split(',');
let query = {
_id: ids
};
PayType.deleteMany(query, (err, doc) => {
if (err) {
res.send({msg: '删除失败', state: '99'})
} else {
res.send({msg: '删除成功', state: '200', data: doc})
}
})
});
module.exports = router;
|
$(document).ready(function(){
if($("#tipoPerfil").val()==2){
$("#wrapEmpresas").css("display","block");
}
wrapEmpresas
$("#tipoPerfil").change(function(){
tipoPerfil = $(this).val();
if(tipoPerfil==2){
$("#wrapEmpresas").fadeIn(500);
}else{
$("#wrapEmpresas").fadeOut(100);
}
});
});
|
import React from 'react'
import PropTypes from 'prop-types'
const ItemPage = ({ styles, match }) => (
<div className={styles.wrapper}>
This is a page: {match.path}
</div>
)
ItemPage.propTypes = {
styles: PropTypes.object,
match: PropTypes.shape({
path: PropTypes.string.isRequired,
}).isRequired,
}
export default ItemPage
|
var searchData=
[
['port',['port',['../main_8c.html#a938bdc6ae46c346147b6d4f67ad1e704',1,'main.c']]]
];
|
import React from "react";
import pageInfo from "./pageInfo.module.css";
let PageInfo = () => {
return (
<div>
<section className={`${pageInfo.latestBlogArea}`}>
<div className="row justify-content-center">
<div className={`${pageInfo.areaHeading}`}>
<h3>A global robotics community preparing young people for the future.</h3>
<br/>
<p>We engage young people in exciting mentor-based programs that build science, engineering and technology skills,
that inspire innovation, and that foster well-rounded life capabilities including self-confidence,
communication, and leadership.</p>
<br/>
<br/>
<br/>
<hr/>
</div>
</div>
</section>
</div>
);
};
export default PageInfo;
|
'use strict'; //"operatingcashflow","espdiluted",
var fundamentalOptions = ['assets', 'bookvalue' ,"capitalexpenditures" ,"cash","costofgoodssold","dps",'epsbase', "floatshares","goodwill","incomeaftertax",'incomebeforetax', "institutionalown", "inventory","liability","longtermdebt",'netincome' , "numofemployees" ,"operatingincome","revenue","shorttermdebt","totaloperatingexpense"]
var array = ["Assets","Book Value","Capital Expenditures","Cash","Cost of Good Sold","DPS","EPS Base","Float Shares","Good Will","Income After Tax","Income Before Tax","Institutional Own","Inventory","Liability","Long Term Debt","Net Income","Number of Employees","Operating Income","Revenue","Short Term Debt","Total Operating Expense"];
var validTicker = 0
var fundata = new Array()
StockRender.AppRender.register({
id: "49e90eee6ce1942a94136fc8db19319c",
name: "Tables",
version: "1.0.0",
defaults: {
terminal: {
x: 0,
y: 0,
w: 100,
h: 100
}
},
beforeRender: function () {
console.log('running beforeRender!');
},
ready: function(AppMemory, AppData) {
/*Defining Variables*/
var last_input;
/*Reading User-Data*/
AppMemory.read('last_input')
.success(function(data) {
if(!data) {
AppMemory.write('last_input','A');
last_input = 'A';
} else {
last_input = data;
}
})
.error(function(err, data) {
if(err) {
console.log('AppMemory not retrieved',data);
AppMemory.write('last_input','A');
last_input = 'A';
}
})
/*Running Program*/
$('#autocomplete').keypress(function(e) {
if( e.which === 13 ) {
fundata = new Array();
//Local variable "input"
var input = document.getElementById("autocomplete");
//Call function again -- function in EnterStock.js
validTicker = determineTicker(input.value.toUpperCase());
if (validTicker == 1) {
Runner.loadData(AppData, $('#autocomplete')[0].value.toUpperCase());
return;
};
}
})
///////////////////////////////////////////////*Settings*//////////////////////////////////////////////
var isChanged;
var changeSize;
$( "#inpText" ).change(function() {
var newTextSize = document.getElementById('inpText').value;
console.log(newTextSize);
changeSize = newTextSize + 'px';
isChanged = true; //Don't know what it does yet
})
//this is the function for opening and closing the settings
var settingsShown = false;
var fundChanged;
$( "#opener" ).click(function() {
if (settingsShown == false) {
settingsShown = true;
$("#settings").show();
//$("#table1").hide();
} else {
settingsShown = false;
$("#settings").hide();
//$("#table1").show();
//Change of text size
if(isChanged == true) {
console.log(changeSize);
var pLength = document.getElementsByTagName('tr').length;
for(var x = 0; x < pLength; x++) {
document.getElementsByTagName('tr')[x].style.fontSize = changeSize;
}
var emLength = document.getElementsByTagName('tr').length;
for(var x = 0; x < emLength; x++) {
document.getElementsByTagName('tr')[x].style.fontSize = changeSize;
}
isChanged = false;
}
if(fundChanged == true) {
var rowNum = document.getElementById("table1").rows.length;
while(rowNum > 4) {
document.getElementById("table1").deleteRow(rowNum - 2);
rowNum = document.getElementById("table1").rows.length;
stockLength = 0;
numAddedStocks = 0;
}
fundChanged = false;
}
//Upon confirming settings changes
Settings_all();
}
console.log('settingsShown', settingsShown);
})
}
})
function Runner () {}
Runner.loadData = function loadData(AppData, stockId) {
var checks = 0;
//-----------------------------------------
// /v1/fundamentals
//-----------------------------------------
for( var i=0; i< fundamentalOptions.length; i++) {
// use closure from
// http://stackoverflow.com/questions/19564172/for-loop-wont-pass-i-variable-to-jquery-function-inside-the-loop
(function(i) {
var tempfund = fundamentalOptions[i];
var tempName = array[i]
AppData.v1.fundamental.GET(stockId,tempfund)
.then(function(data) {
var ek = data.response.data[0][1]
if ( ek / 1000000000 > 1 || ek / 1000000000 < -1) {
ek = (ek / 1000000000).toFixed(2) + " bn"
}
else if( ek / 1000000 >1 || ek / 1000000 < -1) {
ek = (ek / 1000000).toFixed(2) + " M"
}
var curr = {
'label': tempName,
'val': ek //data.response.data[0][1]
}
fundata.push(curr);
}, function(jqXHR) {
throw new Error('Failed to load data!',jqXHR);
}).then(function() {
checks ++;
if(checks === 2) {
//Runner.toggleOverhead();
}
})
})(i);
}
console.log(fundata)
}
|
const loggedIn = false;
const currentUser = null;
const email = '';
const password = '';
export { loggedIn, currentUser, email, password }
|
function GetCategoryList()
{
$.post("Category.aspx", { Action: "getcategorylist", NodeCode: request("NodeCode") }, function (data, textstatus) {
switch(parseInt(data.Code)){
case 200:$("ul.ulbody").remove();$(".ulheader").after(data.Message);BindUL();break;
default: alert({msg:'['+data.Code+'] '+data.Message});break;
}
},"json");
}
function BindUL()
{
$("ul.ulbody").each(function(){
$(this).mouseover(function(){ $(this).css("background","#E8F3F6");});
$(this).mouseout(function(){ $(this).css("background","#fff");});
});
$(".orders").bind({
click: function() {
$(this).css({background:'#fff',padding:'0px'}).html('<input type=\"text\" style=\"width:60px;height:14px;border:#e4e4e4 1px solid;text-align:center;padding-bottom:2px;\" value=\"'+$(this).html()+'\" onblur=\"UpdateOrders('+$(this).attr("ref")+',this)\" />');
$(this).unbind("click").find("input").focus();
}
});
}
function Del(id,obj)
{
selfconfirm({msg:'您确定要删除该数据吗?',fn:function(data){if(data=="true"){DelItem(id,obj)};$(this).hide() }});
}
function DelItem(id,obj)
{
$.post("Category.aspx",{Action:"removeitem",id:id},function(data,textstatus){
switch(parseInt(data.Code)){
case 200:$(obj).parents("ul").remove();break;
default: alert({msg:'['+data.Code+'] '+data.Message});break;
}
},"json");
}
function ShowValid(id,obj)
{
$.post("Category.aspx",{Action:"showvalid",id:id},function(data,textstatus){
switch(parseInt(data.Code)){
case 200:
if(data.Data=="1")
$(obj).attr("src",'/sysadmin/images/yes.gif');
else
$(obj).attr("src",'/sysadmin/images/no.gif');
break;
default: alert({msg:'['+data.Code+'] '+data.Message});break;
}
},"json");
}
function ShowIndex(id,obj)
{
$.post("Category.aspx",{Action:"showindex",id:id},function(data,textstatus){
switch(parseInt(data.Code)){
case 200:
if(data.Data=="1")
$(obj).attr("src",'/sysadmin/images/yes.gif');
else
$(obj).attr("src",'/sysadmin/images/no.gif');
break;
default: alert({msg:'['+data.Code+'] '+data.Message});break;
}
},"json");
}
function UpdateOrders(id,obj)
{
var orders = parseInt($(obj).val(),0);
var span=$(obj).parent("span");
$(span).html(orders);
$.post("Category.aspx",{Action:"updateorders",id:id,orders:orders},function(data,textstatus){
switch(parseInt(data.Code)){
case 200:GetCategoryList();break;
default: GetCategoryList();break;
}
},"json");
}
function chkdelete() {
var chks = document.getElementsByName("chkId");
var tempval = 0;
for (var i = 0; i < chks.length; i++) {
if (chks[i].checked == true) {
tempval += 1;
}
}
if (tempval == 0) { return false; }
else { return confirm("确定要删除吗?"); }
}
/**
* 折叠分类列表
*/
function rowClicked(obj)
{
var imgPlus = "/sysadmin/images/DTree/plus.gif";
if($(obj).attr("src")==imgPlus)
$(obj).attr("src", "/sysadmin/images/DTree/minus.gif");
else
$(obj).attr("src",imgPlus);
obj = $(obj).parents(".ulbody");
var ull = $(".ulbody");
var lvl = parseInt($(obj).attr("ref"));
var fnd = false;
var display= $(obj).attr("ishow");
if(display=="0")
$(obj).attr("ishow","1");
else
$(obj).attr("ishow","0");
for (i = 0; i < ull.length; i++)
{
var row =ull.eq(i);
if ($(row).html()== $(obj).html())
fnd = true;
else
{
if (fnd == true)
{
var cur = parseInt($(row).attr("ref"));
if (cur > lvl)
{
if(display=="0")
$(row).show().attr("ishow", "1").find("img").eq(0).attr("src", "/sysadmin/images/DTree/minus.gif");
else
$(row).hide();
}
else
{
fnd = false;
break;
}
}
}
}
}
/*--获取网页传递的参数--*/
function request(paras) {
var url = location.href;
var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
var paraObj = {};
for (i = 0; j = paraString[i]; i++) {
paraObj[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=") + 1, j.length);
}
var returnValue = paraObj[paras.toLowerCase()];
if (typeof (returnValue) == "undefined") {
return "";
} else {
return returnValue;
}
}
function EditOrders() {
}
(function($){
GetCategoryList();
})(jQuery)
|
var goToViewPaper = function(paperUid) {
var url, method, params;
url = "/cocotask/eapp/paper/view";
method = "post";
params = {
paperUid: paperUid,
moduleName: "view", // TODO: moduleName을 다른 방법으로 변경 (너무 복잡함)
windowType: ""
};
post(url, params, method);
};
function post(path, params, method) {
method = method || "post";
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var key in params) {
if(params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
};
var goPageNumber = function(pageNumber) {
var url, method, params;
url = "/cocotask/eapp/paper/waitList";
method = "get";
params = {
pageNumber: pageNumber
};
post(url, params, method);
};
var createPagination = function() {
var selectedPageNumber, totalPages, startPages, showPages;
showPages = 5;
selectedPageNumber = $("#selectedPageNumber").val();
totalPages = $("#totalPages").val();
startPages = (selectedPageNumber - (selectedPageNumber % 5)) + 1;
if (showPages > totalPages) {
showPages = totalPages;
}
for (var i = 0; i < showPages; i++) {
var liNode = document.createElement("li");
liNode.className = "page-item";
var aNode = document.createElement("a");
var aTextNode = document.createTextNode(startPages);
aNode.className = "page-link";
aNode.href = "javascript:void(0);";
aNode.onclick = function(test) {
goPageNumber(this.innerText);
};
aNode.appendChild(aTextNode);
liNode.appendChild(aNode);
$(liNode).insertBefore($("#pageItemLast"));
startPages++;
}
};
|
'use strict'
const User = use('App/Models/User');
class UserController {
async login({request,auth}){
const { email,password} = request.all();
const token = await auth.attempt(email,password);
return token;
}
async store( {request} ){
const { email,password} = request.all();
console.log(email,password);
const user = await User.create({
email,
password,
username:email
});
// Retorna los datos del usuarios
//return user;
// sin no requiere validar el email sirve sino, Hay que tener en cuenta que hay que validar si el email existe.
return this.login(...arguments);
};
}
module.exports = UserController
|
import React from 'react';
import './App.scss';
import QuoteBox from './components/QuoteBox';
class App extends React.Component {
state = {
color: '#FFCBA4',
};
render() {
return (
<div className="App" style={{ backgroundColor: this.state.color }}>
<QuoteBox handleColor={(color) => this.setState({ color })} />
</div>
);
}
}
export default App;
|
#!/usr/bin/env node
//TODO to make this a module of its own, get the package name from package.json somehow
var exec = require('child_process').exec;
var cmd = `
mkdir -p bower_components/video-upload &&
mkdir -p bower_components/video-upload/dist &&
ln -s ../../video-upload.component.html bower_components/video-upload/video-upload.component.html &&
ln -s ../../../dist/video-upload.component.js bower_components/video-upload/dist/video-upload.component.js
`;
var newProcess = exec(cmd);
newProcess.stdout.on('data', function(data) {
console.log(data);
});
newProcess.stderr.on('data', function(data) {
console.log(data);
});
|
app.factory('DreamFactory', function($http) {
var extractData = function(response) {
return response.data;
}
var exports = {
getDreams: function() {
return $http.get('/api/dreams')
.then(extractData)
},
addDream: function(dream) {
return $http.post('/api/dreams', dream)
.then(extractData);
}
};
return exports;
})
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ShortList from 'AppComponents/ShortList';
import s from './StatisticsSection';
export default class StatisticsSection extends Component {
render() {
const listItems = this.props.data.map(item => (
<div key={item.id} className={s.statsList}>
<ShortList data={item.data} title={item.title} showMore={item.moreLink.name} showMoreLink={item.moreLink.link} />
</div>
));
return (
<div>
<h1 className="mainHeading">
{this.props.title}
</h1 >
<div className={`${s.sectionDetails} clearfix`}>
{listItems}
</div>
</div>
);
}
}
StatisticsSection.defaultProps = {
data: [],
title: null,
};
StatisticsSection.propTypes = {
data: PropTypes.array,
title: PropTypes.string,
};
|
var userName = prompt("What's is your name?",' ');
alert(userName);
|
var observable = Rx.Observable.create(function subscribe(observer) {
var id = setInterval(() => {
observer.next('hola');
}, 1000);
return function unsubscribe() {
clearInterval(id);
};
});
function subscribe(observer){
var id = setInterval(() => {
observer.next('hola');
}, 1000);
return function unsubscribe(){
clearInterval(id);
}
}
var unsubcribe = subscribe( { next : (x) => console.log(x)});
unsubcribe();
var i=0;
var observable = Rx.Observable.create(function subscribe(observer) {
var id= setInterval(() => {
try {
observer.next(i);
i++;
} catch (err) {
observer.error(err); // Entrega una notificación de “error” si sucede uno
}
}, 3000);
return function unsubscribe(){ // define un subscribe aqui adentro para poder hacer otras operaciones cuando cancela
console.log("osmel");
clearInterval(id);
}
});
//Cuando se llama a "observable.subscribe", el observer se une a la ejecución recién creada del observable,
//pero también esta llamada devuelve un "objeto de suscripción":
var observador1 = observable.subscribe(x => console.log("obs1: "+x));
var observador2 = observable.subscribe(x => console.log("obs2: "+x));
//La suscripción representa la ejecución en curso y tiene una API mínima que le permite cancelar esa ejecución.
// Con subscription.unsubscribe() puede cancelar la ejecución en curso:
observador1.unsubscribe(); //ejecuta el suscribe que esta dentro del observable
//observador2.unsubscribe();
|
(function() {
'use strict';
angular.module('myApp', ['ui.router'])
.controller('ListOneController', function(videos) {
this.items = videos;
})
.config(function($stateProvider, $urlRouterProvider) {
//
// For any unmatched url, redirect to /state1
$urlRouterProvider.otherwise('/state1');
//
// Now set up the states
$stateProvider.state('state1', {
url: '/state1',
templateUrl: 'templates/state1.html'
})
.state('state1.list', {
url: '/list/:query',
templateUrl: 'templates/state1.list.html',
resolve: {
videos: function($http, $stateParams) {
return $http.get('https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=20&type=video&q=' + $stateParams.query + '&key=AIzaSyD4YJITOWdfQdFbcxHc6TgeCKmVS9yRuQ8')
.then(function(res) {
return res.data.items.map(function(v) {
var snip = v.snippet;
return {
title: snip.title,
description: snip.description,
thumb: snip.thumbnails.medium.url,
link: 'https://www.youtube.com/watch?v=' + v.id.videoId
};
});
});
}
},
controller: 'ListOneController as list'
})
.state('state2', {
url: '/state2',
templateUrl: 'templates/state2.html'
})
.state('state2.list', {
url: '/list',
templateUrl: 'templates/state2.list.html',
controller: function($scope) {
$scope.things = ['A', 'Set', 'Of', 'Things'];
}
});
})
})();
|
const handlers = require('./handlers');
function list(call, callback) {
handlers.list(call.request).then((response) => callback(null, response));
}
function get(call, callback) {
handlers.get(call.request).then((response) => callback(null, response))
}
function create(call, callback) {
handlers.create(call.request).then(response => callback(null, response))
}
module.exports = {
list,
get,
create,
}
|
//
const key = "keys";
let index = -1;
const findMyKeys = (arr) => {
const index = arr.findIndex((item) => item === key);
return index;
};
// another way
// Alternate solution:
// As a function declaration using a loop:
// function findMyKeys(arr) {
// let index = -1;
// for (let i = 0; i < arr.length; i++) {
// if (arr[i] === key) {
// index = i;
// break;
// }
// }
// return index;
// }
const randomStuff = [
"credit card",
"screwdriver",
"receipt",
"gum",
"keys",
"used gum",
"plastic spoon",
];
console.log(findMyKeys(randomStuff));
|
import { getBannerFromDB, getCurriculumFromDB, getTeacherFromDB } from '../../database/dal/firebase/homeDal';
export const getBanner = () => {
return (dispatch) => {
getBannerFromDB(dispatch);
}
}
export const getCurriculum = () => {
return (dispatch) => {
getCurriculumFromDB(dispatch);
}
}
export const getTeacher = () => {
return (dispatch) => {
getTeacherFromDB(dispatch);
}
}
|
function Controller() {
function openAbout() {
APP.openWindow({
controller: "Widgets/Browser",
controllerParams: {
title: L("about"),
url: L("url_about")
}
});
return true;
}
function openMyAccountSettings() {
APP.getToken({
openLogin: true,
callback: function(_token) {
APP.openWindow({
controller: "Settings/MyAccountSettings",
controllerParams: {
token: _token
}
});
return true;
}
});
return true;
}
function openMyAlertSettings() {
APP.getToken({
openLogin: true,
callback: function(_token) {
return APP.openWindow({
controller: "Settings/MyAlertSettings",
controllerParams: {
token: _token
}
});
}
});
return true;
}
function openMyAddresses() {
APP.getToken({
openLogin: true,
callback: function(_token) {
APP.openWindow({
controller: "Settings/MyAddresses",
controllerParams: {
token: _token
}
});
return true;
}
});
return true;
}
function openPrivacy() {
APP.openWindow({
controller: "Widgets/Browser",
controllerParams: {
title: L("terms_and_cond"),
url: L("url_privacy")
}
});
return true;
}
function openShareApp() {
var _emailDialog = Ti.UI.createEmailDialog();
_emailDialog.subject = L("share_subject");
_emailDialog.messageBody = L("share_body") + "\n";
_emailDialog.open();
return true;
}
function setState(event) {
switch (event.source.id) {
case "law_enforcement_switch":
Ti.App.Properties.setBool("lawEnforcementS", event.value);
break;
case "send_anonymosly_switch":
Ti.App.Properties.setBool("anonymousS", event.value);
break;
case "community_watch_switch":
Ti.App.Properties.setBool("communityS", event.value);
break;
case "media_switch":
Ti.App.Properties.setBool("mediaS", event.value);
}
return true;
}
function updateView() {
APP.headerbar.setLeftButton(0, false);
APP.headerbar.setRightButton(0, false);
APP.headerbar.setLeftButton(APP.OPENMENU, true);
APP.headerbar.setTitle("Settings");
$.law_enforcement_switch.value = Boolean(Ti.App.Properties.getBool("lawEnforcementS"));
$.send_anonymosly_switch.value = Boolean(Ti.App.Properties.getBool("anonymousS"));
$.community_watch_switch.value = Boolean(Ti.App.Properties.getBool("communityS"));
$.media_switch.value = Boolean(Ti.App.Properties.getBool("mediaS"));
return true;
}
require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
this.__controllerPath = "Settings/Settings";
arguments[0] ? arguments[0]["__parentSymbol"] : null;
arguments[0] ? arguments[0]["$model"] : null;
arguments[0] ? arguments[0]["__itemTemplate"] : null;
var $ = this;
var exports = {};
var __defers = {};
$.__views.Settings = Ti.UI.createScrollView({
layout: "vertical",
id: "Settings"
});
$.__views.Settings && $.addTopLevelView($.__views.Settings);
$.__views.__alloyId1171 = Ti.UI.createView({
height: Alloy.Globals.CONTENT_TOP,
id: "__alloyId1171"
});
$.__views.Settings.add($.__views.__alloyId1171);
$.__views.__alloyId1172 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
layout: "absolute",
left: 0,
right: 0,
id: "__alloyId1172"
});
$.__views.Settings.add($.__views.__alloyId1172);
openMyAddresses ? $.__views.__alloyId1172.addEventListener("click", openMyAddresses) : __defers["$.__views.__alloyId1172!click!openMyAddresses"] = true;
$.__views.__alloyId1173 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
textid: "my_addresses",
id: "__alloyId1173"
});
$.__views.__alloyId1172.add($.__views.__alloyId1173);
$.__views.__alloyId1174 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1174"
});
$.__views.__alloyId1172.add($.__views.__alloyId1174);
$.__views.__alloyId1175 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId1175"
});
$.__views.Settings.add($.__views.__alloyId1175);
$.__views.__alloyId1176 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
layout: "absolute",
left: 0,
right: 0,
id: "__alloyId1176"
});
$.__views.Settings.add($.__views.__alloyId1176);
openMyAlertSettings ? $.__views.__alloyId1176.addEventListener("click", openMyAlertSettings) : __defers["$.__views.__alloyId1176!click!openMyAlertSettings"] = true;
$.__views.__alloyId1177 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
textid: "my_alert_settings",
id: "__alloyId1177"
});
$.__views.__alloyId1176.add($.__views.__alloyId1177);
$.__views.__alloyId1178 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1178"
});
$.__views.__alloyId1176.add($.__views.__alloyId1178);
$.__views.__alloyId1179 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId1179"
});
$.__views.Settings.add($.__views.__alloyId1179);
$.__views.__alloyId1180 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
layout: "absolute",
left: 0,
right: 0,
id: "__alloyId1180"
});
$.__views.Settings.add($.__views.__alloyId1180);
openMyAccountSettings ? $.__views.__alloyId1180.addEventListener("click", openMyAccountSettings) : __defers["$.__views.__alloyId1180!click!openMyAccountSettings"] = true;
$.__views.__alloyId1181 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
textid: "my_account_settings",
id: "__alloyId1181"
});
$.__views.__alloyId1180.add($.__views.__alloyId1181);
$.__views.__alloyId1182 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1182"
});
$.__views.__alloyId1180.add($.__views.__alloyId1182);
$.__views.__alloyId1183 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId1183"
});
$.__views.Settings.add($.__views.__alloyId1183);
$.__views.__alloyId1184 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
layout: "absolute",
left: 0,
right: 0,
id: "__alloyId1184"
});
$.__views.Settings.add($.__views.__alloyId1184);
openShareApp ? $.__views.__alloyId1184.addEventListener("click", openShareApp) : __defers["$.__views.__alloyId1184!click!openShareApp"] = true;
$.__views.__alloyId1185 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
textid: "share_app",
id: "__alloyId1185"
});
$.__views.__alloyId1184.add($.__views.__alloyId1185);
$.__views.__alloyId1186 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1186"
});
$.__views.__alloyId1184.add($.__views.__alloyId1186);
$.__views.__alloyId1187 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId1187"
});
$.__views.Settings.add($.__views.__alloyId1187);
$.__views.__alloyId1188 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
layout: "absolute",
left: 0,
right: 0,
id: "__alloyId1188"
});
$.__views.Settings.add($.__views.__alloyId1188);
$.__views.__alloyId1189 = Ti.UI.createLabel({
color: "black",
font: {
fontSize: 16
},
textAlign: "left",
left: 15,
textid: "sharing_preferences",
id: "__alloyId1189"
});
$.__views.__alloyId1188.add($.__views.__alloyId1189);
$.__views.__alloyId1190 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId1190"
});
$.__views.Settings.add($.__views.__alloyId1190);
$.__views.__alloyId1191 = Ti.UI.createView({
height: 40,
layout: "absolute",
left: 0,
right: 0,
id: "__alloyId1191"
});
$.__views.Settings.add($.__views.__alloyId1191);
$.__views.community_watch = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
textid: "community_watch",
id: "community_watch"
});
$.__views.__alloyId1191.add($.__views.community_watch);
$.__views.community_watch_switch = Ti.UI.createSwitch({
right: 15,
value: false,
id: "community_watch_switch"
});
$.__views.__alloyId1191.add($.__views.community_watch_switch);
setState ? $.__views.community_watch_switch.addEventListener("change", setState) : __defers["$.__views.community_watch_switch!change!setState"] = true;
$.__views.__alloyId1192 = Ti.UI.createView({
height: 40,
layout: "absolute",
left: 0,
right: 0,
id: "__alloyId1192"
});
$.__views.Settings.add($.__views.__alloyId1192);
$.__views.__alloyId1193 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
textid: "law_enforcement",
id: "__alloyId1193"
});
$.__views.__alloyId1192.add($.__views.__alloyId1193);
$.__views.law_enforcement_switch = Ti.UI.createSwitch({
right: 15,
value: false,
id: "law_enforcement_switch"
});
$.__views.__alloyId1192.add($.__views.law_enforcement_switch);
setState ? $.__views.law_enforcement_switch.addEventListener("change", setState) : __defers["$.__views.law_enforcement_switch!change!setState"] = true;
$.__views.__alloyId1194 = Ti.UI.createView({
height: 40,
layout: "absolute",
left: 0,
right: 0,
id: "__alloyId1194"
});
$.__views.Settings.add($.__views.__alloyId1194);
$.__views.__alloyId1195 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
textid: "media",
id: "__alloyId1195"
});
$.__views.__alloyId1194.add($.__views.__alloyId1195);
$.__views.media_switch = Ti.UI.createSwitch({
right: 15,
value: false,
id: "media_switch"
});
$.__views.__alloyId1194.add($.__views.media_switch);
setState ? $.__views.media_switch.addEventListener("change", setState) : __defers["$.__views.media_switch!change!setState"] = true;
$.__views.__alloyId1196 = Ti.UI.createView({
height: 40,
layout: "absolute",
left: 0,
right: 0,
id: "__alloyId1196"
});
$.__views.Settings.add($.__views.__alloyId1196);
$.__views.__alloyId1197 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
textid: "send_anonymosly",
id: "__alloyId1197"
});
$.__views.__alloyId1196.add($.__views.__alloyId1197);
$.__views.send_anonymosly_switch = Ti.UI.createSwitch({
right: 15,
value: false,
id: "send_anonymosly_switch"
});
$.__views.__alloyId1196.add($.__views.send_anonymosly_switch);
setState ? $.__views.send_anonymosly_switch.addEventListener("change", setState) : __defers["$.__views.send_anonymosly_switch!change!setState"] = true;
$.__views.__alloyId1198 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId1198"
});
$.__views.Settings.add($.__views.__alloyId1198);
$.__views.__alloyId1199 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
layout: "absolute",
left: 0,
right: 0,
id: "__alloyId1199"
});
$.__views.Settings.add($.__views.__alloyId1199);
openAbout ? $.__views.__alloyId1199.addEventListener("click", openAbout) : __defers["$.__views.__alloyId1199!click!openAbout"] = true;
$.__views.__alloyId1200 = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
textid: "about",
id: "__alloyId1200"
});
$.__views.__alloyId1199.add($.__views.__alloyId1200);
$.__views.__alloyId1201 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1201"
});
$.__views.__alloyId1199.add($.__views.__alloyId1201);
$.__views.__alloyId1202 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId1202"
});
$.__views.Settings.add($.__views.__alloyId1202);
$.__views.__alloyId1203 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
layout: "absolute",
left: 0,
right: 0,
id: "__alloyId1203"
});
$.__views.Settings.add($.__views.__alloyId1203);
openPrivacy ? $.__views.__alloyId1203.addEventListener("click", openPrivacy) : __defers["$.__views.__alloyId1203!click!openPrivacy"] = true;
$.__views.terms_and_cond = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
textid: "terms_and_cond",
id: "terms_and_cond"
});
$.__views.__alloyId1203.add($.__views.terms_and_cond);
$.__views.__alloyId1204 = Ti.UI.createImageView({
image: "/images/ic_forward.png",
right: 0,
width: 36,
height: 36,
id: "__alloyId1204"
});
$.__views.__alloyId1203.add($.__views.__alloyId1204);
$.__views.__alloyId1205 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId1205"
});
$.__views.Settings.add($.__views.__alloyId1205);
$.__views.__alloyId1206 = Ti.UI.createView({
backgroundColor: "white",
height: 40,
layout: "horizontal",
left: 0,
right: 0,
id: "__alloyId1206"
});
$.__views.Settings.add($.__views.__alloyId1206);
$.__views.version = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
text: Alloy.Globals.VERSION,
height: 40,
id: "version"
});
$.__views.__alloyId1206.add($.__views.version);
$.__views.copyright = Ti.UI.createLabel({
color: "#333",
font: {
fontSize: 14
},
textAlign: "left",
left: 15,
textid: "copyright",
height: 40,
id: "copyright"
});
$.__views.__alloyId1206.add($.__views.copyright);
$.__views.__alloyId1207 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId1207"
});
$.__views.Settings.add($.__views.__alloyId1207);
$.__views.__alloyId1208 = Ti.UI.createView({
height: Alloy.Globals.CONTENT_BOTTOM,
id: "__alloyId1208"
});
$.__views.Settings.add($.__views.__alloyId1208);
exports.destroy = function() {};
_.extend($, $.__views);
var APP = require("/core");
arguments[0] || {};
exports.updateView = updateView;
__defers["$.__views.__alloyId1172!click!openMyAddresses"] && $.__views.__alloyId1172.addEventListener("click", openMyAddresses);
__defers["$.__views.__alloyId1176!click!openMyAlertSettings"] && $.__views.__alloyId1176.addEventListener("click", openMyAlertSettings);
__defers["$.__views.__alloyId1180!click!openMyAccountSettings"] && $.__views.__alloyId1180.addEventListener("click", openMyAccountSettings);
__defers["$.__views.__alloyId1184!click!openShareApp"] && $.__views.__alloyId1184.addEventListener("click", openShareApp);
__defers["$.__views.community_watch_switch!change!setState"] && $.__views.community_watch_switch.addEventListener("change", setState);
__defers["$.__views.law_enforcement_switch!change!setState"] && $.__views.law_enforcement_switch.addEventListener("change", setState);
__defers["$.__views.media_switch!change!setState"] && $.__views.media_switch.addEventListener("change", setState);
__defers["$.__views.send_anonymosly_switch!change!setState"] && $.__views.send_anonymosly_switch.addEventListener("change", setState);
__defers["$.__views.__alloyId1199!click!openAbout"] && $.__views.__alloyId1199.addEventListener("click", openAbout);
__defers["$.__views.__alloyId1203!click!openPrivacy"] && $.__views.__alloyId1203.addEventListener("click", openPrivacy);
_.extend($, exports);
}
var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;
module.exports = Controller;
|
/* variables locales de T_FCTRCOHOJWGYR_975*/
|
const colorPalet = {
primary: '#ACC18A',
secundary: '#837A75',
bgApp: '#F2FBE0',
active: '#DAFEB7',
dark: '#605B56',
bg: '#f5f5f5',
};
export { colorPalet };
|
import React from 'react'
import { Link, withRouter } from 'react-router-dom'
import DogResult from '../DogResult'
export default withRouter(function ({ dogs, history }) {
return <>
<section className="navi">
<Link className="navi__logo" to="/profile"><i className="fas fa-paw"></i></Link>
<input className="navi__search" onClick={event => {
event.preventDefault()
history.push('/search')
}}
type="text" placeholder="Find your dog ..."></input>
</section>
<section className="noresults">
{!dogs.length && <> <i className="noresults__sign fas fa-exclamation-triangle"></i>
<h3 className="noresults__text">No dogs found</h3></>}
</section>
<section className="results">
<ul className="results__ul">
{dogs.map(dog => <li className="results__li"><DogResult dog={dog} /></li>)}
</ul>
</section>
</>
})
|
import React, {Component} from 'react'
import { Text, Linking, TouchableHighlight } from 'react-native'
import Colors from '@Colors/colors'
import merge from '../util/merge'
import commonStyle from './style'
// The designs have a number of screens where fonst of mixed size are displayed on the same
// line of text. Typically this would be achieved by vertically aligning text around the baseline.
// However, this is not supported in react native. In order to achieve the same result, the baseline
// of the Museo 300 font used by this app has been measured experimentally, giving rise to the function
// below. Aliging fonts of different sizes can be achieved by offsetting them based on their respective
// baselines.
export const baselineForFontSize = (size) =>
size / 40 * 9
export const baselineDeltaForFonts = (largeFontSize, smallFontSize) =>
baselineForFontSize(largeFontSize) - baselineForFontSize(smallFontSize)
const style = {
fontFamily: commonStyle.font.museo300,
fontSize: 18,
color: Colors.offBlack,
backgroundColor: Colors.transparent
}
class DefaultText extends Component {
setNativeProps (nativeProps) {
this._root.setNativeProps(nativeProps)
}
render () {
const newStyle = merge(style, this.props.style)
const defaultProps = {
numberOfLines: 1,
ellipsizeMode: 'tail'
}
return (
<Text
ref={component => this._root = component}
{...merge(defaultProps, this.props, {style: newStyle})}>
{this.props.children}
</Text>
)
}
}
export class MultilineText extends Component {
setNativeProps (nativeProps) {
this._root.setNativeProps(nativeProps)
}
render () {
const newStyle = merge(style, this.props.style)
return (
<Text {...this.props}
ref={component => this._root = component}
style={newStyle}>
{this.props.children}
</Text>
)
}
}
export const HyperlinkText = ({text, link, style}) =>
<TouchableHighlight underlayColor='transparent'
onPress={() => Linking.openURL(link)}>
<DefaultText style={{
textDecorationLine: 'underline',
...style
}}>
{text}
</DefaultText>
</TouchableHighlight>
export default DefaultText
|
import {
NOUN_SEARCH,
NOUN_SEARCH_SUCCESS,
NOUN_SEARCH_FAILURE,
WEIGHT_TEST,
WEIGHT_TEST_SUCCESS,
WEIGHT_TEST_FAILURE,
WEIGHT_EDIT,
WEIGHT_DATA,
WEIGHT_DATA_SUCCESS,
WEIGHT_DATA_FAILURE,
WEIGHT_DATA_LIST,
WEIGHT_DATA_LIST_SUCCESS,
WEIGHT_DATA_LIST_FAILURE,
WEIGHT_SAVE,
WEIGHT_DATA_LIST_COUNT,
WEIGHT_DATA_LIST_COUNT_SUCCESS,
WEIGHT_DATA_LIST_COUNT_FAILURE
} from './ActionTypes';
import {API} from '../common';
import axios from 'axios';
var answer_management_log = `${API}/log/answer_management_log`;
var answer_management = `${API}/answer_management`;
/* WEIGHT_DATA_LIST */
export function getWeightDataList(page) {
return (dispatch) => {
// Inform Login API is starting
dispatch(getWeightDataListload());
// API REQUEST
return axios.get(`${answer_management_log}/nouns_adjust?page=${page}&pagesize=10`)
.then((response) => {
// SUCCEED
dispatch(getWeightDataListSuccess(response.data, page));
}).catch(() => {
// FAILED
dispatch(getWeightDataListFailure());
});
};
}
export function getWeightDataListload() {
return {
type: WEIGHT_DATA_LIST
};
}
export function getWeightDataListSuccess(data, page) {
return {
type: WEIGHT_DATA_LIST_SUCCESS,
data, page
};
}
export function getWeightDataListFailure() {
return {
type: WEIGHT_DATA_LIST_FAILURE
};
}
export function getWeightDataListCount() {
return (dispatch) => {
// Inform Login API is starting
dispatch(getWeightDataListCountload());
// API REQUEST
return axios.get(`${answer_management_log}/nouns_adjust/count`)
.then((response) => {
// SUCCEED
dispatch(getWeightDataListCountSuccess(response.data));
}).catch(() => {
// FAILED
dispatch(getWeightDataListCountFailure());
});
};
}
export function getWeightDataListCountload() {
return {
type: WEIGHT_DATA_LIST_COUNT
};
}
export function getWeightDataListCountSuccess(data) {
return {
type: WEIGHT_DATA_LIST_COUNT_SUCCESS,
data
};
}
export function getWeightDataListCountFailure() {
return {
type: WEIGHT_DATA_LIST_COUNT_FAILURE
};
}
/* WEIGHT_DATA */
export function getWeightData(id) {
return (dispatch) => {
// Inform Login API is starting
dispatch(getWeightDataload());
// API REQUEST
return axios.get(`${answer_management_log}/nouns_adjust/${id}`)
.then((response) => {
// SUCCEED
var str = response.data.noun_string_sort;
return axios.get(`${answer_management}/nouns_weights/${str}`)
.then((res) => {
if(res.status === 200){
dispatch(searchNounSuccess(res.data));
}else{
dispatch(getWeightDataSuccess(response.data));
}
}).catch(() => {
dispatch(searchNounFailure());
});
}).catch(() => {
// FAILED
dispatch(getWeightDataFailure());
});
};
}
export function getWeightDataload() {
return {
type: WEIGHT_DATA
};
}
export function getWeightDataSuccess(data) {
return {
type: WEIGHT_DATA_SUCCESS,
data
};
}
export function getWeightDataFailure() {
return {
type: WEIGHT_DATA_FAILURE
};
}
export function searchNounLoad() {
return {
type: NOUN_SEARCH
};
}
export function searchNounSuccess(data) {
return {
type: NOUN_SEARCH_SUCCESS,
data
};
}
export function searchNounFailure() {
return {
type: NOUN_SEARCH_FAILURE
};
}
/* WEIGHT_TEST */
export function weightTest(id, data) {
return (dispatch) => {
// Inform Register API is starting
dispatch(weightTestLoad());
return axios.post(`${answer_management_log}/nouns_adjust/test/${id}`, data)
.then((response) => {
console.log(response)
dispatch(weightTestSuccess(id, response.data));
}).catch(() => {
dispatch(weightTestFailure());
});
};
}
export function weightTestLoad() {
return {
type: WEIGHT_TEST
};
}
export function weightTestSuccess(id, data) {
return {
type: WEIGHT_TEST_SUCCESS,
id,
data
};
}
export function weightTestFailure() {
return {
type: WEIGHT_TEST_FAILURE
};
}
/* WEIGHT_SAVE */
export function weightSave(data, page) {
return (dispatch) => {
// Inform Register API is starting
dispatch(weightSaveLoad());
return axios.post(`${answer_management}/nouns_weights`, data)
.then(() => {
alert('저장되었습니다.')
dispatch(getWeightDataList(page));
}).catch(() => {
return alert('잠시 후 다시 시도해주세요.')
});
};
}
export function weightSaveLoad() {
return {
type: WEIGHT_SAVE
};
}
/* WEIGHT_EDIT */
export function weightEdit(id, data, page) {
return (dispatch) => {
// Inform Register API is starting
dispatch(weightEditLoad());
return axios.put(`${answer_management}/nouns_weights/${id}`, data)
.then(() => {
alert('저장되었습니다.')
dispatch(getWeightDataList(page));
}).catch(() => {
return alert('잠시 후 다시 시도해주세요.')
});
};
}
export function weightEditLoad() {
return {
type: WEIGHT_EDIT
};
}
// export function weightEditSuccess() {
// return {
// type: WEIGHT_EDIT_SUCCESS,
// };
// }
// export function weightEditFailure() {
// return {
// type: WEIGHT_EDIT_FAILURE
// };
// }
// /* SAVED_WEIGHT_LIST */
// export function weightList(page) {
// return (dispatch) => {
// // Inform Register API is starting
// dispatch(weightListLoad());
// return axios.get(`${answer_management}/nouns_weights?page=${page}&pagesize=10`)
// .then((response) => {
// dispatch(weightListSuccess(response.data));
// }).catch(() => {
// dispatch(weightListFailure());
// });
// };
// }
// export function weightListLoad() {
// return {
// type: SAVED_WEIGHT_LIST
// };
// }
// export function weightListSuccess(data) {
// return {
// type: SAVED_WEIGHT_LIST_SUCCESS,
// data
// };
// }
// export function weightListFailure() {
// return {
// type: SAVED_WEIGHT_LIST_FAILURE
// };
// }
// /* WEIGHT_DELETE */
// export function weightDelete(id) {
// return (dispatch) => {
// // Inform Register API is starting
// dispatch(weightDeleteLoad());
// return axios.delete(`${answer_management}/nouns_weights/${id}`)
// .then(() => {
// dispatch(weightDeleteSuccess());
// }).catch(() => {
// dispatch(weightDeleteFailure());
// });
// };
// }
// export function weightDeleteLoad() {
// return {
// type: WEIGHT_DELETE
// };
// }
// export function weightDeleteSuccess() {
// return {
// type: WEIGHT_DELETE_SUCCESS,
// };
// }
// export function weightDeleteFailure() {
// return {
// type: WEIGHT_DELETE_FAILURE
// };
// }
|
function solution(A) {
//goal: return the beginning of any ascending slice of A of
let comb = []
//generate combination with size of 1
for (i = 0; i < A.length; i++) {
comb.push(combinations1 = generateCombinations(A[i], A[i]))
// console.log(combinations1)
}
//generate combination with size of 2
for (i = 0; i < A.length; i++) {
if (A[i] != A[A.length - 1]) {
comb.push(combinations2 = generateCombinations(A[i], A[i + 1]))
// console.log(combinations2)
}
}
console.log(comb)
//step 1: generate all possible combination of slices - brute force
//step 2: select those that are only ascending - analyze array
//condition 1 for ascending - size =1 and same element
//condition 2 for ascending - each corresponding element is increasing
//step 3: determine the max size of ascending array and replace the variable maxSize
//step 4: only select those slices that match max size
//step 5: return the beginning of the slice
}
function check(comb2) {
}
function generateCombinations(firstElement, secondElement) {
let combo = [];
// Recursion call to generate a combination of size 1
combo.push(firstElement, secondElement)
//recusion call to generate a combination of size of 2
return combo
}
solution([2, 3, 4, 3, 6])
|
export const indexToString = (item, index) => index.toString();
export const capitalize = (text = '') =>
text.charAt(0).toUpperCase() + text.substr(1);
export const extractSetupParams = (route) => {
if (!route || !route.params) {
return {
gender: '',
updateSetup: false,
};
}
return {
birthDate: route.params.birthDate,
country: route.params.country,
state: route.params.state,
countryName: route.params.countryName,
stateName: route.params.stateName,
givenName: route.params.givenName,
gender: route.params.gender || '',
birthPlace: route.params.birthPlace,
platform: route.params.platform,
notifications: route.params.notifications,
updateSetup: route.params.updateSetup || false,
};
};
|
const
express = require('express'),
{Question} = require('../db'),
router = express.Router(),
ObjectId = require('mongodb').ObjectID;
router.get('/', async (req, res)=>{
try {
const questions = await Question.find(req.query)
res.status(200).json(questions);
} catch(err){
res.status(500).json({message : "something went wrong!"})
}
});
router.get('/:id', async (req, res) => {
try{
const {id} = req.params;
const question = await Question.find({"_id" : ObjectId(`${id}`)});
res.status(200).json(question);
} catch(err){
res.status(404).json({error: "please enter a proper ID"});
}
});
module.exports = router;
|
import {render, screen} from '@testing-library/react'
import HelloWorld from './HelloWorld'
test("print hello world to the user", () => {
const rendered = render(<HelloWorld/>);
const hello = screen.getByText(" Hello World from Component ");
// test be in the Document
expect(hello).toBeInTheDocument();
// test et enregistre l'etat du test
//expect(hello).toMatchSnapShot();
} );
|
import React, { useState, useEffect } from 'react'
import { useParams } from 'react-router';
import {verifyEmail} from "./apicalls"
export default function VerificationEmail() {
const { verifToken } = useParams();
const [verification, setVerification] = useState({});
console.log(verifToken)
useEffect(() => {
//Authenticate our cookie sir
(async function () {
const res = await verifyEmail({
verifToken,
});
setVerification(res);
})();
}, []);
return (
<div>
<h2>user is verified {verification.verified}</h2>
</div>
)
}
|
import React, { Component } from "react";
import PropTypes from "prop-types";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
// import InputBase from "@material-ui/core/InputBase";
import { withStyles } from "@material-ui/core/styles";
// import SearchIcon from "@material-ui/icons/Search";
// import Grid from "@material-ui/core/Grid";
// import Radio from "@material-ui/core/Radio";
// import RadioGroup from "@material-ui/core/RadioGroup";
// import FormGroup from "@material-ui/core/FormGroup";
import Typography from '@material-ui/core/Typography';
// import FormControlLabel from "@material-ui/core/FormControlLabel";
// import Checkbox from "@material-ui/core/Checkbox";
// import FormLabel from "@material-ui/core/FormLabel";
// import Button from "@material-ui/core/Button";
// import API from "../../utils/API";
// import RecipeCard from "../RecipeCard/index";
// import Firebase from "../../config/Firebase";
// import Swal from "sweetalert2";
// import CircularProgress from "@material-ui/core/CircularProgress";
import "./style.css";
const styles = theme => ({
root: {
width: "100%"
},
// search: {
// position: "relative",
// borderRadius: theme.shape.borderRadius,
// backgroundColor: "rgba(55, 55, 55, 0.65)",
// "&:hover": {
// backgroundColor: "rgba(55, 55, 55, 0.8)"
// },
// marginLeft: "0!important",
// width: "100%",
// height: "35px",
// [theme.breakpoints.up("sm")]: {
// marginLeft: theme.spacing.unit,
// width: "auto"
// }
// },
// searchIcon: {
// width: theme.spacing.unit * 9,
// height: "100%",
// position: "absolute",
// pointerEvents: "none",
// display: "flex",
// alignItems: "center",
// justifyContent: "center"
// },
// inputRoot: {
// color: "inherit",
// width: "100%",
// position: "relative"
// },
// inputInput: {
// paddingTop: "1px",
// paddingRight: theme.spacing.unit,
// paddingBottom: "1px",
// paddingLeft: theme.spacing.unit * 10,
// transition: theme.transitions.create("width"),
// width: "100%",
// height: "30px",
// [theme.breakpoints.up("sm")]: {
// width: 120,
// "&:focus": {
// width: 200
// }
// }
// },
// recipeModalTitle: {
// fontSize: "12px"
// },
// recipeModalText: {
// fontSize: "10px"
// },
// buttonProgress: {
// color: "white",
// position: "absolute",
// top: "50%",
// right: "10%",
// marginTop: -12,
// marginLeft: -12
// },
// buttonProgressAlt: {
// color: "rgb(100,100,100)",
// position: "absolute",
// top: "50%",
// right: "-25%",
// marginTop: -12,
// marginLeft: -12
// }
});
class Title extends Component {
render(props) {
const { classes } = this.props;
return (
<div className={classes.root}>
<AppBar position="static">
<Toolbar className="searchMenuBg">
<Typography
className="title searchbarMarginFix"
>
{this.props.children}
</Typography>
</Toolbar>
</AppBar>
</div>
);
}
}
Title.propTypes = {
classes: PropTypes.object.isRequired
};
export default withStyles(styles)(Title);
|
import React from 'react';
import {View, Text, TouchableOpacity, Dimensions} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import styled from 'styled-components';
import {ICAlam, ICEvent, ICScan} from '../../../Assets';
const width = Dimensions.get('screen').width;
export default function ButtonChoice({type, onPress}) {
const Icon = type => {
switch (type) {
case 'Scan':
return <ICScan />;
case 'Event':
return <ICEvent />;
case 'Alam':
return <ICAlam />;
}
};
const colorGradient = type => {
let data = [];
if (type === 'Scan') {
data = ['#ED673C', '#DFB536'];
} else {
data = ['#FFFFFF', '#FFFFFF'];
}
return data;
};
const checkColor = type => {
if (type === 'Scan') {
return '#FFFFFF';
} else {
return 'black';
}
};
return (
<LinearGradient
colors={colorGradient(type)}
style={{
width: (width * 27) / 100,
height: (width * 27) / 100,
marginHorizontal: 8,
borderRadius: 8,
}}>
<ContainerButton onPress={onPress}>
{Icon(type)}
<TextAbsolute color={checkColor(type)}>{type}</TextAbsolute>
</ContainerButton>
</LinearGradient>
);
}
const ContainerButton = styled.TouchableOpacity`
height: 100%;
justify-content: center;
align-items: center;
border-radius: 8px;
border: 2px solid #f4f4f4;
`;
const TextAbsolute = styled.Text`
position: absolute;
bottom: 0px;
color: ${props => props.color};
`;
|
const productNam = require("../models/product.nam");
const productNu = require("../models/product.nu");
const productGirl = require("../models/product.girl");
const productBoy = require("../models/product.boy");
const dataFull = require("../models/fulldata");
const productAccessories = require("../models/product.accessories");
class ProductInfo {
comment(req, res) {
res.send("Asd");
}
index(req, res) {
res.send("new");
}
async show(req, res) {
try {
const numberid = req.params.numberid;
const data = await dataFull.findOne({ maSp: numberid });
res.json(data);
} catch {
res.status(401);
}
}
productList(req, res) {
// const data = req.body;
// console.log(data);
res.json({ d: "sdasd" });
}
}
module.exports = new ProductInfo();
|
import examGroups from "./examGroups"
import examLogs from "./examLogs"
import exams from "./exams"
import auth from "./auth"
export default {
examGroups,
examLogs,
exams,
auth
}
|
export default {
api: {
baseUrl: "https://api.themoviedb.org/3/",
},
images: {
base_url: "http://image.tmdb.org/t/p/",
secure_base_url: "https://image.tmdb.org/t/p/",
backdrop_sizes: ["w300", "w780", "w1280", "original"],
logo_sizes: ["w45", "w92", "w154", "w185", "w300", "w500", "original"],
poster_sizes: ["w92", "w154", "w185", "w342", "w500", "w780", "original"],
profile_sizes: ["w45", "w185", "h632", "original"],
still_sizes: ["w92", "w185", "w300", "original"],
},
change_keys: [
"adult",
"air_date",
"also_known_as",
"alternative_titles",
"biography",
"birthday",
"budget",
"cast",
"certifications",
"character_names",
"created_by",
"crew",
"deathday",
"episode",
"episode_number",
"episode_run_time",
"freebase_id",
"freebase_mid",
"general",
"genres",
"guest_stars",
"homepage",
"images",
"imdb_id",
"languages",
"name",
"network",
"origin_country",
"original_name",
"original_title",
"overview",
"parts",
"place_of_birth",
"plot_keywords",
"production_code",
"production_companies",
"production_countries",
"releases",
"revenue",
"runtime",
"season",
"season_number",
"season_regular",
"spoken_languages",
"status",
"tagline",
"title",
"translations",
"tvdb_id",
"tvrage_id",
"type",
"video",
"videos",
],
};
|
export const AUTH_START = 'AUTH_START';
export const AUTH_SUCCESS = 'AUTH_SUCCESS';
export const AUTH_FAIL = 'AUTH_FAIL';
export const AUTH_LOGOUT = 'AUTH_LOGOUT';
export const SET_PROFILE = 'SET_PROFILE';
export const PROFILE_END = 'PROFILE_END';
export const CHANGE_PASSWORD = 'CHANGE_PASSWORD';
export const TOURNAMENT_START = 'TOURNAMENT_START';
export const TOURNAMENT_PAST_SUCCESS = 'TOURNAMENT_PAST_SUCCESS';
export const TOURNAMENT_UPCOMING_SUCCESS = 'TOURNAMENT_UPCOMING_SUCCESS';
export const TOURNAMENT_END = 'TOURNAMENT_END';
export const TOURNAMENT_SUCCESS = 'TOURNAMENT_SUCCESS';
export const MYTOURNAMENT_SUCCESS = 'MYTOURNAMENT_SUCCESS';
export const MYTOURNAMENT_DELETE = 'MYTOURNAMENT_DELETE';
export const MYPARTICIPATION_SUCCESS = 'MYPARTICIPATION_SUCCESS';
|
const utils = require('./utils')
module.exports = {
title: 'awesome-record',
description: '个人记录',
base: '/awesome-record/',
themeConfig: {
nav:[
{
text:'首页',
link:'/'
},
{
text: '算法',
link: '/algorithm/chapter1'
},
{
text: 'Blog',
link: '/blog/vue'
}
],
sidebar: utils.inferSiderbars(),
repo:'wungjyan/awesome-record',
editLinkText: '在 GitHub 上编辑此页',
lastUpdated:'上次更新'
}
}
|
export default function Home() {
return (
<div className="m-4">
<h1 className="font-bold text-2xl mb-4">Tutorial Start</h1>
<p>
Welcome to my sample project for Modern Test Driven Development with:
</p>
<ul className="list-disc list-inside">
<li>Storybook</li>
<li>React Testing Library</li>
<li>Mock Service Worker</li>
</ul>
</div>
);
}
|
import React from "react";
import { withRouter } from "react-router-dom";
import { connect } from "react-redux";
import Api from "../data/Api";
import Nav from "../data/Nav";
import MovieCard from "../components/MovieCard";
import TvCard from "../components/TvCard";
import Carousel from "../components/Carousel";
import { ReactComponent as Spinner } from "../assets/svg/spinner.svg";
class Actor extends React.Component {
constructor(props) {
super(props);
this.state = {
bioOpen: false,
};
this.getActor = this.getActor.bind(this);
this.handleScroll = this.handleScroll.bind(this);
this.toggleBio = this.toggleBio.bind(this);
}
componentDidMount() {
let page = document.querySelectorAll(".page-wrap")[0];
let scrollY = 0;
let pHist = Nav.getNav(this.props.location.pathname);
page.scrollTop = scrollY;
if (pHist) {
this.setState(pHist.state);
} else {
let id = this.props.match.params.id;
this.getActor(id);
}
}
componentDidUpdate() {
if (this.state.getPos) {
this.setState({
getPos: false,
});
this.getPos();
}
}
componentWillUnmount() {
let page = document.querySelectorAll(".page-wrap")[0];
let carouselsData = document.querySelectorAll(".carousel");
let carousels = [];
carouselsData.forEach((carousel) => {
carousels.push(carousel.scrollLeft);
});
let state = this.state;
state.scrollWatch = false;
Nav.storeNav(
this.props.location.pathname,
state,
page.scrollTop,
carousels
);
}
getPos() {
let page = document.querySelectorAll(".page-wrap")[0];
let scrollY = 0;
let pHist = Nav.getNav(this.props.location.pathname);
if (pHist) {
scrollY = pHist.scroll;
document.querySelectorAll(".carousel").forEach((carousel, i) => {
carousel.scrollLeft = pHist.carousels[i];
});
}
page.scrollTop = scrollY;
}
getActor(id) {
if (!this.props.api.person_lookup[id]) {
// check for cached
Api.person(id);
}
}
handleScroll(e) {
let banner = e.currentTarget.querySelectorAll(".person--banner")[0];
let poster = e.currentTarget.querySelectorAll(".person--thumb--inner")[0];
let offset =
e.currentTarget.scrollTop > banner.offsetHeight
? 1
: e.currentTarget.scrollTop / banner.offsetHeight;
let posterOffset = 10 * offset;
offset = offset * 10 + 40;
banner.style.backgroundPosition = `50% ${offset}%`;
poster.style.transform = `translateY(${posterOffset}px)`;
}
sortByRanking(a, b) {
if (a.ranking < b.ranking) {
return 1;
}
if (a.ranking > b.ranking) {
return -1;
}
return 0;
}
processCredits(credits, items) {
for (let i in items) {
let item = items[i];
if (!credits[item.id]) {
let ranking = Math.round(item.popularity * item.vote_count);
item.ranking = ranking;
credits[item.id] = item;
}
if (item.job) {
if (credits[item.id].jobs) {
credits[item.id].jobs[item.job] = item.job;
} else {
credits[item.id].jobs = new Array();
credits[item.id].jobs[item.job] = item.job;
}
}
if (item.character) {
if (credits[item.id].characters) {
credits[item.id].characters[item.character] = item.character;
} else {
credits[item.id].characters = new Array();
credits[item.id].characters[item.character] = item.character;
}
}
}
return credits;
}
processCredit(item, personData) {
let credit = null;
if (personData.known_for_department !== "Acting") {
// Not actor
credit = item.jobs ? item.jobs : item.characters ? item.characters : null;
} else {
// actor
credit = item.characters ? item.characters : item.jobs ? item.jobs : null;
}
if (credit) {
let output = "";
for (let i in credit) {
output += `${credit[i]} / `;
}
credit = output;
credit = credit.substring(0, credit.length - 3);
}
return credit;
}
toggleBio() {
this.setState({
bioOpen: this.state.bioOpen ? false : true,
});
}
render() {
let id = this.props.match.params.id;
let personData = this.props.api.person_lookup[id];
if (!personData) {
return (
<div className="page-wrap">
<div className="spinner">
<Spinner />
</div>
</div>
);
}
if (personData.success === false) {
return (
<div className="page-wrap">
<p className="main-title">Person Not Found</p>
<p>
This person may have been removed from TMDb or the link you've
followed is invalid
</p>
</div>
);
}
let banner = false;
let bWidth = 0;
// Credits Movie
let movieCredits = this.props.api.actor_movie[id];
let moviesList = false;
if (movieCredits) {
moviesList = {};
moviesList = this.processCredits(moviesList, movieCredits.cast);
moviesList = this.processCredits(moviesList, movieCredits.crew);
moviesList = Object.values(moviesList);
moviesList.sort(this.sortByRanking);
}
// Credits TV
let tvCredits = this.props.api.actor_series[id];
let showsList = false;
if (tvCredits) {
showsList = {};
showsList = this.processCredits(showsList, tvCredits.cast);
showsList = this.processCredits(showsList, tvCredits.crew);
showsList = Object.values(showsList);
showsList.sort(this.sortByRanking);
}
if (!personData.images) {
banner = false;
bWidth = 0;
} else {
personData.images.profiles.forEach((image) => {
if (image.width > bWidth) {
banner = image;
bWidth = image.width;
}
});
}
return (
<>
<div className="page-wrap" onScroll={this.handleScroll}>
<div className="generic-wrap">
<div className="person--wrap">
<div
className="person--banner"
style={{
backgroundImage: `url(https://image.tmdb.org/t/p/original${banner.file_path})`,
}}
></div>
<div className="person--top">
<div className="person--thumb">
<div className="person--thumb--inner">
{personData.profile_path ? (
<img
src={`https://image.tmdb.org/t/p/w500${personData.profile_path}`}
/>
) : (
<img src="/images/no-poster-person.jpg" />
)}
</div>
</div>
<div className="person--details">
<h1 className="single-title">{personData.name}</h1>
<p>{personData.place_of_birth}</p>
<p>{personData.known_for_department}</p>
</div>
</div>
<section>
<div className="person--bio">
<h3 className="sub-title mb--1">Biography</h3>
{personData.biography ? (
<div className={`bio ${this.state.bioOpen ? "open" : ""}`}>
{personData.biography.split("\n").map((str, i) => (
<p key={`bio-${i}`}>{str}</p>
))}
</div>
) : null}
<p
onClick={this.toggleBio}
className="person--bio--read-more"
>
{this.state.bioOpen ? "Read less" : "Read more"}
</p>
</div>
</section>
{moviesList.length > 0 ? (
<section>
<h3 className="sub-title mb--1">Movies</h3>
<Carousel>
{Object.keys(moviesList).map((key, i) => {
let result = moviesList[key];
if (result.rating < 100) return null; // threshold to display
return (
<MovieCard
key={result.id + "-cast-" + i}
movie={result}
msg={this.props.msg}
character={this.processCredit(result, personData)}
/>
);
})}
</Carousel>
</section>
) : null}
{showsList.length > 0 ? (
<section>
<h3 className="sub-title mb--1">TV</h3>
<Carousel>
{Object.keys(showsList).map((key, i) => {
let result = showsList[key];
if (result.rating < 100) return null; // threshold to display
return (
<TvCard
key={result.id + "-cast-" + i}
series={result}
msg={this.props.msg}
character={this.processCredit(result, personData)}
/>
);
})}
</Carousel>
</section>
) : null}
</div>
</div>
</div>
</>
);
}
}
Actor = withRouter(Actor);
function ActorContainer(props) {
return <Actor api={props.api} msg={props.msg} />;
}
const mapStateToProps = function (state) {
return {
api: state.api,
};
};
export default connect(mapStateToProps)(ActorContainer);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.