text
stringlengths
7
3.69M
// adapted from https://github.com/nunof07/markdown-it-fontawesome/blob/master/index.js import Plugin from 'markdown-it-regexp'; export default function(md, options) { md.use(Plugin(/\:(fa[srb])-([\w\-]*\w)\:/, (m, utils) => `<%= ${m[1]}('${m[2]}') %>`)); }
var files_dup = [ [ "block_cluster.cpp", "block__cluster_8cpp.html", "block__cluster_8cpp" ], [ "block_cluster.h", "block__cluster_8h_source.html", null ], [ "graph_cluster.cpp", "graph__cluster_8cpp.html", "graph__cluster_8cpp" ], [ "graph_cluster.h", "graph__cluster_8h_source.html", null ], [ "h_mat.h", "h__mat_8h_source.html", null ], [ "main.cpp", "main_8cpp.html", "main_8cpp" ], [ "tree.cpp", "tree_8cpp.html", "tree_8cpp" ], [ "tree.h", "tree_8h_source.html", null ] ];
$(window).scroll(function(){ if($('.navbar').offset().top > 50){ $('.navbar-fixed-top').addClass('top-nav-collapse'); } else{ $('.navbar-fixed-top').removeClass('top-nav-collapse'); } }) $(function(){ $('.page-scroll a').bind('click', function(){ var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1500, 'easeInOutExpo'); event.preventDefault(); }); }); $(document).ready(function(){ $('.play').bind('mouseenter mouseleave', function(){ $(this).attr({ src: $(this).attr('data-other-src') , 'data-other-src' : $(this).attr('src') }); }); $("[rel='tooltip']").tooltip(); $('.thumbnail').hover( function(){ $(this).find('.caption').slideDown(250); //.fadeIn(250) }, function(){ $(this).find('.caption').slideUp(250); //.fadeOut(205) } ); });
/** * Implementation of Factory pattern to create various objects required * for eskin model construction **/ //TODO figure out how to unit test factory pattern var SBMLFactory = d3scomos.SBMLFactory = function SBMLFactory (){ /** return this **/ var factory = {}; var factoryProto = factory.prototype; /** * SBMLModel */ factory.getSBMLModel = function(options){ return new SBMLModel(options); } /** expose the SBML object constructors **/ factory.getBase = function(options){ return new Base(options); } factory.getSpecies = function(options){ return new Species(options); } factory.getCompartment = function(options){ return new Compartment(options); } factory.getReaction = function(options){ return new Reaction(options); } factory.getEdge = function(source,target,role,options){ return new Edge(source,target,role,options); } return factory; }
import React from 'react' import { HashRouter as Router, Switch, Route, Redirect, Link } from 'react-router-dom'; import Counter from '../components/Counter'; import { Login } from '../components/Login'; import Navbar from '../components/Navbar'; const AppRouters = () => { return ( <Router> <div> <Navbar /> <div className="container"> <Switch> <Route exact path="/" component={Counter} /> <Route exact path="/login" component={Login} /> <Redirect to="/" /> </Switch> </div> </div> </Router> ) } export default AppRouters
// Support for plotting non-standard functions // Written by Jieun Chon, Cliff Shaffer, and Ville Karavirta (function() { "use strict"; var Plot = { // Create and return a set of points used to draw a dashed line. // func: The function for the line being drawn drawDash: function(func, xStart, yStart, xEnd, xMax, yMax, height) { var points = [xStart, yStart, xEnd]; var y = yStart - func(xMax) * height / yMax; points.push(y); return points; }, // Create and return a set of points used to draw an arbitary function // func: The function being drawn, it is used to generate the y values // xStart: The x coordinate of the starting point of the function // yStart: The y coordinate of the starting point of the function // yEnd: The y coordinate of the ending point of the function // xMax: maximum number of steps in the x direction // yMax: maximum number of steps in the y direction // width: number of pixels in the width of the function // height: number of pixels in the height of the function // increment: Something to do with how big a step to take, to avoid jaggies // isLog: if true start at 1, if false start at 0 // TODO: We should automate the incrementing process! drawCurve: function(func, xStart, yStart, yEnd, xMax, yMax, width, height, increment, isLog) { var points = []; var xStep = width / xMax; var start = isLog ? 1 : 0; var x, y; for (var i = start; i <= xMax; i += increment) { x = xStart + (i * xStep); y = yStart - ((func(i) / yMax) * height); if (y < yEnd) { y = yEnd; points.push([x, y]); break; } points.push([x, y]); } return points; } }; // Plot window.Plot = window.Plot || Plot; }());
var texture = THREE.ImageUtils.loadTexture('../assets/smb3.png',THREE.UVMapping, function() { //var texture = THREE.ImageUtils.loadTexture('../assets/contra.png', THREE.UVMapping, function () { gpu.init(256, 240); // 60 fps requestAnimationFrame(function () { gpu.render(texture); }); });
"use strict"; function diamond(n) { for (let index = 1; index <= n; index += 2) { let stars = '*'.repeat(index); let margin = ' '.repeat((n - index) / 2); console.log(margin + stars); } for (let index = n - 2; index >= 1; index -= 2) { let stars = '*'.repeat(index); let margin = ' '.repeat((n - index) / 2); console.log(margin + stars); } } diamond(1); diamond(3); diamond(9); diamond(23);
import React from "react"; import { Star, StarBorder } from "@material-ui/icons"; import { withAuth } from "../../../hoc/withAuth"; function FavoriteIcon({ auth: { favorites }, authActions: { toggleFavoriteMovies }, id, }) { let isFavorite = false; if (favorites.length > 0) { let favoriteIDs = favorites.map((el) => el.id); isFavorite = favoriteIDs.includes(id) ? true : false; } return ( <> {isFavorite ? ( <Star onClick={() => toggleFavoriteMovies(id)} /> ) : ( <StarBorder onClick={() => toggleFavoriteMovies(id)} /> )} </> ); } export default withAuth(FavoriteIcon);
import React, { useState } from 'react' import Aux from '../aux/Aux' import classes from './Layout.css' import Toolbar from '../../components/navigation/toolbar/Toolbar' import SideDrawer from '../../components/navigation/SideDrawer/SideDrawer' const Layout = (props) => { const [show, setShow] = useState(false) const sideDrawerClosedHandler = () => { setShow(false) } const toggleDrawerHandler = () => { setShow(!show) } return ( <Aux> <Toolbar toggle={toggleDrawerHandler} /> <SideDrawer open={show} closed={sideDrawerClosedHandler} /> <main className={classes.content}> {props.children} </main> </Aux> ) } export default Layout
export { default as Internal } from './internal' export { default as requireText } from './requireText' // Useful for nested strings that should be evaluated export const escape = (str, quote) => { str = str.replace(/\\/g, '\\\\') switch (quote) { case "'": return str.replace(/'/g, "\\'") case '"': return str.replace(/"/g, '\\"') case '`': return str.replace(/`/g, '\\`') default: return str .replace(/'/g, "\\'") .replace(/"/g, '\\"') .replace(/`/g, '\\`') } } export const importantizeCSS = (css) => { return css.replace(/(!important)?;/gi, ' !important;'); } // Encapsulates all rules under .af-view export const encapsulateCSS = (css, source) => { return css.replace( /((?:^|\{|\}|;)\s*(?:\/\*[^]*?\*\/\s*)*)([^@{}]+?)(\s*\{)/g, ( match, left, rule, right ) => { // Animation keyframe e.g. 50% if (/^\d/.test(rule)) return match // Empty line skip, probably after a media query or so if (!rule.trim()) return match // Apply for all selectors in rule // Note that <html /> and <body /> tags are replaced with .af-view rule = rule .replace(/\.(af-class-)?([\w_-]+)/g, '.af-class-$2') rule = rule .replace(/\[class(.?)="( ?)([^"]+)( ?)"\]/g, '[class$1="$2af-class-$3$4"]') rule = rule .replace(/([^\s][^,]*)(\s*,?)/g, '.af-view $1$2') rule = rule .replace(/\.af-view html/g, '.af-view') rule = rule .replace(/\.af-view body/g, '.af-view') rule = rule .replace('.af-view .af-class-af-view', '') switch (source) { case 'webflow': rule = rule .replace(/af-class-w-/g, 'w-') break case 'sketch': rule = rule .replace(/af-class-anima-/g, 'anima-') .replace(/af-class-([\w_-]+)an-animation([\w_-]+)/g, '$1an-animation$2') break default: rule = rule .replace(/af-class-w-/g, 'w-') .replace(/af-class-anima-/g, 'anima-') .replace(/af-class-([\w_-]+)an-animation([\w_-]+)/g, '$1an-animation$2') } return `${left}${rule}${right}` }) } // Will use the shortest indention as an axis export const freeText = (text) => { if (text instanceof Array) { text = text.join('') } // This will allow inline text generation with external functions, same as ctrl+shift+c // As long as we surround the inline text with ==>text<== text = text.replace( /( *)==>((?:.|\n)*?)<==/g, (match, baseIndent, content) => { return content .split('\n') .map(line => `${baseIndent}${line}`) .join('\n') }) const lines = text.split('\n') const minIndent = lines.filter(line => line.trim()).reduce((minIndent, line) => { const currIndent = line.match(/^ */)[0].length return currIndent < minIndent ? currIndent : minIndent }, Infinity) return lines .map(line => line.slice(minIndent)) .join('\n') .trim() .replace(/\n +\n/g, '\n\n') } // Calls freeText() and disables lint export const freeLint = (script) => { return freeText(` /* eslint-disable */ ==>${freeText(script)}<== /* eslint-enable */ `) } // Calls freeLint() and ensures that 'this' is represented by window export const freeContext = (script) => { return freeLint(` (function() { ==>${freeText(script)}<== }).call(window) `) } // Creates a completely isolated scope with Function constructor. // args is a varToInject-injectedVarName map. export const freeScope = (script, context = 'window', args = {}) => { const callArgs = [context].concat(Object.keys(args)) return freeText(` new Function(\` with (this) { ${script} } \`).call(${callArgs.join(', ')}) `) } // upper -> Upper export const upperFirst = (str) => { return str.substr(0, 1).toUpperCase() + str.substr(1) } // foo_barBaz -> ['foo', 'bar', 'Baz'] export const splitWords = (str) => { return str .replace(/[A-Z]/, ' $&') .split(/[^a-zA-Z0-9]+/) .filter(word => word.trim()) } // abc 5 0 -> 00abc export const padLeft = (str, length, char = ' ') => { str = String(str) length = parseInt(length + 1 - str.length) return Array(length).join(char) + str }
const { GraphQLString, GraphQLObjectType } = require('graphql') const TimestampType = require('./timestamp.type') const MessageType = new GraphQLObjectType({ name: 'Message', description: 'SMS Message', fields: () => { return { id: { type: GraphQLString, description: 'The identifier of message' }, __typename: { type: GraphQLString, description: 'Type of record', resolve: () => 'Message' }, recipient: { type: GraphQLString, description: 'The agent of message' }, originator: { type: GraphQLString, description: 'The case of message' }, body: { type: GraphQLString, description: 'The Channel Account identifier' }, created: { type: TimestampType, description: 'The timestamp of created at date' }, sended: { type: TimestampType, description: 'The timestamp of published date' } } } }) module.exports = MessageType
TQ.bayonetList = function (dfop){ function bayonetOperatorFormatter(el,options,rowData){ return (dfop.hasUpdateBayonet == 'true' ? "<a href='javascript:bayonetUpdateOperator("+rowData.id+")'><span>修改</span></a> "+ "&nbsp;|&nbsp;" : '' )+ (dfop.hasDeleteBayonet == 'true' ? "<a href='javascript:bayonetDeleteOperator("+rowData.id+")'><span>删除</span></a>" : ''); } $(document).ready(function(){ loadList(); if(dfop.useOrgDepartmentNo.indexOf("511622") == 0){ gisType = "3D"; } function loadList(){ // 生成列表 $("#bayonetList").jqGridFunction({ mtype:'post', datatype: "local", colModel:[ {name:"id",index:'id',hidden:true}, {name:"encryptId",index:'id',frozen:true,hidden:true}, {name:"operator", index:'id',label:'操作',formatter:bayonetOperatorFormatter,width:100,frozen:true,sortable:false,align:'center' }, {name:'bayonetNo', index:'code',label:'编号', width:150, sortable:true, align:'center', hidden:false,formatter:bayonetNameFormatter}, {name:'organization.orgName',index:'orgId',label:'所属区域', width:360,hidden:false,sortable:true}, {name:'address', index:'address',label:'地址', width:400, sortable:true, align:'center', hidden:false}, {name:'createUser', index:'createUser',label:'创建人', width:100, sortable:true, align:'center', hidden:true}, {name:'updateUser', index:'updateUser',label:'修改人', width:100, sortable:true, align:'center', hidden:true}, {name:'createDate', index:'createDate',label:'创建时间', width:100, sortable:true, align:'center', hidden:true}, {name:'updateDate', index:'updateDate',label:'修改时间', width:100, sortable:true, align:'center', hidden:true}, {name:"isEmphasis",label:"是否关注",hidden:true,hidedlg:true,width:100}, {name:'isBind',index:'isBind',label:'绑定地图',sortable:false,width:120,align:"center"}, {name:'openLayersMapInfo.centerLon',sortable:false,index:'openLayersMapInfo.centerLon',label:'卡口中心坐标X',width:120,hidden:true}, {name:'openLayersMapInfo.centerLat',sortable:false,index:'openLayersMapInfo.centerLat',label:'卡口中心坐标Y',width:120,hidden:true}, {name:'openLayersMapInfo.centerLon2',sortable:false,index:'openLayersMapInfo.centerLon2',label:'卡口中心2D坐标X',width:120,hidden:true}, {name:'openLayersMapInfo.centerLat2',sortable:false,index:'openLayersMapInfo.centerLat2',label:'卡口中心2D坐标Y',width:120,hidden:true} ], gridComplete:function(){ var ids=jQuery("#bayonetList").jqGrid('getDataIDs'); for(var i=0; i<ids.length; i++){ var id=ids[i]; var isBind = $("#bayonetList").getCell(id,"isBind"); var lon="" var lat=""; if(gisType=="2D"){ lon = $("#bayonetList").getCell(id,"openLayersMapInfo.centerLon2"); lat = $("#bayonetList").getCell(id,"openLayersMapInfo.centerLat2"); }else if(gisType=="3D"){ lon = $("#bayonetList").getCell(id,"openLayersMapInfo.centerLon"); lat = $("#bayonetList").getCell(id,"openLayersMapInfo.centerLat"); } if(lon!="" && lon!=null && lat!="" && lat!=null){ modify = "<a href='javascript:viewBindMap("+lon+","+lat+")' style='color:#f60; text-decoration: underline;' >查看地图</a>";//查看 }else{ modify="未绑定"; } jQuery("#bayonetList").jqGrid('setRowData', ids[i], { isBind: modify}); } }, multiselect:true, onSelectAll:function(data){ toggleButtonState(data); }, loadComplete: function(data){ afterLoad(data); }, ondblClickRow:function (rowid){ if(dfop.hasViewBayonet=='true'){ viewBayonet(rowid); } }, onSelectRow: function(data){ toggleButtonState(data); } }); if(getCurrentOrgId()!="" && getCurrentOrgId()!=null){ onOrgChanged(getCurrentOrgId(),isGrid()); } } jQuery("#bayonetList").jqGrid('setFrozenColumns'); $("#fastSearchButton").click(function(){ search(getCurrentOrgId()); }); $("#searchText").focus(function(){ this.select(); }); $("#refreshSearchKey").click(function(){ $("#searchText").attr("value","请输入卡口编号"); }); $("#add").click(function(){ if (!isGrid()){ $.messageBox({level:'warn',message:"请先选择网格级别组织机构进行新增!"}); return; } $("#bayonetDialog").createDialog({ model :"add", title:"新增卡口信息", width: dialogWidth, height: dialogHeight, url:PATH+'/bayonetManage/dispatch.action?mode=add&organization.id='+getCurrentOrgId()+"&gisType="+gisType, buttons: { "保存" : function(){ $("#maintainForm").submit(); }, "关闭" : function(){ $(this).dialog("close"); } } }); }); $("#update").click(function(){ var selectedIds = $("#bayonetList").jqGrid("getGridParam", "selarrrow"); if(selectedIds==null || selectedIds.length>1){return;} var selectedId = getSelectedIdLast(); if(selectedId==null){ return; } bayonetUpdateOperator(selectedId); }); $("#delete").click(function(){ var allValue = getSelectedIds(); if(allValue.length ==0){ $.messageBox({level:'warn',message:"请选择一条或多条记录,再进行删除!"}); return; } bayonetDeleteOperator(allValue); }); $("#view").click(function(){ if($("#view").attr("disabled")){ return ; } var selectedId = getSelectedIdLast(); if(selectedId==null){ return; } viewBayonet(selectedId); }); $("#reload").click(function(){ if(getCurrentOrgId()!="" && getCurrentOrgId()!=null){ onOrgChanged(getCurrentOrgId(),isGrid()); } }); $("#search").click(function(event){ $("#bayonetDialog").createDialog({ width:650, height:320, title:'卡口查询-请输入查询条件', url:PATH+'/digitalCity/publicSecurity/bayonetManagement/searchBayonetDlg.jsp?orgId=' + getCurrentOrgId(), buttons: { "查询" : function(event){ searchBayonet(); $(this).dialog("close"); }, "关闭" : function(){ $(this).dialog("close"); } } }); }); $("#cancelEmphasise").click(function(event){ if($(this).attr("disabled")=="disabled"){ return; } var selectedId =getSelectedIds(); var cancelEmphasise=new Array(); var temp=new Array(); if(selectedId == null || selectedId.length<=0){ $.messageBox({level:'warn',message:"请选择一条或多条记录,再进行取消关注!"}); return; } for(var i=0;i<selectedId.length;i++){ var rowData = $("#bayonetList").getRowData(selectedId[i]); if(rowData.isEmphasis==false || rowData.isEmphasis=="false"){ cancelEmphasise.push(selectedId[i]); }else{ temp.push(selectedId[i]); } } selectedId=cancelEmphasise; if(selectedId==null||selectedId.length==0){ $.messageBox({level:'warn',message:"没有可取消关注的数据!"}); return; } var encryptIds=deleteOperatorByEncrypt("bayonet",selectedId,"encryptId"); $("#bayonetDialog").createDialog({ width:450, height:210, title:'取消关注提示', modal:true, url:PATH+'/digitalCity/publicSecurity/emphasiseConditionDlg.jsp?publicSecurityType='+dfop.publicSecurityType+'&locationIds='+encryptIds+'&isEmphasis=true&dailogName=bayonet&temp='+temp, buttons: { "保存" : function(event){ $("#emphasisForm").submit(); }, "关闭" : function(){ $(this).dialog("close"); } } }); }); $("#reEmphasise").click(function(){ if($(this).attr("disabled")=="disabled"){ return; } var selectedId = getSelectedIds(); var reEmphasise=new Array(); var temp=new Array(); if(selectedId == null || selectedId.length<=0){ $.messageBox({level:'warn',message:"请选择一条或多条记录,再重新关注!"}); return; } for(var i=0;i<selectedId.length;i++){ var rowData = $("#bayonetList").getRowData(selectedId[i]); if(rowData.isEmphasis==true||rowData.isEmphasis=="true"){ reEmphasise.push(selectedId[i]); }else{ temp.push(selectedId[i]); } } selectedId=reEmphasise; if(selectedId==null||selectedId.length==0){ $.messageBox({level:'warn',message:"没有可重新关注的数据!"}); return; } var encryptIds=deleteOperatorByEncrypt("bayonet",selectedId,"encryptId"); $.ajax({ url:PATH+"/bayonetManage/updateEmphasiseByEncryptId.action", data:{ "ids": encryptIds, "bayonet.isEmphasis":0 }, success:function(responseData){ if(null==temp || temp.length==0){ $.messageBox({message:" "+dfop.moduleCName+"重新关注成功 ! "}); }else{ $.messageBox({level:'warn',message:"除选中的红色数据外,其余"+dfop.moduleCName+"重新关注成功 ! "}); } notExecute=temp; $("#bayonetList").trigger("reloadGrid"); } }); }); $("#transfer").click(function(e){ if(isTownOrganization()){ $.messageBox({level:'warn',message:"请先选择乡镇(街道)级别组织机构进行转移!"}); return; } var allValue = $("#bayonetList").jqGrid("getGridParam", "selarrrow"); if(allValue.length ==0){ $.messageBox({level:'warn',message:"请选择一条或多条记录,再进行转移!"}); return; } for(var i=0;i<allValue.length;i++){ var rowData=$("#bayonetList").getRowData(allValue[i]); if(rowData.isBind!="未绑定"){ $.messageBox({level:'warn',message:"所选记录已绑定地图,无法转移!"}); return; } if(rowData.isEmphasis==true || rowData.isEmphasis=="true"){ $.messageBox({level:'warn',message:"所选记录是已注销记录,无法转移!"}); return; } } var orgid= getCurrentOrgId(); if(orgid==""||orgid==null){ $.messageBox({level:'warn',message:"没有获取到当前的组织机构id"}); return; } $.confirm({ title:"转移卡口", message:"转移卡口时,若目标网格存在相同数据,该数据不进行转移。", okFunc: function() { moveOperator(e,allValue,orgid); } }); }); function moveOperator(event,allValue,orgid){ var encryptIds=deleteOperatorByEncrypt("bayonet",allValue,"encryptId"); $("#moveDataDialog").createDialog({ width: 400, height: 230, title:"数据转移", url:PATH+"/publicSecurity/transferManage/transferDispatchByEncrypt.action?orgId="+orgid+"&ids="+encryptIds+"&type=bayonet", buttons: { "保存" : function(event){ $("#maintainShiftForm").submit(); }, "关闭" : function(){ $(this).dialog("close"); } } }); var evt = event || window.event; if (window.event) { evt.cancelBubble=true; } else { evt.stopPropagation(); } } function parseObj(strData) { return (new Function("return " + strData))(); } function searchBayonet(){ var formdata = $("#searchBayonetForm").serialize(); if (formdata != '') { formdata = formdata.replace(/\+/g," "); formdata = formdata.replace(/=/g, '":"'); formdata = formdata.replace(/&/g, '","'); formdata += '"'; } formdata = decodeURIComponent('{"' + formdata + '}'); $("#bayonetList").setGridParam({ url:PATH+'/bayonetManage/findBayonetPagerBySearchVo.action', datatype: "json", page:1, mtype:"post" }); $("#bayonetList").setPostData(parseObj(formdata)); $("#bayonetList").trigger("reloadGrid"); } function search(orgId){ var fastSearchVal = $("#searchText").val(); if(fastSearchVal == '请输入卡口编号' || fastSearchVal==''){ onOrgChanged(getCurrentOrgId(),isGrid()); return; } var postData = { "organization.id":orgId, "searchBayonetVo.bayonetNo":fastSearchVal } $("#bayonetList").setGridParam({ url:PATH+'/bayonetManage/findBayonetPagerBySearchVo.action', datatype: "json", page:1 }); $("#bayonetList").setPostData(postData); $("#bayonetList").trigger("reloadGrid"); } function getSelectedIdLast(){ var selectedId; var selectedIds = $("#bayonetList").jqGrid("getGridParam", "selarrrow"); for(var i=0;i<selectedIds.length;i++){ selectedId = selectedIds[i]; } return selectedId; } function getSelectedIds(){ var selectedIds = $("#bayonetList").jqGrid("getGridParam", "selarrrow"); return selectedIds; } function isTownOrganization(){ return $("#currentOrgId").attr("orgLevelInternalId") > dfop.townOrganization; } }); } function bayonetUpdateOperator(selectedId){ var ent = $("#bayonetList").getRowData(selectedId); if(ent.isEmphasis==true || ent.isEmphasis=="true"){ $.messageBox({level : 'warn',message:"该卡口信息已经注销,不能修改!"}); return; } var encryptId=ent.encryptId; $("#bayonetDialog").createDialog({ model :"edit", title:"修改卡口信息", width: dialogWidth, height: dialogHeight, url:PATH+'/bayonetManage/dispatchByEncrypt.action?mode=edit&bayonet.id='+encryptId+"&gisType="+gisType, buttons: { "保存" : function(){ $("#maintainForm").submit(); }, "关闭" : function(){ $(this).dialog("close"); } } }); } function bayonetDeleteOperator(allValue){ var id=deleteOperatorByEncrypt("bayonet",allValue,"encryptId"); $.confirm({ title:"确认删除", message:"确定要删除吗?一经删除将无法恢复", okFunc: function() { $.ajax({ url:PATH+'/bayonetManage/deleteBayonetByIds.action', type:"post", data:{ "ids":id }, success:function(data){ $.messageBox({message:"已经成功删除该卡口信息!"}); $("#bayonetList").trigger("reloadGrid"); } }); } }); } function toggleButtonState(){ var selectedIds=$("#bayonetList").jqGrid("getGridParam", "selarrrow"); var selectedRowCount=selectedIds.length; } function afterLoad(){ } function viewBindMap(lon,lat){ $("#gisbayonetDialog").createDialog({ zIndex:1020, width: 800, height: 600, title:'查看建筑物', url:PATH+"/openLayersMap/product_3.0/gisPublicSecurity.jsp?flag=3&dailogName=bayonet&organizationId="+getCurrentOrgId()+"&viewLon="+lon+"&viewLat="+lat+"&gisType="+gisType, buttons: { "关闭" : function(){ $("#bayonetList").trigger("reloadGrid"); $(this).dialog("close"); } }, shouldEmptyHtml:false }); } function bayonetNameFormatter(el,options,rowData){ if(null == rowData.bayonetNo) { return "&nbsp;&nbsp;" }else if(rowData.isEmphasis==1){ return "<a href='javascript:viewBayonet("+rowData.id+")'><font color='#778899'>"+rowData.bayonetNo+"</font></a>"; } return "<a href='javascript:viewBayonet("+rowData.id+")'><font color='#6633FF'>"+rowData.bayonetNo+"</font></a>"; }
module.exports = { // test: { // bind (el, binding, vnode, oldVnode) { // }, // inserted (el, binding, vnode, oldVnode) { // }, // update (el, binding, vnode, oldVnode) { // }, // componentUpdated (el, binding, vnode, oldVnode) { // }, // unbind (el, binding, vnode, oldVnode) { // }, // } };
import React from 'react'; import './Player.css'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faPlusSquare } from '@fortawesome/free-solid-svg-icons' import 'bootstrap/dist/css/bootstrap.min.css'; const Player = (props) => { const { name, salary, country, image } = props.player; return ( <div className="player"> <div className="card-setup"> <img className="image-setup" src={image} alt="" /> </div> <div> <h4>{name}</h4> <p>Country : {country}</p> <p>Salary :${salary}</p> <button className="btn btn-success" onClick={() =>props.handleClick(props.player)}> <FontAwesomeIcon icon={faPlusSquare} /> Add to List</button> </div> </div> ); }; export default Player;
module.exports = function () { // determine user id var id = require('cookie').parse(document.cookie)['user-id']; console.info("User ID:", id); _.model.UserId.set(id); }
import React, { Component } from 'react'; import queryString from 'query-string'; import fetchJsonp from 'fetch-jsonp'; import search from './img/search.svg'; export default class Search extends Component { static defaultProps = { meetup: '', coords: { latitude: 40.7259114, longitude: -73.99591649999999 }, handleSearchSuccess: function() {} }; state = { meetup: this.props.meetup }; handleSubmit = (e) => { e.preventDefault(); this.fetchEvents() .then(response => response.json()) .then(({ data }) => this.props.handleSearchSuccess(data) ); } handleInputChange = (e) => { this.setState({ meetup: e.target.value }); } fetchEvents() { const ENDPOINT = 'https://api.meetup.com/find/events/'; const { token, coords } = this.props; const { meetup } = this.state; const params = queryString.stringify({ only: [ 'name', 'group', 'link', 'time', 'yes_rsvp_count', 'venue', 'rsvp_sample' ].join(','), access_token: token, text: meetup, lat: coords.latitude, lon: coords.longitude, fields: [ 'group_key_photo', 'group_photo_gradient', 'rsvp_sample' ].join(',') }); return fetchJsonp(`${ENDPOINT}?${params}`, { method: 'GET', credentials: 'include' }); } render() { return ( <form onSubmit={this.handleSubmit}> <div className="row"> <div className='row-item'> <input id="meetup" name='meetup' placeholder="Search for Meetups" className="form-control" type="text" value={this.state.meetup} onChange={this.handleInputChange} /> </div> <div className='row-item row-item--shrink'> <button type='submit' className='button button--primary button-override'> <img src={search} width={20} alt='search' /> </button> </div> </div> </form> ); } }
define(["DataURL"],function (DataURL){ var Contents={ convert: function (src, destType, options) { // options:{encoding: , contentType: } // src: String|DataURL|ArrayBuffer|OutputStream|Writer // destType: String|DataURL|ArrayBuffer|InputStream|Reader var srcType; if (typeof src=="string") srcType=String; if (src instanceof DataURL) srcType=DataURL; if (src instanceof ArrayBuffer) srcType=ArrayBuffer; if (srcType==destType) return src; throw new Error("Cannot convert from "+srcType+" to "+destType); } }; return Contents; });
define(['jquery', 'QDP'], function ($, QDP) { "use strict"; let isFullScreen = false; /** 当前登录状态是否超时 */ let isLoginTimeout = false; var fullScreen = () => { var docElm = document.documentElement; //W3C if (docElm.requestFullscreen) { isFullScreen = true; docElm.requestFullscreen(); } //FireFox else if (docElm.mozRequestFullScreen) { isFullScreen = true; docElm.mozRequestFullScreen(); } //Chrome等 else if (docElm.webkitRequestFullScreen) { isFullScreen = true; docElm.webkitRequestFullScreen(); } //IE11 else if (docElm.msRequestFullscreen) { isFullScreen = true; docElm.msRequestFullscreen(); } } var exitFullScreen = () => { if (document.exitFullscreen) { isFullScreen = false; document.exitFullscreen(); } else if (document.mozCancelFullScreen) { isFullScreen = false; document.mozCancelFullScreen(); } else if (document.webkitCancelFullScreen) { isFullScreen = false; document.webkitCancelFullScreen(); } else if (document.msExitFullscreen) { isFullScreen = false; document.msExitFullscreen(); } } /** 导航至系统主界面 */ var gotoMain = function () { // EVENT-RAISE:layout.logined 用户登录后触发,{cfgs.INFO} QDP.raise("layout.logined", QDP.config.INFO); $("body").removeClass("login"); $('body>section').empty(); $('body>section').height($(document).height()); // 加载导航页面 QDP.block.show("初始化导航", $("body>aside")); $("body>aside").load(QDP.config.navpage, function () { QDP.block.close($("body>aside")); QDP.layout.initMenu(); QDP.layout.resizeScroller(); }); // 加载主页面 QDP.block.show("初始化页面", $("body>section")); $("body>section").load(QDP.config.mainpage, function () { QDP.block.close($("body>section")); $(".username").text(QDP.config.INFO.name); $(".userrole").text(QDP.config.INFO.rolename); QDP.layout.resizeContentScroller(); }); }; /** 导航至登录界面 */ var gotoLogin = function () { QDP.cookie.save(""); $("body").addClass("login"); $("body>section").removeAttr("style"); $("body>aside").removeAttr("style"); $("body>aside").empty(); var loginPageLoadCallback = function () { $(".btn-login").on("click", function () { var username = $("#username").val(); var password = $("#password").val(); if (!username || username == "") { QDP.alert("账号不能为空!"); return; } if (!password || password == "") { QDP.alert("密码不能为空!"); return; } var options = { u: QDP.base64.encode(username), p: QDP.base64.encode(password) }; QDP.post(QDP.api.login.loginapi, options, function (json) { QDP.cookie.save(json); gotoMain(); }); }); }; $("body>section").load(QDP.config.loginpage, loginPageLoadCallback); }; // EVENT-ON:layout.initialize QDP.on("layout.initialize", function () { // console.time(times.initialize); if (!(QDP.config.INFO = QDP.cookie.read())) { console.info("TOKEN验证失败,重新登录"); gotoLogin(); /*不存在token或token失效,需重新登录*/ } else { console.info("TOKEN验证成功,进入系统"); gotoMain(); /*token有效,可正常使用系统*/ } }); // EVENT-ON:layout.started QDP.on("layout.started", function () { console.info("注册->系统运行后自动注册 - plugins-events"); // 注册导航栏收起/展开开关点击事件 $('body').on("click", ".sidebar-collapse", function () { if ($("body").hasClass("mini-menu")) { $("body").removeClass("mini-menu"); // EVENT-ON:siderbar.collapse 导航栏折叠后触发 QDP.raise('sidebar.collapse'); } else { $("body").addClass("mini-menu"); // EVENT-ON:siderbar.expand 导航栏展开后触发 QDP.raise('sidebar.expand'); } // 延迟触发 // EVENT-ON:siderbar.changed 导航栏折叠\展开状态切换后触发 setTimeout(function () { QDP.raise('sidebar.changed'); }, 300); }); // 处理全屏展示功能 $('body').on('click', '.sys-fullscreen', function () { isFullScreen = !isFullScreen; if (isFullScreen) { fullScreen(); } else { exitFullScreen(); } }); // 修改密码功能 $('body').on("click", '.sys-chgpwd', function () { QDP.form.openWidow({ 'title': "修改密码", 'width': '400px', 'height': '230px', 'url': QDP.api.login.changepwdpage, 'onshow': function (parent) { $('form', parent).bootstrapValidator({ feedbackIcons: {/*输入框不同状态,显示图片的样式*/ valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, fields: {/*验证*/ oldpwd: { validators: { notEmpty: { message: '原始密码不能为空' } } }, newpwd: { validators: { notEmpty: { message: '新密码不能为空' }, stringLength: { min: 6, max: 30, message: '密码长度必须在6到30之间' }, identical: {//相同 field: 'newpwd2', //需要进行比较的input name值 message: '两次密码不一致' }, // different: {//不能和用户名相同 // field: 'username',//需要进行比较的input name值 // message: '不能和用户名相同' // }, regexp: { regexp: /^[a-zA-Z0-9_\.]+$/, message: '密码需由字母、数字、下划线组成' } } }, newpwd2: { validators: { notEmpty: { message: '确认密码不能为空' }, identical: {//相同 field: 'newpwd', message: '两次密码不一致' }, // different: {//不能和用户名相同 // field: 'username', // message: '不能和用户名相同' // }, regexp: { regexp: /^[a-zA-Z0-9_\.]+$/, message: '密码需由字母、数字、下划线组成' } } } } }); // 处理确定按钮事件 $(".btn-save").on("click", function (e) { e.preventDefault(); var validator = $('form', parent).data("bootstrapValidator"); validator.validate(); if (validator.isValid()) { var options = { "oldpwd": $("#oldpwd", parent).val(), "newpwd": $("#newpwd", parent).val(), "newpwd2": $("#newpwd2", parent).val() }; QDP.post(QDP.api.login.changepwdapi, options, function () { parent.modal('hide'); }); } }); } }); }); // 修改个人信息 $('body').on("click", 'aside>header', function () { QDP.form.openWidow({ 'title': "修改个人信息", 'width': '400px', 'height': '260px', 'url': QDP.api.login.changeinfopage, 'onshow': function (parent) { $('form', parent).bootstrapValidator({ feedbackIcons: {/*输入框不同状态,显示图片的样式*/ valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, fields: {/*验证*/ nickname: { validators: { notEmpty: { message: '昵称不能为空' }, stringLength: { min: 6, max: 30, message: '昵称长度必须在6到30之间' } } }, phone: { validators: { notEmpty: { message: '手机号码不能为空' }, stringLength: { min: 11, max: 11, message: '请输入11位手机号码' }, regexp: { regexp: /^1[3|5|8]{1}[0-9]{9}$/, message: '请输入正确的手机号码' } } }, email: { validators: { notEmpty: { message: '邮箱不能为空' }, emailAddress: { message: '请输入正确的邮箱地址' } } } } }); // 处理确定按钮事件 $(".btn-save").on("click", function (e) { e.preventDefault(); var validator = $('form', parent).data("bootstrapValidator"); validator.validate(); if (validator.isValid()) { var options = { "nickname": $("#nickname", parent).val(), "phone": $("#phone", parent).val(), "email": $("#email", parent).val() }; QDP.post(QDP.api.login.changepwdapi, options, function () { parent.modal('hide'); }); } }); } }); }); /** 刷新功能 */ $('body').on('click', '.btn-refresh', function () { QDP.table.reload(); }); /** 导出功能 */ $('body').on('click', '.btn-export', function () { QDP.table.export(); }); /* 处理【取消/返回】按钮事件 */ $('body').on('click', '.btn-back', function (e) { e.preventDefault(); if ($(this).hasClass("custom") == false) { QDP.layout.back(); } }); // 全选按钮点击事件处理函数 $('body').on('click', '.btn-selectall', function () { var trs = $('.qdp-table>tbody>tr[data-id]'); trs.each(function (index) { if (!$(this).hasClass('selected')) { $(this).addClass('selected'); } if (trs.length - 1 == index) { refreshButtonStatus(); } }); }); // 反选按钮点击事件处理函数 $('body').on('click', '.btn-selectopp', function () { var trs = $('.qdp-table>tbody>tr[data-id]'); trs.each(function (index) { if ($(this).hasClass('selected')) { $(this).removeClass('selected'); } else { $(this).addClass('selected'); } if (trs.length - 1 == index) { refreshButtonStatus(); } }); }); $('body').on('click', ".qdp-table", function (e) { try { if (e.target.localName == 'td') { var tr = $(e.target).parent(); if (tr.data('id') == undefined) { return; } if (tr.hasClass('selected')) { tr.removeClass('selected'); } else { tr.addClass('selected'); } } else if ($(e.target).parent()[0].localName == 'td') { var tr = $(e.target).parent().parent(); if (tr.data('id') == undefined) { return; } if (tr.hasClass('selected')) { tr.removeClass('selected'); } else { tr.addClass('selected'); } } refreshButtonStatus(); } catch (e) { } // console.log(e); }); /* 注册按钮事件 */ $('body').on('click', '.sys-logout', function () { QDP.post(QDP.api.login.logoutapi, {}, function () { gotoLogin(); }); }); var refreshButtonStatus = function () { var selector = $('table>tbody>tr[class*="selected"]'); if (selector.length == 1) { $(".btn-edit").removeAttr('disabled'); $(".btn-preview").removeAttr('disabled'); $(".btn-remove").removeAttr('disabled'); } else if (selector.length == 0) { $(".btn-edit").attr('disabled', "true"); $(".btn-preview").attr('disabled', "true"); $(".btn-remove").attr('disabled', "true"); } else { $(".btn-remove").removeAttr('disabled'); $(".btn-preview").attr('disabled', "true"); $(".btn-edit").attr('disabled', "true"); } // EVENT-RAISE:table.selected table选中行后触发 {selector,length} QDP.raise('table.selected', { "selector": selector, "length": selector.length }); } }); // EVENT-ON:layout.logined 当用户登录后触发:用于处理登录超时后弹出多个对话框 QDP.on("layout.logined", function () { isLoginTimeout = false; }); // EVENT-ON:login.timeout 当用户session过期时出发,进入用户登录界面 QDP.on("login.timeout", function () { // 解决登录超时后弹出多个对话框 if (isLoginTimeout) { return; } isLoginTimeout = true; QDP.alert("登录超时,请重新登录", function () { gotoLogin(); }); }); });
//const { SlashCommand } = require("gcommands") module.exports = { name: "test", aliases: ["ccc"], description: "Test", //expectedArgs: '<enable:6:description> <test>', /*expectedArgs: [ { name: "list", type: 3,//SlashCommand.STRING, description: "helllo", required: true, choices: [ { name: "Hyro Dog", value: "dogik" }, { name: "Pancucha", value: "pancier" } ] }, { name: "user", type: 6,//SlashCommand.USER, description: "select user", required: false } ],*/ /*expectedArgs: [ { name: "user", description: "Get or edit permissions for a user", type: 2, // 2 is type SUB_COMMAND_GROUP options: [ { name: "get", description: "Get permissions for a user", type: 1, // 1 is type SUB_COMMAND options: [ { name: "user", description: "The user to get", type: 6, required: true } ] }, { name: "edit", description: "Edit permissions for a user", type: 1 } ] }, { name: "role", description: "Get or edit permissions for a role", type: 2, options: [ { name: "get", description: "Get permissions for a role", type: 1 }, { name: "edit", description: "Edit permissions for a role", type: 1 } ] } ],*/ minArgs: 1, cooldown: 3, guildOnly: "747526604116459691", //["id","id2"] //userOnly: "id", //["id","id2"] //channelOnly: "id", //["id","id2"] userRequiredPermissions: ["ADMINISTRATOR","MANAGE_GUILD"], clientRequiredPermissions: ["ADMINISTRATOR"], usage: "usage lol", //requiredRole: "ROLE ID", //slash: false, run: async(client, slash, message, args) => { console.log(args) if(message) { console.log(await message.guild.commandPrefix()) if(args[0]) { return message.channel.send("My ping is `" + Math.round(client.ws.ping) + "ms`") } else { return message.inlineReply("Need args") } return; } return { content: "My ping is `" + Math.round(client.ws.ping) + "ms`", ephemeral: true, allowedMentions: { parse: [], repliedUser: true } } /* CAN USE return "My ping is `" + Math.round(client.ws.ping) + "ms`" */ } };
const chai=require('chai'); const chaiHttp=require('chai-http'); const should=chai.should(); const server=require('../app'); chai.use(chaiHttp); let token,directorId; describe('api/directory tests',()=>{ before((done)=>{ chai.request(server) .post('/authenticate') .send({username:'metin123',password:'123456'}) .end((err,res)=>{ token=res.body.token; done(); }) }); describe('/GET directors',()=>{ it('it should all the directors',(done)=>{ chai.request(server) .get('/api/directors') .set('x-access-token',token) .end((err,res)=>{ res.should.status(200); res.body.should.be.a('array'); done(); }); }); }); describe('/POST director',()=>{ it('it should post director',(done)=>{ const director={ name:'metin', surname:'ozturk', bio:'uzun hikaye' }; chai.request(server) .post('/api/directors') .send(director) .set('x-access-token',token) .end((err,res)=>{ res.should.status(200); res.should.be.a('object'); res.body.should.have.property('name'); res.body.should.have.property('surname'); res.body.should.have.property('bio'); directorId=res.body._id; done(); }); }); }); describe('/GET/:directorId director',()=>{ it('it should GET a director by the given id',(done)=>{ chai.request(server) .get('/api/directors/'+directorId) .set('x-access-token',token) .end((err,res)=>{ res.should.status(200); res.body.should.be.a('array'); done(); }); }); }); describe('/PUT/:directorId director',()=>{ it('it should UPDATE a director given by id',(done)=>{ const director={ name:'mehmet', surname:'kara', bio:'ne yapcan bea' }; chai.request(server) .put('/api/directors/'+directorId) .send(director) .set('x-access-token',token) .end((err,res)=>{ res.should.status(200); res.should.be.a('object'); res.body.should.have.property('name').eql(director.name); res.body.should.have.property('surname').eql(director.surname); res.body.should.have.property('bio').eql(director.bio); done(); }); }); }); describe('/DELETE/:directorId director',()=>{ it('it should DELETE a movie given by id',(done)=>{ chai.request(server) .delete('/api/directors/'+directorId) .set('x-access-token',token) .end((err,res)=>{ res.should.status(200); res.should.have.be.a('object'); res.body.should.have.property('status').eql(1); done(); }); }); }); });
import { createStore } from 'redux'; const initialState = { Prop1: 'test' // Props2: [] // ... }; const reducer = (state = initialState, action) => { // The .dispatcher() will trigger reducer() // Add if/then statements for how to resolve actions // // ==================================================== // EXAMPLE: // // The code below doesn't update the 'initialState' // directly, it instead creates a copy and updates the // state of the 'copied' verion. This is how it SHOULD // be done // ==================================================== // // if (action.type === 'ADD_POST') { // return Object.assign({}, state, { // posts: state.posts.concat(action.payload) // }) // } return state; }; const store = createStore(reducer); export default store;
#!/usr/bin/env node var fs = require('fs') var nunjucks = require('nunjucks') var argv = process.argv; //返回命令行脚本的各个参数组成的数组。 var filePath = __dirname; var currentPath = process.cwd(); //返回运行当前脚本的工作目录的路径。_ // // console.log(filePath) // console.log(currentPath) // cli parse argv.shift() argv.shift() console.log(argv) var data = { model: argv[0], attr: { } } for (var i = 1; i < argv.length; i++) { var arr = argv[i].split(':') var k = arr[0]; var v = arr[1]; data.attr[k] = v } console.log('data = ') console.dir(data) // read tpl var tpl = fs.readFileSync(filePath + '/gen.tpl').toString() console.dir(data) // tpl compile var compiledData = nunjucks.renderString(tpl, data) console.log(compiledData) // write file fs.writeFileSync(currentPath + '/gen.xxx', compiledData)
'use strict'; module.exports = function(app) { var express = require('express'); var atms = require('../../app/controllers/atms.server.controller'); var router = express.Router(); app.use('/api/v1/atms', router); // router.use(); router.route('/search') .get(atms.queryATM); router.route('/states') .get(atms.getStates) .post(atms.addState); router.route('/banks') .get(atms.getBanks) .post(atms.addBank); router.route('/') .get(atms.getAllAtms) .post(atms.createATM); router.route('/:atmid') .get(atms.getOneATM) .put(atms.updateATM) .delete(atms.deleteATM); router.route('/user/:userid') .get(atms.getUserAtms); };
import React from 'react'; import useWindowDimensions from './windowdimensions'; import './wordcloud.css'; export default function WordCloud(props) { let words = props.data; let data = []; for (const word in words) { data.push({ word: word, weight: words[word] }); } /* returned input is too large. The supplied endpoint returns an entire story with weight values. Future versions of this component will need to either return less words from the API or another solution would be to order the words by their weight values before slicing them. So that only the more complex words would be displayed*/ const wordCloudData = data.slice(0, 50); function generateColor() { let number = Math.random(); if (number <= 0.1) { return '#9BE1DF'; } else if (number <= 0.2) { return '#F94144'; } else if (number <= 0.3) { return '#F3722C'; } else if (number <= 0.4) { return '#F8961E'; } else if (number <= 0.5) { return '#F9844A'; } else if (number <= 0.6) { return '#F9C74F'; } else if (number <= 0.7) { return '#90BE6D'; } else if (number <= 0.8) { return '#43AA8B'; } else if (number <= 0.9) { return '#4D908E'; } else { return '#277DA1'; } } function shuffle(array) { var currentIndex = array.length, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex--; // And swap it with the current element. [array[currentIndex], array[randomIndex]] = [ array[randomIndex], array[currentIndex], ]; } return array; } shuffle(wordCloudData); const { height, width } = useWindowDimensions(); return ( <div className="word-cloud"> {wordCloudData.map((line, i) => { let left = width * Math.random(); let top = height * Math.random(); return ( <span key={i} style={{ color: generateColor(), fontSize: `calc(2rem * (${line.weight} * 100) + 1vw)`, left: Math.random() < 0.5 ? `-${left}px` : `${left}px`, top: Math.random() < 0.5 ? `-${top}px` : `${top}px`, }} > <p>{line.word}</p> </span> ); })} ; </div> ); }
const add = function (x, y) { const total = x + y; console.log("Сумма = ", total); return total; }; add(5, 6); console.log("Сумма = ", add(3, 2)); const result = add(4, 5); console.log("Результат суммы ", result); add(1, 4); const fnA = function (val) { return val >= 50 ? "More than 50" : "Less than 50"; }; console.log(fnA(70)); console.log(fnA(30)); console.log(fnA(50)); // Написать функцию, кот. возвращает сумму чисел const calculateTotalPrice = function (items) { let total = 0; for (const item of items) { total += item; } return total; }; console.log(calculateTotalPrice([54, 28, 105, 70, 92, 17, 120, 12, 25, 90])); console.log(calculateTotalPrice([1, 2, 3])); console.log(calculateTotalPrice([100, 200, 300])); const findLogin = function (allLogins, loginToFind) { return allLogins.includes(loginToFind) ? `Password ${loginToFind} is found` : `Password ${loginToFind} is not found`; }; console.log( findLogin(["m4ngoDoge", "k1widab3st", "poly1scute", "aj4xth3m4n"], "avocod3r") ); console.log( findLogin( ["m4ngoDoge", "k1widab3st", "poly1scute", "aj4xth3m4n"], "k1widab3st" ) ); console.log( findLogin(["m4ngoDoge", "k1widab3st", "poly1scute", "aj4xth3m4n"], "jam4l") ); console.log( findLogin( ["m4ngoDoge", "k1widab3st", "poly1scute", "aj4xth3m4n"], "poly1scute" ) ); const changeToSlug = function (title) { let slugString = ""; return (slugString = title.toLowerCase().split(" ").join("-")); }; console.log(changeToSlug("Top 10 benefits of React framework")); // Array.from const fn = function () { console.log(arguments); const args = Array.from(arguments); console.log(args); }; fn(1, 2, 3); fn(1, 2, 3, 4, 5); fn(1, 2, 3, 4, 5, 6, 7); // ...rest const fn1 = function (...args) { console.log(args); }; fn1(1112, 13224, 13134); fn1(1, 2, 3, 4, 5); fn1(1, 2, 3, 4, 5, 6, 7); // Задачи // сложение произвольного кол-ва аргументов const add1 = function (...args) { let total = 0; for (const arg of args) { total += arg; } return total; }; console.log(add1(1, 2, 3)); console.log(add1(1, 2, 3, 4, 5, 6));
import React from 'react' function Page3(props) { return ( <div> <h2> 我是Page33页</h2> <h2> 我是Page33页</h2> </div> ) } export default Page3
#!/usr/bin/env node "use strict" require('./helper') let ls = require('./ls') let fs = require('fs').promise let co = require('co') let path = require('path') let dir = process.argv[2] let rm = co.wrap(function*(dir) { let stat = yield fs.stat(dir) if (stat) { let fileNames = yield fs.readdir(dir) for (let file of fileNames ) { let filePath = path.join(dir, file) let stat = yield fs.stat(filePath) if(stat.isDirectory()) { rm(filePath); } else { fs.unlink(filePath); } } fs.rmdir(dir) } }) function* main() { rm(dir) } module.exports = main
const { Event } = require("klasa"); const AudioManager = require("../utils/music/AudioManager.js"); const Website = require("../utils/Website.js"); class KlasaReady extends Event { async run() { this.client.user.setActivity(`${this.client.guilds.size} guilds! | r.help | v2`, { type: "WATCHING" }); this.client.audioManager = new AudioManager(this.client); this.client.website = new Website(this.client); this.client.website.start(); this.client.audioManager.nodes.forEach(n => { n.on("ready", () => this.client.console.log(`AudioNode connected with host: ${n.host}`)); n.on("error", error => this.client.console.error(`AudioNode failed to connect with host: ${n.host}. This node will not be used for audio.`)); }); } } module.exports = KlasaReady;
/** * Using POST params update or save a boss to the database * If res.locals.boss is there, it's an update otherwise this middleware creates an entity * Redirects to / after success */ const requireOption = require('../requireOption'); module.exports = function (objectrepository) { const BossModel = requireOption(objectrepository, 'BossModel'); return function (req, res, next) { if( typeof req.body.name === 'undefined' || typeof req.body.dateOfBirth === 'undefined' || typeof req.body.nickName === 'undefined' || typeof req.body.wealth === 'undefined') { return next(); }; if(typeof res.locals.boss==='undefined') { res.locals.boss = new BossModel(); } res.locals.boss.name=req.body.name; res.locals.boss.dateOfBirth=req.body.dateOfBirth; res.locals.boss.nickName=req.body.nickName; res.locals.boss.wealth=req.body.wealth; if(typeof res.locals.boss.picture === 'undefined' || res.locals.boss.picture == 'none') { if(typeof req.file === 'undefined') { res.locals.boss.picture = 'none'; } else { res.locals.boss.picture = req.file.filename; } } else { if(typeof req.file !== 'undefined') { res.locals.boss.picture = req.file.filename; } } res.locals.boss.save(err => { if(err) { return next(err); } return res.redirect('/'); }) }; };
import { Meteor } from 'meteor/meteor'; import { ReactiveVar } from 'meteor/reactive-var'; import { ReactiveDict } from 'meteor/reactive-dict'; import { Template } from 'meteor/templating'; import './nav.js'; import './footer.html'; import './homeLayout.html'; import './layout.html'; import './footer.css';
'use strict'; var app=angular.module('loginApp', ['ngRoute']); app.config(['$routeProvider', function($routeProvider){ $routeProvider.when('/login', {templateUrl: 'partials/login.html', controller:'loginCtrl'}); $routeProvider.when('/home', {templateUrl: 'partials/home.html', controller:'homeCtrl'}); $routeProvider.otherwise({redirectTo: '/login'}); }]); app.run(function($rootScope, $location , loginService){ var routespermission=['/home']; $rootScope.$on('$routeChangeStart', function(){ if(routespermission.indexOf($location.path()) !=-1) { var connected=loginService.islogged(); connected.then(function(msg){ if(!msg.data) $location.path('/login'); }); } }); });
/*! * @copyright 2012-2014 SAP SE. All rights reserved@ */ jQuery.sap.declare("sap.landvisz.internal.ModelingStatusRenderer"); /** * @class ModelingStatusRenderer renderer. * @static */ sap.landvisz.internal.ModelingStatusRenderer = {}; /** * Renders the HTML for the given control, using the provided * {@link sap.ui.core.RenderManager}. * * @param {sap.ui.core.RenderManager} * oRm the RenderManager that can be used for writing to the render * output buffer * @param {sap.ui.core.Control} * oControl an object representation of the control that should be * rendered */ sap.landvisz.internal.ModelingStatusRenderer.render = function(oRm, oControl) { // write the HTML into the render manager var rb = sap.ui.getCore().getLibraryResourceBundle("sap.landvisz"); if (!this.initializationDone) { oControl.initControls(); oRm.write("<div"); oRm.writeControlData(oControl); if (oControl.entityMaximized != true) { if (oControl.renderSize == sap.landvisz.EntityCSSSize.Small) { oControl._imgFolderPath = "16x16/"; oRm.addClass("sapLandviszStatusSectionSmallSize"); } else if(oControl.renderSize == sap.landvisz.EntityCSSSize.RegularSmall || oControl.renderSize == sap.landvisz.EntityCSSSize.Regular || oControl.renderSize == sap.landvisz.EntityCSSSize.Medium || oControl.renderSize == sap.landvisz.EntityCSSSize.Large ){ oControl._imgFolderPath = "24x24/"; oRm.addClass("sapLandviszStatusSectionAllSize"); } } else if (oControl.entityMaximized == true) { oControl._imgFolderPath = "24x24/"; oRm.addClass("sapLandviszStatusSectionAllSize"); } // write the HTML into the render manager oRm.writeClasses(); if (oControl.getStatus() == sap.landvisz.ModelingStatus.ERROR || oControl.getStatus() == sap.landvisz.ModelingStatus.WARNING) oRm.addStyle("border","1px solid #999999"); oRm.writeStyles(); oRm.writeAttributeEscaped("title",oControl.getStatusTooltip()); oRm.write(">"); //oControl.statusImage.setTooltip(oControl.getStatusTooltip()); if(oControl.initializationDone == false){ oControl.statusImage.attachPress(function(oEvent) { oControl.fireEvent("statusSelected"); }); } this._assignIconSrc(oRm, oControl); if (oControl.getStatus() == sap.landvisz.ModelingStatus.ERROR || oControl.getStatus() == sap.landvisz.ModelingStatus.WARNING) oRm.renderControl(oControl.statusImage); if (oControl.getStateIconSrc() && "" != oControl.getStateIconSrc()) { oControl.stateImage.setSrc(oControl.getStateIconSrc()); oControl.stateImage.setTooltip(oControl.getStateIconTooltip()); oControl.stateImage.addStyleClass("stateIconClass"); oRm.renderControl(oControl.stateImage); } oControl.initializationDone = true; oRm.write("</div>"); } }; sap.landvisz.internal.ModelingStatusRenderer._assignIconSrc = function(oRm, oControl) { if (oControl.getStatus() == sap.landvisz.ModelingStatus.ERROR) oControl.statusImage.setSrc(oControl._imgResourcePath + oControl._imgFolderPath + "error.png"); else if (oControl.getStatus() == sap.landvisz.ModelingStatus.WARNING) oControl.statusImage.setSrc(oControl._imgResourcePath + oControl._imgFolderPath + "warning.png"); else if (oControl.getStatus() == sap.landvisz.ModelingStatus.WARNING) oControl.statusImage.setSrc(oControl._imgResourcePath + oControl._imgFolderPath + "success.png"); };
{ "blog.title": "Blogen" }
var timedata; var td_norm; $(document).ready(function() { // Stuff to do as soon as the DOM is ready $.getJSON("./data_int.json",function(data){ timedata = data.slice() console.log("data loaded"); //$("#play-btn").prop("disabled", false); }); $.getJSON("./data_int.json",function(data_int){ td_norm = normalizedTimeseries(data_int.slice()); //loadGraphs(td_norm) loadCanvas(); checkboxes(); }) document.getElementById("play-btn").disabled = false; }); function checkboxes(){ var container = $("#checkboxes"); for (var i = 0; i < timedata.length; i++) { $('<input />', { type: 'checkbox', id: 'chkbx-'+i, value: timedata[i].label , checked: true}).appendTo(container); $('<label />', { 'for': 'chkbx-'+i, text: timedata[i].label }).appendTo(container); } } var year = 0; var drum = new Tone.MembraneSynth().toMaster(); drum.oscillator.type = "sine"; drum.volume.value = -12 var bell = new Tone.MetalSynth().toMaster(); var freeverb = new Tone.Freeverb(0.5,600); Tone.Master.volume.value = -12; //mute master until user presses play //Tone.Master.mute = true; Tone.Master.chain(freeverb); var oscillators = createOsc(); Tone.Transport.scheduleRepeat(function(time){ console.log("playing"); //console.log(year++);// + " - year: " + (1890 + (year/0.126))); if (year == 1000) { stop(); } drum.triggerAttackRelease("C4", "16n",Tone.now,0.2); oscillators.forEach(function(el,idx){ if(el === null){ return }; el.osc.mute = false; if($("#chkbx-"+idx).prop("checked") & td_norm[idx].timeseries[year] != null){ el.osc.mute = false; el.play(timedata,td_norm); } if(td_norm[idx].timeseries[year] === null){ el.osc.mute = true; } }); }, "16n"); function play(startingFrom){ year = startingFrom | 0; Tone.Master.mute = false; Tone.Transport.start(); } function stop(){ Tone.Transport.stop(); Tone.Transport.clear(); bell.triggerAttack(); oscillators.forEach(function(el){ if(el === null) return; el.osc.stop(); }) //Tone.Master.mute = true; year = 0; } function loadGraphs(d){ plotData = [] d.forEach(function(el,idx){ let trace = { x: [...Array(timedata[0].timeseries.length).keys()], //spread operator, dirty hack :( y: el.timeseries,//normalize(el.timeseries), type: 'scatter', name: idx +" - "+ el.label }; plotData[idx] = trace; }) Plotly.newPlot('graphs', plotData); } function loadCanvas(){ var can = document.getElementById("canvas"); can.height = 520; can.width = 999; var ctx = can.getContext("2d"); timedata.forEach(function(el,idx){ //console.log("printing " + el.label); ctx.fillStyle = stringToColour(el.label); ctx.fillRect(0,40*idx,999,40); }); } function normalizedTimeseries(tmdt){ var res = tmdt.slice(); res.forEach(function(el,idx){ res[idx].timeseries = normalize(res[idx].timeseries); }) return res; } function normalize(tms){ let a = new Array(1000); let max = Math.max.apply(Math, tms); tms.forEach(function(el,idx) { if (el == null) { a[idx] = el; }else{ a[idx] = el / max; } }); return a; } function createOsc(){ var oscillators = new Array(13); oscillators[0] = { osc: new Tone.OmniOscillator("C5","fmsquare").toMaster(), play: function(timedata, td_norm){ if(timedata[0].timeseries[year] != null){ if(this.osc.state == "stopped") this.osc.start(); this.osc.frequency.value = td_norm[0].timeseries[year]*880; } } } // oscillators[1] = { osc: new Tone.OmniOscillator("C2","fmsine").toMaster(), play: function(timedata, td_norm){ if(this.osc.state == "stopped") this.osc.start(); this.osc.modulationIndex.value = td_norm[1].timeseries[year]*10; } } oscillators[2] = { osc: new Tone.OmniOscillator("B3","fmsine").toMaster(), play: function(timedata, td_norm){ if(timedata[2].timeseries[year] != null){ if(this.osc.state == "stopped") this.osc.start(); this.osc.modulationIndex.value = td_norm[2].timeseries[year]; } } } oscillators[3] = { osc: new Tone.OmniOscillator("F#5","fatsine").toMaster(), play: function(timedata, td_norm){ if(timedata[3].timeseries[year] != null){ if(this.osc.state == "stopped") this.osc.start(); this.osc.detune.value = timedata[3].timeseries[year]; this.osc.spread = -40 + timedata[4].timeseries[year]; } } } oscillators[4] = null;//oscillator[3] oscillators[5] = { osc: new Tone.OmniOscillator("D5","fatsine").toMaster(), play: function(timedata, td_norm){ if(timedata[5].timeseries[year] != null){ if(this.osc.state == "stopped") this.osc.start(); this.osc.frequency.value = 880 + timedata[5].timeseries[year]; } } } oscillators[6] = { osc: new Tone.OmniOscillator("C2","fatsquare").toMaster(), play: function(timedata, td_norm){ if(timedata[6].timeseries[year] != null){ if(this.osc.state == "stopped") this.osc.start(); this.osc.frequency.value = timedata[6].timeseries[year]; } } } oscillators[7] = { osc: new Tone.OmniOscillator("G2","fmsine").toMaster(), play: function(timedata, td_norm){ if(this.osc.state == "stopped") this.osc.start(); this.osc.modulationIndex.value = timedata[7].timeseries[year]*2; } } oscillators[8] = { osc: new Tone.OmniOscillator("C2","fmsquare").toMaster(), play: function(timedata, td_norm){ if(timedata[8].timeseries[year] != null){ if(this.osc.state == "stopped") this.osc.start(); this.osc.frequency.value = timedata[8].timeseries[year]; } } } oscillators[9] = { osc: new Tone.OmniOscillator("G2","fmsquare").toMaster(), play: function(timedata, td_norm){ if(timedata[9].timeseries[year] != null){ if(this.osc.state == "stopped") this.osc.start(); this.osc.frequency.value = timedata[9].timeseries[year]/10; } } } oscillators[10] = { osc: new Tone.OmniOscillator("F5","fatsine").toMaster(), play: function(timedata, td_norm){ if(timedata[10].timeseries[year] != null){ if(this.osc.state == "stopped") this.osc.start(); this.osc.frequency.value = timedata[10].timeseries[year]/10; } } } oscillators[11] = { osc: new Tone.OmniOscillator("G2","fmsquare").toMaster(), play: function(timedata, td_norm){ if(timedata[11].timeseries[year] != null){ if(this.osc.state == "stopped") this.osc.start(); this.osc.frequency.value = timedata[11].timeseries[year]*30; } } } oscillators[12] = { osc: new Tone.OmniOscillator("G6","fatsine").toMaster(), play: function(timedata, td_norm){ if(timedata[12].timeseries[year] != null){ if(this.osc.state == "stopped") this.osc.start(); this.osc.spread = timedata[12].timeseries[year]; } } } oscillators.forEach(function(el){ if(el === null) return; el.osc.volume.value = -12; }); return oscillators } var stringToColour = function(str) { var hash = 0; for (var i = 0; i < str.length; i++) { hash = str.charCodeAt(i) + ((hash << 5) - hash); } var colour = '#'; for (var i = 0; i < 3; i++) { var value = (hash >> (i * 8)) & 0xFF; colour += ('00' + value.toString(16)).substr(-2); } return colour; }
//Load all the function at the beginning, for scroll and for resize $(document).ready(function(){ $(".parallax-noSnap").timGuignardParallax({ snapEffect : false }); $(".parallax-intro").timGuignardParallax({ heightForSnap : 50 }); $(".parallax").timGuignardParallax(); /*$(".parallax").timGuignardParallax({ snapEffect : true, //Default : true => allow Snap Effect heightForSnap : 300, //If snap Effect, number of pixel from where the element appers position: 'absolute' //Default: relative => other value: false, 'relative', 'fixed' });*/ });//end Document ready
const toTopArrow = () => { const toTop = document.getElementById('totop'), headerMain = document.querySelector('.header-main'); document.addEventListener('scroll', () => toTop.style.display = (window.scrollY > headerMain.clientHeight - 100) ? 'block' : 'none'); }; export default toTopArrow;
#!/usr/bin/env node /** * Module dependencies. ***/ var program = require('commander'); var pack = require('./package.json'); var shell = require('shelljs'); function list(val) { return val.split(','); } program .version(pack.version) .description('Limits processes CPU usage') .option('-t, --time <n>', 'Time in seconds to scan. Defaults to 20') .option('-c, --cpu <n>', 'Percentage of cpu allowed from 0 to 800. Defaults to 50') .option('-l, --list <items>', 'A list of process names to grep', list) .parse(process.argv); var process_limiting = []; process.on('uncaughtException', function(err){ console.log("Err: ", err); }); // Find Node Processes var findProcesses = function(){ console.log("Finding processes..."); var grepList = program.list || []; console.log('grepList', grepList); if (grepList.length === 0) { console.log('A list of process to grep must be provided'); process.exit(); } var grepCmd = grepList.join(' | grep '); var cmd = "ps ax | grep "+grepCmd+" | grep -v node-limiter | grep -v grep | awk '{print $1}'"; var wait_secs = parseInt(program.time) || 20; var cpu_limit = parseInt(program.cpu) || 10; if(process_limiting.length > 0 ) { console.log("Currently limited "+process_limiting.length+" processes"); } var child = shell.exec(cmd, function(code, stdout, stderr) { //console.log('Exit code:', code); //console.log('Program output:', stdout); //console.log('Program stderr:', stderr); var pid = parseInt(stdout); //console.log(typeof pid); if(pid === "" || isNaN(pid)) { console.log("No process found, will try again in "+wait_secs+"s"); } else if(process_limiting.indexOf(pid) === -1) { console.log("Process found with pid: ", pid); var limiter = "cpulimit -p "+pid+" -l "+cpu_limit+" "; console.log(limiter); process_limiting.push(pid); nodeLimiter(limiter, pid, wait_secs); } setTimeout(findProcesses, 1000*wait_secs); }); } // Limiter var nodeLimiter = function(limiter, pid, wait_secs){ var child_process = shell.exec(limiter, {async:true}); child_process.stdout.on('data', function(data) { //console.log("Data: ", data); }); child_process.stderr.on('data', function(data) { console.log("Err: ", data); }); child_process.on('close', function(code) { console.log('Limiting pid ended: ', pid, ' with code ', code); }); } if (program.init !== ''){ // check cpulimit availability if (!shell.which('cpulimit')) { shell.echo('Sorry, this script requires cpulimit'); shell.echo('Please install it:'); shell.echo('$ brew install cpulimit'); shell.echo('$ apt-get install cpulimit'); shell.exit(1); } findProcesses(); }
$(document).ready(function(){ $('.search').bind('keyup', function(e){ if (e.keyCode === 13){ var query = $(this).val(); window.location = "search.php?query=" + query; } }); });
import { renderString } from '../../src/index'; describe(`Escape strings for use in URLs (uses UTF-8 encoding). It accepts both dictionaries and regular strings as well as pairwise iterables.`, () => { it(`unnamed case 0`, () => { const html = renderString(`{{ "Escape & URL encode this string"|urlencode }}`); }); });
import React, {Component} from 'react'; import Form from "./Form"; class Index extends Component { // This State Declaration state = { userControl: '', fatherControl: '', emailControl: '', birthControl: '', phoneControl: '', } //This is handChange Method handleChange = event => { // This Is code for new value set of Sate this.setState({ [event.target.name] : event.target.value }) } // This is submit method submitControl = event => { event.preventDefault(); //This is code for console log console.log(this.state) // This is code for clear an input value after form submit this.setState({ userControl:'', birthControl:'', fatherControl:'', phoneControl:'', emailControl:'' }) //event.target.reset() } render() { return ( <div className='container mt-5 pt-2 pl-3 pr-3 pb-3'> <div className='row'> <div className='col-md-6 mb-5'> <div className='card-header mb-5'> <h2 className='text-danger'>Control Form with react</h2> </div> <div className='form-row'> <Form values = {this.state} handleChange = {this.handleChange} submitControl = {this.submitControl} btnTest = 'Apply' /> </div> </div> </div> </div> ); } } export default Index;
module.exports = { env: { browser: true, es6: true }, extends: 'eslint:recommended', parser: 'babel-eslint', parserOptions: { ecmaFeatures: { experimentalObjectRestSpread: true, jsx: true }, sourceType: 'module' }, plugins: ['react'], rules: { 'no-console': 0, 'no-unused-vars': 'off', 'no-use-before-define': 'error', 'react/no-unused-state': 'warn', 'react/no-unused-prop-types': 'warn', 'react/prefer-es6-class': ['warn', 'always'], 'react/react-in-jsx-scope': 'off', 'react/jsx-no-bind': 'off', 'react/jsx-uses-vars': 'warn', 'react/jsx-key': 'warn', 'react/jsx-no-duplicate-props': 'warn', indent: ['error', 4], 'linebreak-style': ['error', 'unix'], quotes: ['error', 'single'], semi: ['error', 'never'] } };
var Result = React.createClass({ render: function() { var tab; var block; if(this.props.chem){ tab; switch(this.props.tabs['result']){ case 'raw': tab = <ResultRaw chem={this.props.chem}/> break; case 'vis': tab = <Vis chem={this.props.chem} info={this.props.info} tabs={this.props.tabs}/>; break; // case 'mod': // tab = <ModViewer chem={this.props.chem} // tabs={this.props.tabs}/> // break; case 'dld': tab = <ResultDownload chem={this.props.chem} tabs={this.props.tabs}/> break; } block = <div className='result-block'> <ResultNav tabs={this.props.tabs}/> <div id='result-tab-wrapper'> {tab} </div> </div> }else{ block = <div className='result-block'> Please either generate new results or load old ones. Manage local data using the 'Submit' tab. <br/><br/> Once data has been loaded, interact by clicking 'view results' in the menu to the left. </div> } return( <div> <ResultLocalIndex index={this.props.localIndex}/> {block} </div> ) }, });
$(function () { var maiorLinha = 0; $(".container .linha").each(function () { var larguraLinha = 0; $(this).children(".tile").each(function () { larguraLinha += $(this).width(); larguraLinha += 2*parseInt($(this).css("margin-right").toString().replace("px", "")); }); if (larguraLinha > maiorLinha) maiorLinha = larguraLinha+5; }); $(".container").css("width", maiorLinha.toString() + "px"); }); $(".tile").mousedown(function () { $(this).addClass("selecionado"); }); $(".tile").mouseup(function () { $(this).removeClass("selecionado"); }); $(".tile").mouseleave(function () { $(this).removeClass("selecionado"); });
import catalogService from './catalogService'; import customerLocationService from './customerLocationService'; export { catalogService, customerLocationService };
import React, { Component } from 'react'; import { Table } from 'react-bootstrap'; import Barca from '../../Assets/barca.png' import chelsea from '../../Assets/chelsea.png' import juvey from "../../Assets/juvey.png"; import napoli from '../../Assets/napoli.png'; import manu from '../../Assets/mancity.png'; import './MatchTable.css'; class MatchTable extends Component { constructor() { super() this.state = { leagueTable: [ { id: "1", logo: <img className="euro_image" src={manu} alt="logo" />, club: "Manchester United", P: "18", W: "12", D: "2", L: "4", GD: '34', Pts: "44" }, { id: "2", logo: <img className="euro_image" src={Barca} alt="logo" />, club: "Barcelona", P: "18", W: "12", D: "2", L: "4", GD: '34', Pts: "44" }, { id: "3", logo: <img className="euro_image" src={juvey} alt="logo" />, club: "Juventus", P: "18", W: "12", D: "2", L: "4", GD: '34', Pts: "44" }, { id: "4", logo: <img className="euro_image" src={napoli} alt="logo" />, club: "Napoli", P: "18", W: "12", D: "2", L: "4", GD: '34', Pts: "44" }, { id: "5", logo: <img className="euro_image" src={chelsea} alt="logo" />, club: "Chelsea", P: "18", W: "12", D: "2", L: "4", GD: '34', Pts: "44" }, ] } } matchLeague = () => { let { leagueTable } = this.state return ( leagueTable.map(result => { return ( <tr key={result.id}> <td>{result.id}</td> <td className="euro_club_data"> <div className="euro_image_cover">{result.logo}</div> <div><p>{result.club}</p></div> </td> <td>{result.P}</td> <td>{result.W}</td> <td>{result.D}</td> <td>{result.L}</td> <td>{result.GD}</td> <td>{result.Pts}</td> </tr> ) }) ) } render() { return ( <div> <div className="table_header"><h3 className="table__content">Group A</h3></div> <Table responsive> <thead > <tr> <th>#</th> <th>Teams</th> <th>P</th> <th>W</th> <th>D</th> <th>L</th> <th>GD</th> <th>Pts</th> </tr> </thead> <tbody> {this.matchLeague()} </tbody> </Table> </div> ); } } export default MatchTable;
window.onload = function(){ document.getElementById("cpwd").style.display = "none"; document.getElementById("name").style.display = "none"; document.getElementById("verf").style.display = "none"; } function newaccount(){ document.getElementById("new").style.width = "300px"; document.getElementById("log").style.display = "none"; document.getElementById("forgot").style.display = "none"; document.getElementById("verf").style.display = "flex"; document.getElementById("cpwd").style.display = "flex"; document.getElementById("name").style.display = "block"; console.log("ui changed") } function newvalidate(){ console.log("newvalidate()") var email = document.getElementById('email').value; console.log(email) var password = document.getElementById('pwd').value; console.log(password) var cpassword = document.getElementById("cpwd").value; console.log(cpassword) var name = document.getElementById("name").value; console.log(name) if (email.length < 4) { alert('Please enter an email address.'); return; console.log(email.length) } if (password.length < 4) { alert('Please enter a password.'); return; } console.log(password.length) if(password != cpassword){ alert("password does not match"); } else if((name && email && password) != null){ firebase.auth().createUserWithEmailAndPassword(email,password).then(function(msg){ console.log("user created"); console.log(msg.val()) firebase.auth().onAuthStateChanged((user) => { var uid = user.uid; console.log("current user uid : " + uid); }); saveData(name,email,password) console.log("data saved") console.log("email verification sending..........") emailVerification(); console.log("email verificati0n sent") }) .catch(function(error) { var errorCode = error.code; var errorMessage = error.message; if (errorCode == 'auth/weak-password') { alert('The password is too weak.'); } else { alert(errorMessage); } console.log(error); }); console.log("Account Created"); document.getElementById("form").reset(); console.log("reseted") } else{ alert("Enter all Form Fields"); } } function login(){ document.getElementById("cpwd").style.display = "none"; document.getElementById("verf").style.display = "none"; document.getElementById("new").style.display = "none"; document.getElementById("name").style.display = "none"; console.log("login ui changed"); } function logvalidate(){ var email = document.getElementById('email').value; console.log(email) var password = document.getElementById('pwd').value; console.log(password) if (email.length < 4) { alert('Please enter an email address.'); return; } console.log(email.length) if (password.length < 4) { alert('Please enter a password.'); return; } console.log(password.length) firebase.auth().signInWithEmailAndPassword(email, password) .then(function(msg){ console.log(msg); alert("Logged In") console.log("loggedin") authRetrieve(); }) .catch(function(error) { var errorCode = error.code; console.log(errorCode) var errorMessage = error.message; console.log(errorMessage) document.getElementById("form").reset(); if (errorCode === 'auth/wrong-password') { alert('Wrong password.'); } else { alert(errorMessage); } console.log(error); console.log("inside catch") }); console.log("didnt reach catch") } function authRetrieve(){ firebase.auth().onAuthStateChanged((user) => { if(user){ var name = user.email; console.log(name); } }) } function emailVerification(email){ email = document.getElementById("email").value; firebase.auth().currentUser.sendEmailVerification() .then(function(msg){ alert("Email Verification Sent") console.log(msg); }) .catch(function(err){ var errorcode = err.code; var errormessage = err.message; if(errorcode == 'auth/invalid-email'){ console.log("ErrorCode : ". errorcode); console.log(errormessage) } else if(errorcode == 'auth/user-not-found'){ console.log("ErrorCode : ".errorcode); console.log(errormessage); } console.log(err); }); } function forgot(){ document.getElementById("log").style.display = "none"; document.getElementById("cpwd").style.display = "none"; document.getElementById("verf").style.display = "none"; document.getElementById("new").style.display = "none"; document.getElementById("pwd").style.display = "none"; document.getElementById("name").style.display = "none"; document.getElementById("forgot").style.marginTop = "-200px"; fmessage(); } function fmessage(){ var email = document.getElementById('email').value; firebase.auth().sendPasswordResetEmail(email) .then(function(msg){ console.log(msg); alert("Password Reset Email Sent"); }) .catch(function(err){ var errorcode = err.code; var errormessage = err.message; if(errorcode == 'auth/invalid-email'){ alert("Invalid E-mail"); console.log("ErrorCode : ".errorcode) } else if(errorcode == 'auth/user-not-found'){ alert("User not found"); console.log("ErrorCode : ".errorcode) } console.log(err); }); } function saveData(name,email,pwd){ console.log("inside savedata") var user = firebase.auth(); console.log("user"+ user) for(var value in user){ console.log("key : " + user + "value : " + user[value]); //console.log(user[value]) } console.log("db refferring..........") var database = firebase.database().ref("userlist"); console.log("db reffered") var push = database.push().child("Acoount Details"); console.log("pushed") push.set({ name:name, email:email, password:pwd }); console.log("finish savedata() inside savedata") } var validate = newvalidate(); if(validate){ console.log("savedata calling........ inside validate") saveData(name,email,pwd); console.log("savedata called inside validate !") } else{ console.log("data not saved.........") }
const fs = require('fs') var data = [ { question:'Who was the first congress prcident', optionA:'Mahatma Gandhi', optionB:'Jawaharlal Neheru', optionC:'Netaji Subash Chandra Bose', optionD:'Indira Gandhi' } ] data.push({ question:'Name the animal bird of India', optionA:'Peacock', optionB:'Tiger', optionC:'Leapad', optionD:'Lion' }) let value = JSON.stringify(data, null, 2); fs.writeFileSync('question.json', value) var read = fs.readFileSync('question.json') var question = JSON.parse(read) console.log(question)
/*jshint esversion: 6 */ var fs = require('fs'); var shell = require('shelljs'); var path = require('path'); var config = require('./defaultWebdriverConfig'); var newLine = '\n'; var public = {}; public.getTestScriptPath = function (test) { return `tests/bdd/${test.application}/features/${test._id}.feature`; }; public.testsToScripts = function (application, tests) { setup(application); tests.forEach(test => { testTranslate(application._id, test); }); }; public.runScripts = async function (appId) { var dir = `tests/bdd/${appId}`; if (shell.test('-d', dir) && shell.ls(dir + '/features').length !== 0) { var wdio = path.normalize('node_modules/webdriverio/bin/wdio'); var conf = path.normalize(`${dir}/wdio.conf.js`); shell.exec(`node ${wdio} ${conf}`, function (code) { if (code === 0) { console.log("Success"); } else { console.log("Fail"); } }); return true; } else { return false; } } var testTranslate = function (appId, test, seed) { var resultFile = {}; resultFile.name = test.name; var data = `Feature: ${test.feature}` + newLine; data += newLine; test.scenarios.forEach(scenario => { data += `Scenario: ${scenario.description}` + newLine; scenario.given.forEach(given => { data += " Given " + given.command + newLine; }); scenario.when.forEach(when => { data += " When " + when.command + newLine; }); scenario.when.forEach(then => { data += " Then " + then.command + newLine; }); data += newLine; }); fs.writeFileSync(`tests/bdd/${appId}/features/${test._id}.feature`, data); return data; }; function createTestsDirs(appId) { // Rethink the directories considering the fleeting nature of tests var dir = 'tests/bdd/' + appId; var dirs = [dir + '/features', dir + '/reports']; shell.mkdir('-p', dirs); } function setup(application) { createTestsDirs(application._id); config.writeConfig(application); var dir1 = 'modules/bdd/step-definitions/index.js'; var dir2 = `tests/bdd/${application._id}/features/step-definitions`; shell.mkdir('-p', dir2); shell.exec(`cp ${dir1} ${dir2}`); } module.exports = public;
var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var Zia; (function (Zia) { var Texture2D = (function (_super) { __extends(Texture2D, _super); function Texture2D(graphicsDevice, options) { _super.call(this, graphicsDevice, options, graphicsDevice.gl.TEXTURE_2D); } Texture2D.prototype.setData = function (data) { var width = this.width, height = this.height; this._setData(function (gl) { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data); }, true); this._generateMipmap(); }; Texture2D.createFromImagePath = function (graphicsDevice, imagePath, options) { var result = new Zia.Texture2D(graphicsDevice, options); var gl = graphicsDevice.gl; // Set temporary 1x1 white texture, until image has loaded result.width = 1; result.height = 1; result.setData(new Uint8Array([255, 255, 255, 255])); var image = new Image(); image.onload = function () { result._setData(function () { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); }, true); result._generateMipmap(); result.width = image.naturalWidth; result.height = image.naturalHeight; }; image.src = imagePath; return result; }; Texture2D.createFromImageData = function (graphicsDevice, imageData, width, height, options) { var result = new Zia.Texture2D(graphicsDevice, options); result.width = width; result.height = height; var gl = graphicsDevice.gl; result.setData(imageData); return result; }; Texture2D.createWhiteTexture = function (graphicsDevice) { var whitePixel = new Uint8Array([255, 255, 255, 255]); return Texture2D.createFromImageData(graphicsDevice, whitePixel, 1, 1); }; return Texture2D; })(Zia.Texture); Zia.Texture2D = Texture2D; })(Zia || (Zia = {}));
/** * Created by andycall on 15/5/4. */ var express = require('express'), loggerController = require('../controllers/logger'), loggerRouter = express.Router(); loggerRouter.all('/api/:plugin', loggerController.increase, loggerController.index); module.exports = loggerRouter;
import React from 'react' const {format} = require('date-fns') const hu = require('date-fns/locale/hu') function getToday () { return format(new Date(), 'YYYY.MM.DD. dddd', {locale: hu}) } export default function Day ({day}) { return ( <div className="calendar"> <p>{getToday(new Date())}</p> <p>{day.name} névnapja</p> <p className="event">{day.holiday}</p> </div> ) }
import React from 'react'; import { AppRegistry, StyleSheet, Text, View, Image, Button, ScrollView, TextInput, KeyboardAvoidingView, Picker, TouchableOpacity, Dimensions, } from 'react-native'; import {connect} from 'react-redux'; import {bindActionCreators } from 'redux'; import navigateTo from '../../actions/NavigationAction'; import { Container, Content, Form, Item, Input } from 'native-base'; import uStyles from '../../styles'; import Icon from 'react-native-vector-icons/Entypo'; import Icon2 from 'react-native-vector-icons/MaterialCommunityIcons'; import deletePublicationAction from '../../actions/publication/deletePublicationAction'; import LoaderComponent from '../LoaderComponent'; const {height,width}=Dimensions.get('window'); class SelectedPublicationComponent extends React.Component{ constructor(){ super(); this.state={ showLoader:false } this.editPublication=this.editPublication.bind(this); } static navigationOptions = ({ navigation }) => ({ headerTitle:'Publication Data', headerStyle: { backgroundColor: '#0D47A1'}, headerRight:( <TouchableOpacity onPress={() => navigation.navigate('DrawerOpen')} style={uStyles.hambergerMenu}> <Icon name="menu" size={30} color="#fff" /> </TouchableOpacity> ) }); delete(){ this.setState({ showLoader:true }); this.props.deletePublicationAction({publication_id:this.props.selectedPublication.id}).then((x)=>{ this.setState({ showLoader:false }); if(x){ this.props.navigateTo('back'); } }); } editPublication(){ this.props.navigateTo('editPublication'); } render(){ const selectedPublication=()=>{ const showLoader=()=>{ if(this.state.showLoader){ return( <LoaderComponent/> ) } }; let selected=this.props.selectedPublication; if(selected!==null){ return( <View style={[uStyles.container,localStyles.container]}> <View style={localStyles.icon}> <Icon2 name="newspaper" size={30} color="#0D47A1" /> </View> <View style={localStyles.boxContainer}> <View style={localStyles.box}> <Text style={localStyles.boxText}> Publisher Name </Text> </View> <View style={localStyles.box}> <Text style={localStyles.boxText}> {selected.publisher_name} </Text> </View> </View> <View style={localStyles.boxContainer}> <View style={localStyles.box}> <Text style={localStyles.boxText}> Type </Text> </View> <View style={localStyles.box}> <Text style={localStyles.boxText}> {selected.type_name} </Text> </View> </View> <View style={localStyles.boxContainer}> <View style={localStyles.box}> <Text style={localStyles.boxText}> Language </Text> </View> <View style={localStyles.box}> <Text style={localStyles.boxText}> {selected.language_name} </Text> </View> </View> <View style={localStyles.boxContainer}> <View style={localStyles.box}> <Text style={localStyles.boxText}> Perspective </Text> </View> <View style={localStyles.box}> <Text style={localStyles.boxText}> {selected.perspective_name} </Text> </View> </View> <View style={localStyles.boxContainer}> <View style={localStyles.box}> <Text style={localStyles.boxText}> Description </Text> </View> <View style={localStyles.box}> <Text style={localStyles.boxText}> {selected.description} </Text> </View> </View> <View style={localStyles.boxContainer}> <View style={localStyles.box}> <Text style={localStyles.boxText}> Min Headlines </Text> </View> <View style={localStyles.box}> <Text style={localStyles.boxText}> {selected.minimum_headlines} </Text> </View> </View> <View style={localStyles.boxContainer}> <View style={localStyles.box}> <Text style={localStyles.boxText}> Max Headlines </Text> </View> <View style={localStyles.box}> <Text style={localStyles.boxText}> {selected.maximum_headlines} </Text> </View> </View> <View style={localStyles.boxContainer}> <View style={localStyles.box}> <Text style={localStyles.boxText}> Notification Email </Text> </View> <View style={localStyles.box}> <Text style={localStyles.boxText}> {selected.publication_email} </Text> </View> </View> {showLoader()} <View style={uStyles.row}> <View style={uStyles.buttonContainer}> <View style={uStyles.buttonSubContainer}> <TouchableOpacity style={uStyles.dashBoardbutton}> <Text style={uStyles.dashBoardButtonText}>Delete</Text> </TouchableOpacity> </View> </View> <View style={uStyles.buttonContainer}> <View style={uStyles.buttonSubContainer}> <TouchableOpacity style={uStyles.dashBoardbutton} onPress={()=>this.editPublication()}> <Text style={uStyles.dashBoardButtonText}>Edit</Text> </TouchableOpacity> </View> </View> </View> </View> ) } }; return( <ScrollView style={[uStyles.mainView,localStyles.mainView]}> {selectedPublication()} </ScrollView> ) } } const localStyles=StyleSheet.create({ mainView:{ backgroundColor:'#fff' }, container:{ }, logoContainer:{ }, textInput:{ }, icon:{ flex:1, justifyContent:'center', alignItems:'center', marginBottom:20 }, boxContainer:{ flex:1, flexDirection:'row', padding:10, alignItems:'center', borderWidth:1, borderColor:'#eee', borderRadius:7, margin:20 }, box:{ flex:1, marginBottom:20 }, boxText:{ fontWeight:'700', color:'#7f8c8d' } }); function mapStateToProps(state) { return { selectedPublication:state.selectedPublication } } function mapDispatchToProps(dispatch) { return bindActionCreators( { navigateTo:navigateTo, deletePublicationAction:deletePublicationAction },dispatch) } export default connect(mapStateToProps,mapDispatchToProps)(SelectedPublicationComponent)
import React, { Component } from 'react' import './assets/css/App.scss' import { Layout, Menu } from 'antd' import { BrowserRouter as Router, Route, Link } from 'react-router-dom' import routes from './modal/router.js' const { Header, Sider, Content } = Layout const SubMenu = Menu.SubMenu class App extends Component { state = { collapsed: false, navData: [ { text: '出勤查询', icon: 'el-icon-time', children: [ { text: '个人出勤查询', router: 'people-attendance' }, { text: '组织出勤查询', router: 'organization-attendance' } ] }, // { // text: '报表管理', // icon: 'el-icon-tickets', // children: [ // { // text: '汇总报表' // }, // { // text: '明细报表' // } // ] // }, { text: '异常修复', icon: 'el-icon-edit-outline', children: [ { text: '缺卡修复', router: 'card-exception' }, { text: '刷新纪录', router: 'refresh-record' } ] }, { text: '系统设置', children: [] } ] } toggleCollapsed = () => { this.setState({ collapsed: !this.state.collapsed }) } // 跳转路由 jumpRouter = ({ item, key, keyPath }) => { console.log(item, key, keyPath) } render() { return ( <Router> <div className="App height-100"> <Layout className="height-100"> <Header>Header</Header> <Layout> <Sider> <Menu mode="inline" theme="dark" inlineCollapsed={this.state.collapsed} onClick={this.jumpRouter} > {this.state.navData.map((item, index) => { console.log(index) return ( <SubMenu key={index} title={ <span> <span>{item.text}</span> </span> } > {item.children.map(item2 => { return ( <Menu.Item key={item2.router}> <Link to={item2.router}>{item2.text}</Link> </Menu.Item> ) })} </SubMenu> ) })} </Menu> </Sider> <Content> {routes.map((route, key) => { return ( <Route key={key} exact path={route.path} render={props => { console.log(props) return <route.component props routes={route.routes} /> }} /> ) })} </Content> </Layout> </Layout> </div> </Router> ) } } export default App
import React, { useEffect, useState } from 'react'; import { FlatList, StyleSheet, Text, View, Pressable } from 'react-native'; import { constantstyles } from '../../constants/constanstStyles'; import { theme } from '../../theme'; import { Card, Title, Paragraph } from 'react-native-paper'; import ButtonComponent from '../Button/Button'; import { Evil, IonIcon, MaterialCommunityIcon } from '../Icons/Icons'; import { useDispatch, useSelector } from 'react-redux'; import { acceptRequest, cancelRequest, completeRequest, } from '../../redux/slices/healthWorkerSlice/actions'; import Loading from '../Indicator/Loading'; // import Call API import call from 'react-native-phone-call'; const HealthWorkerFlatList = ({ request }) => { const dispatch = useDispatch(); const [loading, setLoading] = useState(false); const { healthWorker } = useSelector( ({ healthWorkerSlice }) => healthWorkerSlice ); //cancel request const onCancelRequest = (item) => { //alert(item) dispatch(cancelRequest(item)); }; //cancel request //accept request const onAcceptRequest = (item) => { setLoading(true); dispatch(acceptRequest(item)); }; //accept requesst //check request useEffect(() => { if (healthWorker.acceptRequestInfo !== null) { setLoading(false); } if (healthWorker.completeRequest !== null) { setLoading(false); } }, [healthWorker.acceptRequestInfo, healthWorker.completeRequest]); //check request //complete request const oncompleteRequest = (item) => { setLoading(true); dispatch(completeRequest(item)); }; //complete request //make phone call const onMakeCall = (value) => { const args = { number: value, prompt: true, }; // Make a call call(args).catch(console.error); }; //make phone call return ( <View> {/*loading*/} {loading && ( <View style={{ marginVertical:20, marginHorizontal:10 }}> <Loading /> </View> )} {/*loading */} <FlatList data={request} keyExtractor={(item) => String(item.client.id)} contentContainerStyle={{ marginVertical: 15, marginHorizontal: 2, }} showsVerticalScrollIndicator={false} ListHeaderComponentStyle={{ marginVertical: 20, }} ListHeaderComponent={ <View style={[ constantstyles.elevatedCard, constantstyles.centerContent, { marginHorizontal: 10, marginTop: 10 }, ]} > <Text style={{ color: theme.colors.primary, fontSize: 17, }} > Current Request </Text> </View> } renderItem={({ item, index }) => ( <Pressable key={item.id} styles={[styles.pressableStyles]}> <Card style={styles.cardStyle} elevation={2}> {/*cardcontent */} <Card.Content> <View style={[ constantstyles.flexStyles, { justifyContent: 'space-between', alignItems: 'center', }, ]} > <Title>{`${item?.client?.fname} ${item?.client?.lname}`}</Title> {/*accept*/} {item?.request?.status == 'pending' ? ( <ButtonComponent mode="outlined" text="Accept" color={`${theme.colors.primary}`} style={{ marginTop: 5, borderRadius: 10, borderWidth: 2, borderColor: theme.colors.primary, height: 35, }} contentStyle={{ fontSize: 8, height: 28, }} onPress={() => onAcceptRequest(item) } /> ) : null} {/*accept */} {/*finish request */} {item?.request?.status == 'accepted' && ( <ButtonComponent mode="outlined" text="Complete" color={`${theme.colors.primary}`} style={{ marginTop: 5, borderRadius: 10, borderWidth: 2, borderColor: theme.colors.primary, height: 35, }} contentStyle={{ fontSize: 8, height: 28, }} onPress={() => oncompleteRequest( item ) } /> )} {/*finish request */} </View> {/*phone */} <Paragraph style={styles.paragraphStyle}> {/* <AntDesignIcon name="phone" size={20} color={theme.colors.primary} /> <Text style={styles.wordStyles}> {item?.client.phone} </Text> */} <ButtonComponent mode="outlined" text="Call" color={`${theme.colors.primary}`} style={{ marginTop: 5, borderRadius: 10, borderWidth: 2, borderColor: theme.colors.primary, height: 35, width: 150, }} contentStyle={{ flexDirection: 'row-reverse', width: 150, }} onPress={() => onMakeCall(item?.client?.phone) } fullWidth icon="phone-outgoing" /> </Paragraph> {/*phone */} <Paragraph style={styles.paragraphStyle}> <MaterialCommunityIcon name="email-outline" size={20} color={theme.colors.primary} /> <Text style={styles.wordStyles}> {item?.client?.email} </Text> </Paragraph> {/*addresss */} <Paragraph style={styles.paragraphStyle}> <Evil name="location" size={25} color={theme.colors.primary} /> <Text style={styles.wordStyles}> {item?.client?.address} </Text> </Paragraph> {/*address */} {/*work needed */} <View style={[ constantstyles.flexStyles, { justifyContent: 'space-between', alignItems: 'center', }, ]} > {/*worker */} <Paragraph style={styles.paragraphStyle}> <IonIcon name="person-outline" size={22} color={theme.colors.primary} /> <Text style={styles.wordStyles}> {`${item?.client?.health_worker} (needed)`} </Text> </Paragraph> {/*worker */} {item?.request?.status == 'pending' ? ( <ButtonComponent mode="flat" text="Cancel" color={`${theme.colors.error}`} style={{ marginTop: 5, borderRadius: 10, borderWidth: 2, borderColor: theme.colors.error, height: 35, }} contentStyle={{ fontSize: 8, height: 28, }} onPress={() => onCancelRequest(item) } /> ) : null} </View> {/*work neede */} {/*request */} <Paragraph style={styles.paragraphStyle}> <Text style={styles.wordStyles}> Request Status : <Text style={{ color: 'green' }}> {item?.request?.status} </Text> </Text> </Paragraph> {/*request */} </Card.Content> {/*card content */} </Card> </Pressable> )} /> </View> ); }; export default HealthWorkerFlatList; const styles = StyleSheet.create({ cardStyle: { marginHorizontal: 4, marginVertical: 4, borderRadius: 5, padding: 10, borderColor: theme.colors.primary, borderWidth: 0, }, pressableStyles: { marginVertical: 10, }, paragraphStyle: { paddingVertical: 5, }, wordStyles: { fontSize: 14, marginLeft: 20 }, buttonStyle: { borderColor: StyleSheet.hairlineWidth, borderWidth: 2, borderLeftWidth: 0, borderTopLeftRadius: 20, borderBottomLeftRadius: 20, }, buttonStyle1: { borderLeftWidth: 0, borderTopRightRadius: 20, borderBottomRightRadius: 20, }, });
module.exports = { onInput: function(input) { var height = input.height; var width = input.width; var className = input['class']; this.state = { width: width, height: height, lat: input.lat, lng: input.lng, className: className }; }, onMount: function() { var el = this.el; var google = window.google; var lat = this.state.lat; var lng = this.state.lng; // If there is no internet connection then // the Google Maps API will fail to load and // window.google will be undefined if (google && google.maps && google.maps.Map) { var Map = google.maps.Map; var LatLng = google.maps.LatLng; this._map = new Map(el, { zoom: 8, center: new LatLng( lat, lng) }); } else { this.innerHTML = 'Failed to load Google Maps API. Is your internet connection working?'; } } };
import React from "react"; export function Snippet(props){ return ( <p dangerouslySetInnerHTML={{__html:props.snippet}}></p> ) }
import React, { Component } from 'react'; export default class CustomerListGroupItem extends Component { constructor(props) { super(props) this.onDoneClick = this.onDoneClick.bind(this); } onDoneClick(id) { return (e) => {this.props.onDoneClick(id)} } render() { let data = this.props.data; return ( <a href="#" className="list-group-item"> <i className="fa fa-user"></i> &nbsp; {data.name} </a> ); } }
import Incorrect from './Incorrect' export default Incorrect
// Load required modules... var mongoose = require('mongoose'); // Define the schema for our abbreviation model var abbreviationSchema = mongoose.Schema({ uid: String, abbr: String, full: String }); // Create the model for abbreviations and expose it to our app module.exports = mongoose.model('Abbreviation', abbreviationSchema);
var ViveControls = function() { // Constants var CONTROLLER_PATH = '/models/'; var CONTROLLER_OBJ_FILE = 'vr_controller_vive_1_5.obj'; var CONTROLLER_TEXTURE_FILE = 'onepointfive_texture.png'; var CONTROLLER_SPEC_FILE = 'onepointfive_spec.png'; var UP_VECTOR = new THREE.Vector3( 0, 1, 0 ); // Globals var controls; var controller1; var controller2; function init( camera, scene ) { controls = new THREE.VRControls( camera ); controls.standing = true; controller1 = initController( 0 ); controller2 = initController( 1 ); scene.add( controller1 ); scene.add( controller2 ); loadControllerModels(); } function initController( index ) { var controller = new THREE.PaintViveController( index ); controller.standingMatrix = controls.getStandingMatrix(); controller.userData.points = [ new THREE.Vector3(), new THREE.Vector3() ]; controller.userData.matrices = [ new THREE.Matrix4(), new THREE.Matrix4() ]; return controller; } function loadControllerModels() { var loader = new THREE.OBJLoader(); loader.setPath( CONTROLLER_PATH ); loader.load( CONTROLLER_OBJ_FILE, function ( object ) { var loader = new THREE.TextureLoader(); loader.setPath( CONTROLLER_PATH ); var controller = object.children[ 0 ]; controller.material.map = loader.load( CONTROLLER_TEXTURE_FILE ); controller.material.specularMap = loader.load( CONTROLLER_SPEC_FILE ); controller.castShadow = true; controller.receiveShadow = true; // var pivot = new THREE.Group(); // var pivot = new THREE.Mesh( new THREE.BoxGeometry( 0.01, 0.01, 0.01 ) ); var pivot = new THREE.Mesh( new THREE.IcosahedronGeometry( 0.002, 2 ) ); pivot.name = 'pivot'; pivot.position.y = -0.016; pivot.position.z = -0.043; pivot.rotation.x = Math.PI / 5.5; controller.add( pivot ); controller1.add( controller.clone() ); pivot.material = pivot.material.clone(); controller2.add( controller.clone() ); } ); } function update() { controls.update(); updateController( controller1 ); updateController( controller2 ); } function updateController( controller ) { controller.update(); var pivot = controller.getObjectByName( 'pivot' ); if ( pivot ) { pivot.material.color.copy( controller.getColor() ); var matrix = pivot.matrixWorld; var point1 = controller.userData.points[ 0 ]; var point2 = controller.userData.points[ 1 ]; var matrix1 = controller.userData.matrices[ 0 ]; var matrix2 = controller.userData.matrices[ 1 ]; point1.setFromMatrixPosition( matrix ); matrix1.lookAt( point2, point1, UP_VECTOR ); if ( controller.getButtonState( 'trigger' ) ) { // TODO: Refactor to integrate better with Painter class //Core.paintStroke( controller.getColor().getHex(), point1, point2, matrix1, matrix2, 0.01 ); Core.updatePainterVive( [ [ controller.getColor().getHex(), point1, point2, matrix1, matrix2, 0.01 ] ] ) } point2.copy( point1 ); matrix2.copy( matrix1 ); } } return { init: init, update: update }; }();
// If you ever had to get the maxiumum number from an array then you are probably familiar with the good ole' Math.max.apply() function that takes a this argument and an array. A typical implementation would look like this: // // var myArray = [1, 42, 112, 32, 21] // var max = Math.max.apply(null, myArray) //= 112 // That's too easy though. Let's replace the Math.max function with our own solution that uses recursion! Yay! // // Write a function called max that takes one argument, an array, and returns the maximum value of that array. // // Rules: // // You cannot use Math.max (duh!) // You can only use const to declare any variables // You cannot use any loops like for or while // You cannot use any other argument than the one passed to the function // If the array is empty then return -Infinity, just like with Math.max.apply(null, []) // You cannot use any Array.prototype methods like forEach, map, filter, or reduce // Good luck! function max(array) { function max2(arr) { if (arr[0] < arr[1]) { arr.splice(0, 1); } else { arr.splice(1, 1); } return arr; } if (array[0] === undefined) { return -Infinity; } else if (array.length === 1) { return array[0]; } else { max2(array); } }
// @flow import * as React from 'react'; import { Dimensions, Platform, StatusBar, KeyboardAvoidingView } from 'react-native'; import GradientBackground from '../../elements/GradientBackground'; import NextFloatingButton from '../../elements/NextFloatingButton'; import Input from '../../elements/Input'; import IconButton from '../../elements/IconButton'; import Button from '../../elements/Button'; import CreditCardIcon from '../../elements/svg/CreditCardIcon'; import WaterIcon from '../../elements/svg/WaterIcon'; import LightIcon from '../../elements/svg/LightIcon'; import GasIcon from '../../elements/svg/GasIcon'; import HeaderLogin from '../../elements/HeaderLogin'; import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'; import styled from 'styled-components/native'; import Snackbar from 'react-native-snackbar'; import { SafeArea, LOGO_HELPER } from '../common/utils'; import Icon from '../../elements/Icon'; const { width } = Dimensions.get('window'); const LabelsSize = width - 40; const StyledButton = styled(Button)` width: ${props => props.width}; border-width: 2; border-color: ${props => props.border}; `; const InputWrapper = styled.View` flex: 1; align-items: center; justify-content: center; padding-top: 40; `; const SelectLabelContainer = styled.View` width: ${LabelsSize}; flex-direction: row; align-items: center; justify-content: space-around; margin-vertical: 10; `; const InputLabel = styled.Text` font-size: 18; font-weight: bold; color: white; margin-top: 10; text-align: left; width: ${LabelsSize}; padding-left: 10; `; const statusValues = { PAID: 'PAID', NOT_PAID: 'NOT_PAID', }; const typeValues = { CREDIT_CARD: 'CREDIT_CARD', LIGHT: 'LIGHT', GAS: 'GAS', WATER: 'WATER', BILL: 'BILL', }; const InputWidth = width - 40; class AddExpense extends React.Component { state = { title: null, value: null, status: null, type: null, date: null, error: false, }; static navigationOptions = { header: null, }; showMessage = message => { this.setState({ error: true, }); setTimeout(() => { this.setState({ error: false, }); }, 3000); return Snackbar.show({ title: message, duration: Snackbar.LENGTH_LONG, action: { title: 'OK', color: 'red', onPress: () => { this.setState({ error: false, }); }, }, }); }; setStatus = (status: string) => { this.setState({ status, }); }; setType = (type: string) => { this.setState({ type, }); }; login = () => { const { email, password } = this.state; if (email === null || password === null) { return this.showMessage('Please fill all the fields'); } this.props.navigation.goBack(); }; render() { const { title, value, status, type, error } = this.state; return ( <GradientBackground style={{ flex: 1, }} error={error} > <StatusBar backgroundColor={error ? '#F90000' : '#00C5F9'} barStyle="light-content" /> <SafeArea /> <HeaderLogin title="Add a new Expense" backAction={() => this.props.navigation.pop()} logo={LOGO_HELPER.CLOSE} /> <KeyboardAwareScrollView style={{ flex: 1, }} > <InputWrapper> <Input label="Title" textColor="#fff" value={title} onChangeText={title => this.setState({ title })} width={InputWidth} /> <Input label="Value" textColor="#fff" value={value} onChangeText={value => this.setState({ value })} width={InputWidth} keyboardType="numeric" /> <InputLabel>Type of Expense</InputLabel> <SelectLabelContainer> <IconButton onPress={() => this.setType(typeValues.CREDIT_CARD)} border={type === typeValues.CREDIT_CARD ? 'white' : 'rgba(216, 216, 216, 0.6)'} backgroundColor="rgba(216, 216, 216, 0.6)" > <CreditCardIcon size={30} color="white" /> </IconButton> <IconButton onPress={() => this.setType(typeValues.LIGHT)} border={type === typeValues.LIGHT ? 'white' : 'rgba(216, 216, 216, 0.6)'} backgroundColor="rgba(216, 216, 216, 0.6)" > <LightIcon size={30} color="white" /> </IconButton> <IconButton onPress={() => this.setType(typeValues.GAS)} border={type === typeValues.GAS ? 'white' : 'rgba(216, 216, 216, 0.6)'} backgroundColor="rgba(216, 216, 216, 0.6)" > <GasIcon size={30} color="white" /> </IconButton> <IconButton onPress={() => this.setType(typeValues.WATER)} border={type === typeValues.WATER ? 'white' : 'rgba(216, 216, 216, 0.6)'} backgroundColor="rgba(216, 216, 216, 0.6)" > <WaterIcon size={30} color="white" /> </IconButton> <IconButton onPress={() => this.setType(typeValues.BILL)} border={type === typeValues.BILL ? 'white' : 'rgba(216, 216, 216, 0.6)'} backgroundColor="rgba(216, 216, 216, 0.6)" > <Icon width={30} height={31} icon={LOGO_HELPER.BILL} color="white" /> </IconButton> </SelectLabelContainer> <InputLabel>Expense Status</InputLabel> <SelectLabelContainer> <StyledButton color="rgba(216, 216, 216, 0.6)" textColor="white" border={status === statusValues.NOT_PAID ? 'white' : 'rgba(216, 216, 216, 0.6)'} width={InputWidth / 2 - 10} title="Not Paid" onPress={() => this.setStatus(statusValues.NOT_PAID)} /> <StyledButton color="rgba(216, 216, 216, 0.6)" textColor="white" border={status === statusValues.PAID ? 'white' : 'rgba(216, 216, 216, 0.6)'} width={InputWidth / 2 - 10} title="Paid" onPress={() => this.setStatus(statusValues.PAID)} /> </SelectLabelContainer> </InputWrapper> </KeyboardAwareScrollView> <NextFloatingButton color="white" iconColor={error ? 'red' : '#2EDAD0'} onPress={this.login} logo={LOGO_HELPER.ADD} /> {Platform.OS === 'ios' && <KeyboardAvoidingView />} </GradientBackground> ); } } export default AddExpense;
/*$(document).ready(function(){ var selectedCountry = $('select#location').children("option:selected").val(); if(selectedCountry=="Select a Location"){ //$('select#location').addClass("errorValidation"); $('.requestRefillbtn').prop("disabled",true); } $('select#location').change(function(){ $('.requestRefillbtn').prop("disabled",false); }) $(".requestRefillbtn").click(function(){ var selectedCountry = $('select#location').children("option:selected").val(); if(selectedCountry=="Millwoods"){ location.href="./millwoods.html"; } if(selectedCountry=="Chinatown"){ window.location.href="./chinatown.html"; } if(selectedCountry=="Downtown"){ window.location.href="./downtown.html"; } if(selectedCountry=="Highway 16"){ window.location.href="./spruce Grove.html"; } if(selectedCountry=="Salvation"){ window.location.href="./salvation.html"; } }); }); */ function openNav() { document.getElementById("mySidenav").style.width = "95%"; } function closeNav() { document.getElementById("mySidenav").style.width = "0"; }
// 公共接口集合 import {onGet, onPost} from './main' // 获取菜单数据 export const getMenuData = params => { return onGet('sso/main/menuData', params) } // 获取用户信息 export const getUserInfo = params => { return onGet('sso/queryUserInfo', params) } // 注销 export const logout = params => { return onPost('', params) } // 解锁 export const unlock = params => { return onPost('sso/unlock', params) } // 获取页面按钮权限信息 export const getBtnPermission = params => { return onGet('manage/adminPermission/getBtnPermission', params) } // 查询所有城市信息 export const queryCitySelect = params => { return onGet('manage/commonselect/queryCitySelect', params) } /** * 获取自定义动态下拉选项 * @param menuName 菜单 * @param params 参数 */ export const getSelectValue = (params) => { return onGet(`manage/dynamicConfigure/getSelectValue/one`, params) } /** * 获取区间值 * @param params 参数 */ export const getRegionValue = params => { return onGet('manage/dynamicConfigure/getRegionValue/one', params) } /** * 获取自定义动态表单字段 * @param params 参数 */ export const getCustomField = (params) => { return onGet('manage/dynamicConfigure/getCustomField', params) } // 查询所有城市信息 export const getCitySelectUrl = 'manage/commonselect/queryOpenCity' // 查询行政区、片区、小区 级联数据 export const queryCommunitySelectWithRegion = 'manage/commonselect/queryOpenCityCountyRegionCommunity'
/** * @file 路径分割 * @author mengke01(kekee000@gmail.com) */ define( function (require) { var bezierQ2Split = require('math/bezierQ2Split'); var getBezierQ2T = require('math/getBezierQ2T'); /** * 按索引号排序相交点,这里需要处理曲线段上有多个交点的问题 * * @param {Array} path 路径 * @param {Array} joint 交点数组 * @return {Array} 排序后 */ function sortJoint(path, joint) { var length = path.length; return joint.sort(function (p0, p1) { // 如果交点需要不相等,则按小到大排序 if (p0.index !== p1.index) { return p0.index - p1.index; } // 相等,则同一段上有多个交点,按照与原点距离排序 var cur = path[p0.index]; var next = p0.index === length - 1 ? path[0] : path[p0.index + 1]; // 直线 if (cur.onCurve && next.onCurve) { return Math.pow(p0.x - cur.x, 2) + Math.pow(p0.y - cur.y, 2) - (Math.pow(p1.x - cur.x, 2) + Math.pow(p1.y - cur.y, 2)); } else if (!cur.onCurve) { var prev = p0.index === 0 ? path[length - 1] : path[p0.index - 1]; var t1 = getBezierQ2T(prev, cur, next, p0); var t2 = getBezierQ2T(prev, cur, next, p1); return t1 === t2 ? 0 : t1 < t2 ? -1 : 1; } }); } /** * 分割路径 * * @param {Array} path 路径 * @param {Array} joint 分割点数组 * joint结构 * { * x: , // x坐标 * y: , //y坐标 * index: // 交点的线段起始点索引 * } * @param {string} indexProp 索引号 * @return {Array} 分割后的路径集合 */ function pathSplit(path, joint) { joint = sortJoint(path, joint); var jointOffset = 0; // 用来标记插入点产生的偏移 var i; var l; // 插入分割点 for (i = 0, l = joint.length; i < l; i++) { var length = path.length; var p = joint[i]; p.index += jointOffset; var cur = p.index; var next = cur === length - 1 ? 0 : cur + 1; // 直线 if (path[cur].onCurve && path[next].onCurve) { // 在开始点相交 if (Math.abs(path[cur].x - p.x) < 0.001 && Math.abs(path[cur].y - p.y) < 0.001) { p.index = cur; continue; } // 在结束点相交 if (Math.abs(path[next].x - p.x) < 0.001 && Math.abs(path[next].y - p.y) < 0.001) { p.index = next; continue; } path.splice(cur + 1, 0, { x: p.x, y: p.y, onCurve: true }); p.index = cur + 1; jointOffset++; } // 贝塞尔开始点,插入2个节点 else if (!path[cur].onCurve) { var prev = cur === 0 ? length - 1 : cur - 1; // 在开始点相交 if (Math.abs(path[prev].x - p.x) < 0.001 && Math.abs(path[prev].y - p.y) < 0.001) { p.index = prev; continue; } // 在结束点相交 if (Math.abs(path[next].x - p.x) < 0.001 && Math.abs(path[next].y - p.y) < 0.001) { p.index = next; continue; } var bezierArray = bezierQ2Split(path[prev], path[cur], path[next], p); if (!bezierArray) { throw 'can\'t find bezier split point'; } path.splice(cur, 1, bezierArray[0][1], { x: p.x, y: p.y, onCurve: true }, bezierArray[1][1] ); p.index = cur + 1; jointOffset += 2; } else { throw 'joint incorrect'; } } // 这里需要重新筛选排序 joint.sort(function (p0, p1) { return p0.index - p1.index; }); // 分割曲线 var splitedPaths = []; var start; var end; for (i = 0, l = joint.length - 1; i < l; i++) { start = joint[i]; end = joint[i + 1]; splitedPaths.push(path.slice(start.index, end.index + 1)); } // 闭合轮廓 start = end; end = joint[0]; splitedPaths.push(path.slice(start.index).concat(path.slice(0, end.index + 1))); return splitedPaths.filter(function (path) { return path.length > 2; }); } return pathSplit; } );
import {getConstants} from '../shared/utils' export default getConstants( [ 'SOME_ACTION' ] )
const express = require("express"); const router = express.Router(); const User = require("../models/user"); const Profile = require("../models/profile"); const http = require("follow-redirects").http; const logger = require("../util/logger"); const bcrypt = require("bcryptjs"); const { adminRequired, authRequired } = require("../middleware/auth"); var multer = require("multer"); const getConfig = require("../util/config"); const fs = require("fs"); const path = require("path"); const uploadPath = process.pkg ? path.join(path.dirname(process.execPath), `./config/uploads`) : path.join(__dirname, `../config/uploads`); router.get("/thumb/:id", async (req, res) => { let userData = false; try { userData = await User.findOne({ id: req.params.id }); } catch (err) { res.json({ error: err }); return; } if (userData) { if (userData.custom_thumb) { res.sendFile(`${uploadPath}/${userData.custom_thumb}`); return; } let url = userData.thumb; var options = { host: "plex.tv", path: url.replace("https://plex.tv", ""), method: "GET", headers: { "content-type": "image/png", }, }; var request = http .get(options, function (response) { res.writeHead(response.statusCode, { "Content-Type": response.headers["content-type"], }); response.pipe(res); }) .on("error", function (e) { logger.log( "warn", "ROUTE: Unable to get user thumb - Got error: " + e.message, e ); }); request.end(); } }); router.get("/quota", authRequired, async (req, res) => { if (!req.jwtUser) { res.sendStatus(404); return; } const user = await User.findOne({ id: req.jwtUser.id }); if (!user) { res.sendStatus(404); return; } const profile = user.profile ? await Profile.findById(user.profile) : false; let total = 0; let current = user.quotaCount ? user.quotaCount : 0; if (profile) { total = profile.quota ? profile.quota : 0; } res.json({ current: current, total: total, }); }); router.use(authRequired); router.get("/all", adminRequired, async (req, res) => { try { userData = await User.find(); } catch (err) { res.json({ error: err }); return; } if (userData) { let data = Object.values(Object.assign(userData)); Object.keys(data).map((u) => { let user = data[u]; if (user) { if (user.password) user.password = "removed"; } }); res.json(data); } else { res.status(404).send(); } }); router.get("/:id", adminRequired, async (req, res) => { try { userData = await User.findOne({ id: req.params.id }); } catch (err) { res.json({ error: err }); return; } if (userData) { if (userData.password) userData.password = "removed"; res.json(userData); } else { res.status(404).send(); } }); router.post("/create_custom", adminRequired, async (req, res) => { let user = req.body.user; if (!user) { res.status(500).json({ error: "No user details", }); } let dbUser = await User.findOne({ $or: [ { username: user.username }, { email: user.email }, { title: user.username }, ], }); if (dbUser) { res.status(200).json({ error: "User exists, please change the username or email", }); return; } else { try { let newUser = new User({ id: user.id, title: user.username, username: user.username, email: user.email, recommendationsPlaylistId: false, thumb: false, password: bcrypt.hashSync(user.password, 10), altId: user.linked, custom: true, }); await newUser.save(); res.status(200).json(newUser); } catch (err) { logger.log("error", "ROUTE: Unable to create custom user"); logger.log({ level: "error", message: err }); res.status(500).json({ error: "Error creating user", }); } } }); router.post("/edit", adminRequired, async (req, res) => { let user = req.body.user; if (!user) { res.status(500).json({ error: "No user details", }); } try { let userObj = { email: user.email, role: user.role, profile: user.profile, disabled: user.disabled, }; if (user.password) { userObj.password = bcrypt.hashSync(user.password, 10); } if (user.clearPassword) { userObj.password = null; } if (user.role === "admin" && !user.password) { let prefs = getConfig(); userObj.password = prefs.adminPass.substring(0, 3) === "$2a" ? prefs.adminPass : bcrypt.hashSync(prefs.adminPass, 10); } if (user.role === "admin" && user.email) { updateConfig({ adminEmail: user.email, }); } await User.findOneAndUpdate( { _id: user.id }, { $set: userObj, }, { new: true, useFindAndModify: false } ); res.json({ message: "User edited", }); } catch (err) { logger.log({ level: "error", message: err }); res.status(500).json({ error: "Error editing user", }); } }); router.post("/bulk_edit", adminRequired, async (req, res) => { let users = req.body.users; let enabled = req.body.enabled; let profile = req.body.profile; if (!users) { res.status(500).json({ error: "No user details", }); return; } try { await Promise.all( users.map(async (user) => { await User.updateMany( { _id: user, }, { $set: { profile: profile, disabled: enabled ? false : true, }, } ); }) ); res.json({ message: "Users saved", }); } catch { res.status(500).json({ error: "Error editing user", }); } }); router.post("/delete_user", adminRequired, async (req, res) => { let user = req.body.user; if (!user) { res.status(500).json({ error: "No user details", }); return; } if (!user.custom) { res.status(401).json({ error: "Cannot delete non custom users", }); return; } try { await User.findByIdAndDelete(user._id); res.json({ message: "User deleted", }); } catch { res.status(500).json({ error: "Error deleting user", }); } }); let storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, uploadPath); }, filename: function (req, file, cb) { req.newThumb = file.fieldname + "-" + Date.now() + path.extname(file.originalname); cb(null, req.newThumb); }, }); router.use((req, res, next) => { if (fs.existsSync(uploadPath)) { next(); return; } logger.info("ROUTE: Creating upload dir"); fs.mkdirSync(uploadPath); logger.info("ROUTE: Upload dir created"); next(); }); var upload = multer({ storage }).single("thumb"); router.use((req, res, next) => { upload(req, res, function (err) { if (err instanceof multer.MulterError) { logger.log({ level: "error", message: err }); logger.warn("ROUTE: A Multer error occurred when uploading."); res.sendStatus(500); return; } else if (err) { logger.log({ level: "error", message: err }); logger.warn("ROUTE: An unknown error occurred when uploading."); res.sendStatus(500); return; } logger.verbose("ROUTE: Multer image parsed"); next(); }); }); router.post("/thumb/:id", adminRequired, async (req, res) => { if (!req.params.id) { logger.warn("ROUTE: No user ID"); res.sendStatus(400); return; } try { await User.findOneAndUpdate( { id: req.params.id }, { $set: { custom_thumb: req.newThumb, }, }, { useFindAndModify: false } ); res.sendStatus(200); } catch (err) { logger.log({ level: "error", message: err }); logger.warn("ROUTE: Failed to update user thumb in db"); res.sendStatus(500); } }); async function updateConfig(obj) { let project_folder, configFile; if (process.pkg) { project_folder = path.dirname(process.execPath); configFile = path.join(project_folder, "./config/config.json"); } else { project_folder = __dirname; configFile = path.join(project_folder, "../config/config.json"); } let userConfig = false; try { userConfig = fs.readFileSync(configFile); let configParse = JSON.parse(userConfig); let updatedConfig = JSON.stringify({ ...configParse, ...obj }); fs.writeFile(configFile, updatedConfig, (err) => { if (err) { logger.error("ROUTE: Usr unable to update config"); logger.log({ level: "error", message: err }); } }); // return JSON.parse(userConfig); } catch (err) { logger.error("ROUTE: Usr unable to update config"); logger.log({ level: "error", message: err }); } } module.exports = router;
document.getElementById("new-folder").addEventListener("blur", request); document.getElementById("upload-file").addEventListener("change", upload); var divOrders = document.querySelectorAll("div[order]"); var clickOrders = document.querySelectorAll(".click"); divOrders.forEach(element => { let margingLeft = element.getAttribute("order")*16 - 16; element.style.marginLeft= `${margingLeft}px`; if (element.getAttribute("order")>1){ element.classList.add("hidden"); } }); clickOrders.forEach(element => { element.parentNode.addEventListener("click", togAndHide); }); function togAndHide(e) { e.target.firstChild.classList.toggle("fa-caret-right"); e.target.firstChild.classList.toggle("fa-caret-down"); hideSibling(e.target.parentNode); } function hideSibling(origin) { var treeChilds = document.getElementsByClassName("tree-section")[0].children; let i = 0; let index = 10000; while (i<treeChilds.length) { console.log(origin.getAttribute("order")); console.log(treeChilds[i].getAttribute("order")); if (origin.getAttribute("me") == treeChilds[i].getAttribute("me")){ index = i; } if (i>index && parseInt(treeChilds[i].getAttribute("order"))===parseInt(origin.getAttribute("order"))+1){ treeChilds[i].classList.toggle("hidden"); }else if (i>index && origin.getAttribute("order") === treeChilds[i].getAttribute("order")) { break; } i++; } } function request() { var whereToSave = document.getElementById("new-folder").getAttribute("query"); var newNameToSave = document.getElementById("new-folder").value; var data ={ query: whereToSave, newName: newNameToSave, } axios.post("./php/create-folder.php", JSON.stringify(data)) .then(response => { location.reload(); console.log(response); }).catch(error => { console.log(error); }) } function upload() { document.getElementById("upload-form").submit(); }
const _dateToString = (date) => { try { const string = new Intl.DateTimeFormat([], { weekday: "long", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" }).format(new Date(date)); return string; } catch(e) { return null; } }; export default _dateToString;
import React from 'react' const Movie = (props) => { return ( <div className="col s12 m6 l3"> <div className="card"> <div className="card-image waves-effect"> { props.image != null ? <img src={`https://image.tmdb.org/t/p/w185${props.image}`} alt="Movie image" style={{height: 300}}></img> : <img src={`https://ru.uoslab.com/images/tovary/no_image.jpg`} alt='Movie image'></img> } </div> <div className="card-content"> <p><a href="#" onClick={() => {props.viewMovieInfo(props.movieId); props.getSimilarMovies(props.movieId);}} >More info</a></p> </div> </div> </div> ) } export default Movie
var util=require('util'); var qs=require('querystring'); var https=require('https'); var Resource=require('deployd/lib/resource'); function ElasticEmail(){ Resource.apply(this, arguments); } util.inherits(ElasticEmail,Resource); ElasticEmail.prototype.clientGeneration=true; ElasticEmail.basicDashboard={ settings:[ { name:'username', type:'text', description:'Elastic account username' }, { name:'key', type:'text', description:'Elastic api key' }, { name:'defaultFromName', type:'text', description:'The default FROM name' }, { name:'defaultFromEmail', type:'text', description:'The default FROM email address' }, { name:'defaultSubject', type:'text', description:'The default subject ' }, { name:'developmentMode', type:'checkbox', description:'if true then it will print emails to console instead of sending them' } ] }; ElasticEmail.prototype.handle=function(ctx,next){ if(ctx.req && ctx.req.method!='POST'){ return next(); } if(!this.config.username || !this.config.key){ console.log('Elastic username & key missing!'); next(); } var options=ctx.query || {}; options.fromName=options.fromName || this.config.defaultFromName; options.fromEmail=options.fromEmail || this.config.defaultFromEmail; options.subject=options.subject || this.config.defaultSubject; var errors={}; if(!options.to){ errors.to=' \'to\' is required'; } if(!options.fromEmail){ errors.from=' \'from\' is required'; } if(!options.subject){ errors.subject=' \'subject\' is required'; } if(!options.text && !options.html){ errors.content=' \'text\' or \'html\' is required '; } if(errors.length>0){ return ctx.done({statusCode: 400, errors: errors}); } var post_data = qs.stringify({ 'username' : this.config.username, 'api_key': this.config.key, 'from': options.fromEmail, 'from_name' : options.fromName, 'to' : options.to, 'subject' : options.subject, 'body_html' : options.html, 'body_text' : options.text }); if(this.config.developmentMode){ console.log(post_data); return ctx.done(null); } var post_options = { host: 'api.elasticemail.com', path: '/mailer/send', port: '443', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': post_data.length } }; var result = ''; // Create the request object. var post_req = https.request(post_options, function(res) { res.setEncoding('utf8'); res.on('data', function (chunk) { result = chunk; }); res.on('error', function (e) { result = 'Error: ' + e.message; }); }); // Post to Elastic Email post_req.write(post_data); post_req.end(); return ctx.done(null,{message: result}); } module.exports=ElasticEmail;
import React from 'react'; import * as Components from '../components'; import { HeroContent } from '../content'; import { Container, Row, Col, Button } from 'react-bootstrap'; import bgleft from '../assets/bgleft.png'; import bgright from '../assets/bgright.png'; const containerStyle = { 'padding-top': '10vh', 'height': '72vh', 'background-image': `url(${bgleft}), url(${bgright})`, 'background-repeat': 'no-repeat, no-repeat', 'background-position': 'left, right', 'background-size': '50vw, 50vw' }; const rowStyle = { 'padding-bottom': '5vh' } const columnStyle = { } const btnStyle = { 'padding': '10px 20px', 'font-size': '30px', 'border-radius': '10px', 'width': '60%', 'color':'white', 'font-weight':'bold', 'border-color': '#66FCF1' } const scrollStyle = { 'behavior': 'smooth', 'buttonBackgroundColor': '66FCF1', 'iconType': 'arrow-down', 'fontSize': '50px', 'buttonColor': 'white', 'targetId': 'Line', } class Component extends React.Component { render() { return ( <Container fluid style={containerStyle}> <Row className={'justify-content-md-center'} style={rowStyle}> <Col lg="4" className={'text-center'} style={columnStyle}> <Components.H1 content={HeroContent.title} /> </Col> </Row> <Row className={'justify-content-md-center'} style={rowStyle}> <Col lg="7" className={'text-center'} style={columnStyle}> <Components.Subhead content={HeroContent.content} /> </Col> </Row> <Row className={'justify-content-md-center'} style={rowStyle}> <Col lg="3" className={'text-center'} style={columnStyle}> <a href="#" type="button" class="btn btn-outline-info btn-lg" style={btnStyle}>Contact Us</a> </Col> </Row> </Container> ); } } export const HeroContainer = () => <Component />
const express = require('express'); const app = express(); app.use(express.json()); const port = 3000; app.get('/ping', (req, res) => { res.send("<h1>Pong</h1>"); }); app.get('/json', (req, res) => { res.status(200).json({nome: "Paulo Ricardo", Idade: 27, EstadoCivil: "Casado"}); }); app.get('/funcionario/:id/dependentes/', (req, res) => { res.status(200).json( [ {nome: "Rafaela Roque", Idade: 26, funcionarioId: req.params.id}, {nome: "Ana luiza Noé", Idade: 3, funcionarioId: req.params.id}] ); }); app.post('/post/', (req, res) => { console.log(req.body); res.send('Valor Enviado: ' + JSON.stringify(req.body)); }) app.get('*', (req, res) => { res.status(404).send("Rota inexistente!"); }); app.listen(port, () => { console.log(`Servidor rodando na porta: ${port}`); });
'use strict'; import Base from '../base.js'; export default class extends Base { /** * index action * 获取视频列表 * @return {Promise} [] */ async indexAction() { let class_id = this.post('class_id');//分类id let is_group = this.post('is_group');//分组or内容 let orderType = Number(this.post('order'));//排序规则 let is_top = Number(this.post('is_top'));//是否只查询置顶 let is_banner = Number(this.post('is_banner')); let like = this.post('like');//{title: ['like', '%welefen%']} let page = this.post('page'); let size = this.post('size'); let where = {}; let order = {}; //like查询 if(!think.isEmpty(like)){ try { where['title'] = ['like',like]; } catch (e) { console.error(e) } } //指定获取某个分类下的内容 if (!think.isEmpty(class_id)) { where['class_id'] = class_id; } //是筛选分组还是视频,为空则全部 if (!think.isEmpty(is_group)) { where['is_group'] = is_group; } //排序规则 if (orderType == 1) { //时间倒序 order['time'] = 'DESC'; } else if (orderType == -1) { //时间正序 order['time'] = 'ASC'; } else if (orderType == 2) { //热门倒序排序 order['hot'] = 'DESC'; } else if (orderType == -2) { order['hot'] = 'ASC'; } //筛选置顶 if (is_top == 1) { where['is_top'] = 1; } //是否是banner if (is_banner == 1) { where['is_banner'] = 1; } console.log(where); console.log(order); let video = this.model('video'); let data = await video.showList(where, order, page, size); return this.success(data); } }
/** * @param {Array<number>} A * @return {Array<Array<number>>} */ const threeSum = (A) => { // [-3, -1, 1, 0, 2, 10, -2, 8] // sort // [-3, -2, -1, 1, 0, 2, 8, 10] // [-20 ,-3, -2, -1, 1, 0, 2, 8, 10] // left, middle, right pointers // for each left // if l + m + r is zero then add it into result // if less than 0 then increase middle // if more than 0 then decrease right // if middle and prev are same iterate to right // if right and next are same iterate to left A = A.sort((a, b) => a - b); let result = []; for (let left = 0; left < A.length - 2; left++) { if (A[left] > 0) { return result; } if (left > 0 && A[left] == A[left + 1]) { continue; } let middle = left + 1; let right = A.length - 1; while (middle < right) { let total = A[left] + A[middle] + A[right]; if (total === 0) { result.push([A[left], A[middle], A[right]]); middle++; right--; while (middle < right && A[middle] === A[middle - 1]) { middle++; } while (right > middle && A[right] === A[right + 1]) { right--; } } else if (total < 0) { middle++; } else { right--; } } } return result; }; let result = threeSum([ 0, 2, 0, 2, 0, 0, 3, 1, -3, 3, 0, -3, 2, 2, -1, 4, 2, -4, 3, 0, -4, 2, 2, -3, 1, 4, 0, 3, 1, -2, 1, 3, -4, 4, 2, -4, 4, 0, -3, 2 ]); console.log(JSON.stringify(result));
import DS from 'ember-data'; export default DS.RESTAdapter.extend({ namespace: 'api', host:'http://ember-node-blog-miauwi.c9users.io', session: Ember.inject.service(), headers: Ember.computed('session.token', function () { if (this.get('session.token') !== null) { return { 'Authorization': `Bearer ${this.get('session.token')}` }; } }) });
"use strict"; import { NavbarTop } from "./navbarTop.js"; import { NavbarBottom } from "./navbarBottom.js"; import { localeString, localeStringArray, Locale, navbarButtons, } from "./locale.js"; import { Setting } from "./setting.js"; import { setContentHeight } from "./pattern.js"; const divOutlaySettings = document.getElementById("outlaySettings"); export class OutlaySettings { static async displayData() { Setting.setWindowOnload("OutlaySettings"); NavbarTop.show({ menu: { buttonHTML: "&#9776;", content: [ { innerHTML: localeString.utility._capitalize(), href: "#func=OutlayUtils", }, ], }, titleHTML: localeString.settings._capitalize(), buttons: [], }); NavbarBottom.setActiveButton(navbarButtons.navbarButtonSettings.href); setContentHeight(); for (let div of document.querySelectorAll(".content > div")) { div.style.display = "none"; } { while (divOutlaySettings.firstChild) { divOutlaySettings.removeChild(divOutlaySettings.firstChild); } } { const tableOutlaySettings = document.createElement("TABLE"); divOutlaySettings.appendChild(tableOutlaySettings); tableOutlaySettings.className = "tableOutlaySettings"; const tbodyOutlaySettings = document.createElement("TBODY"); tableOutlaySettings.appendChild(tbodyOutlaySettings); { // Locale const tr = document.createElement("TR"); tbodyOutlaySettings.appendChild(tr); { const td = document.createElement("TD"); tr.appendChild(td); td.innerHTML = localeStringArray[ Locale.getNavigatorLanguage() ].language._capitalize(); } { const td = document.createElement("TD"); tr.appendChild(td); const selectLangs = document.createElement("SELECT"); td.appendChild(selectLangs); selectLangs.onchange = async function (event) { await Locale.setUserLang( selectLangs.options[selectLangs.selectedIndex].value ); OutlaySettings.displayData(); }; for (let locale of Object.entries(localeStringArray)) { const optionLang = document.createElement("OPTION"); selectLangs.appendChild(optionLang); optionLang.value = locale[0]; optionLang.innerText = locale[1]._langName; if (Locale.getUserLang() === locale[0]) { optionLang.selected = true; } } } } } divOutlaySettings.style.display = "block"; } }
'use strict'; /* 判断字符是否在之前出现过 */ function hasResults(results, char){ for (var i in results){ if(results[i]["name"] == char){ return true; } } return false; } /* 计数 */ function countResults(results, char){ for (var i in results){ if(results[i]["name"] == char){ results[i]["summary"] += 1; } } return results; } /* 将输入的数据中d-5转换成d,d,d,d,d */ function changeInputType(collection){ var newCollection = []; for(var i in collection){ var coll = collection[i].split("") var count = "" for(var j=1;j<coll.length;j++){ if(!isNaN(coll[j])){ // 判断分割的字符是否为数字,是则进行拼接 count += coll[j].toString(); } } if (count){ // 如果count为空,则只需要加一次。 for(var j=0;j<count;j++){ newCollection.push(coll[0]); } }else{ newCollection.push(coll[0]); } } return newCollection; } module.exports = function countSameElements(collection) { var res = []; collection = changeInputType(collection); for(var i in collection){ if(hasResults(res, collection[i])){ res = countResults(res, collection[i]); }else{ res.push({name: collection[i], summary: 1}); } } return res; }
angular.module('app.component1') .controller('DatepickerDemoCtrl', ['$scope', function($scope) { 'use strict'; $scope.today = function() { if ($scope.data.book.year === '') { $scope.data.book.year = new Date(); } }; $scope.data.book.year = new Date().setFullYear($scope.data.book.year); $scope.today(); $scope.open = function() { $scope.status.opened = true; }; $scope.setDate = function(year) { $scope.date = new Date(year); $scope.data.book.year = $scope.date.getFullYear(); }; $scope.dateOptions = { formatYear: 'yyyy', startingDay: 1, minMode: 'year' }; $scope.format = 'yyyy'; $scope.status = { opened: false }; }]);
"use strict"; /******************************************************************** Exercise 1 - Pixel Painter Pro Original code by Pippin Bar Edited by Amanda Clement *********************************************************************/ // Constants const NUM_PIXELS = 1000; const DELAY = 1000; const DEFAULT_COLOR = '#000000'; // To rotate the pixels let rotation = 0; // To track which key user clicks let currentKey = ""; // Set up our starting function for when the page loads window.onload = setup; // rotate() is called when key is pressed down document.addEventListener('keydown', rotate); // typed() is called when key is pressed down document.addEventListener('keydown', typed); // setup // // Adds DIVs to the page along with event listeners that will allow // then to change color on mouseover. function setup() { // A loop that runs once per pixel we need for (let i = 0; i < NUM_PIXELS; i++) { // Create a DIV and store it in a variable let pixel = document.createElement('div'); // Add the 'pixel' class to the new element pixel.setAttribute('class', 'pixel'); document.body.appendChild(pixel); // Add a mouseover handler to the new element pixel.addEventListener('mouseover', paint); // Add a click handler to the new element pixel.addEventListener('click', remove); // Add a mouseover handler to the new element pixel.addEventListener('mouseover', addText); } } // paint // // Called by the mouseover event handler on each pixel. Changes // the pixel's color and sets a timer for it to revert function paint(e) { // e.target contains the specific element moused over so let's // save that into a variable for clarity. let pixel = e.target; // Math.floor to round to nearest integer (downwards) // Math.random returns number in range of 0-1 let r = Math.floor(Math.random() * 255); let b = Math.floor(Math.random() * 255); let g = Math.floor(Math.random() * 255); let paintedColor = `rgb(${r},${g},${b})`; // To choose random painting color each time user paints a pixel pixel.style.backgroundColor = paintedColor; // Set a timeout to call the reset function after a delay // When we pass additional parameters (like 'pixel' below) they // are passed to the callback function (resetPixel) setTimeout(resetPixel, DELAY, pixel); } // resetPixel // // Takes provided pixel element and sets color back to black (bg color) function resetPixel(pixel) { pixel.style.backgroundColor = DEFAULT_COLOR; // back to black } // remove // // To remove pixel color when user clicks on it function remove(e) { let pixel = e.target; pixel.style.backgroundColor = DEFAULT_COLOR; // back to black } // rotate // // User can rotate all pixels using arrow keys function rotate(e) { // Use pixel class to put them all into variable let pixels = document.getElementsByClassName('pixel'); if (e.keyCode === 37) { // left arrow pressed rotation -= 1; // rotate counter-clockwise } else if (e.keyCode === 39) { // left arrow pressed rotation += 1; // rotate clockwise } // Updating rotation for all pixels for (let i = 0; i < pixels.length; i++) { pixels[i].style.transform = `rotate(${rotation}deg)`; } } // typed // // Set currentKey to the keyCode of the key just presed function typed(e) { currentKey = e.keyCode; } // addText // // Add text to pixel (according to which key is pressed) function addText(e) { e.target.innerHTML = String.fromCharCode(currentKey); }
import React, { Component } from 'react'; import ReactDOM from 'react-dom' import Link from 'next/link' import {connect} from 'react-redux'; import { do_search_listings, do_display_listings } from '../redux/search-actions' import propserv from '../services/property-services'; import { SliderResultListing } from './Sliders'; import currencyFormatter from 'currency-formatter' import conf from '../settings'; const { IMG_URL, BASE_URL } = conf const mapStateToProps = state => ({ search: state.search }); const mapDispatchToProps = { do_search: do_search_listings, display_listings : do_display_listings }; class ResultListing extends Component{ constructor(props){ super(props) this.state = { is_loading : true, is_refresh : true, is_initialize : true, listings : [], showSorting : false, currentIndex : 1, filter : [], limit : 9, end : 9, start : 0 } this.onPaginate = this.onPaginate.bind(this) this.onPageNext = this.onPageNext.bind(this) this.onPagePrev = this.onPagePrev.bind(this) } componentDidMount(){ const { search, display_listings } = this.props var $this = this propserv.searchListings({ province : search.propadd, proptype : search.proptype, proplocal : search.proplocal, municipality : search.propmun, feature : [] }).then((res) => { display_listings(res) this.setState({ is_loading : false }) }) } onPriceLowest(){ const { search, display_listings } = this.props const { start, end, limit, listings, currentIndex } = this.state this.setState({ is_loading : true }) propserv.searchListings({ province : search.propadd, proptype : search.proptype, proplocal : search.proplocal, municipality : search.propmun, feature : [], sort : 'asc' }).then((res) => { var filter = res.filter((item, index) => (index >= 0 && index < limit )) this.setState({ is_loading : false, listings : res, filter : filter, start : 0, end : limit, }) }) } onPriceHighest(){ const { search, display_listings } = this.props const { start, end, limit, listings, currentIndex } = this.state this.setState({ is_loading : true }) propserv.searchListings({ province : search.propadd, proptype : search.proptype, proplocal : search.proplocal, municipality : search.propmun, feature : [], sort : 'desc' }).then((res) => { var filter = res.filter((item, index) => (index >= 0 && index < limit )) this.setState({ is_loading : false, listings : res, filter : filter, start : 0, end : limit, }) }) } onLatestPost(){ const { search, display_listings } = this.props const { start, end, limit, listings, currentIndex } = this.state this.setState({ is_loading : true }) propserv.searchListings({ province : search.propadd, proptype : search.proptype, proplocal : search.proplocal, municipality : search.propmun, feature : [], sort : 'post' }).then((res) => { var filter = res.filter((item, index) => (index >= 0 && index < limit )) this.setState({ is_loading : false, listings : res, filter : filter, start : 0, end : limit, }) }) } shouldComponentUpdate(nextProps, nextState){ const { search } = this.props const { start, limit, end, is_refresh } = this.state if(this.props.is_searching != nextProps.is_searching){ var filter = search.listings.filter((item, index) => (index >= 0 && index < limit )) this.setState({ listings : search.listings, filter : filter, start : 0, end : limit, }) } if(this.state.is_initialize && search.listings.length){ var filter = search.listings.filter((item, index) => (index >= start && index < end )) this.setState({ listings : search.listings, is_initialize : false, filter : filter, start : start + limit, end : end + limit }) } return true } onPageNext(){ const { start, end, limit, listings, currentIndex } = this.state var _start = (limit * (currentIndex + 1)) - limit var _end = (limit * (currentIndex + 1)) var filter = listings.filter((item, index) => (index >= _start && index < _end)) if(filter.length){ this.setState({ filter : filter, start : _start, end : _end, currentIndex : currentIndex + 1 }) } } onPagePrev(){ const { start, end, limit, listings, currentIndex } = this.state var _start = (limit * (currentIndex - 1)) - limit var _end = (limit * (currentIndex - 1)) var filter = listings.filter((item, index) => (index >= _start && index < _end)) if(filter.length){ this.setState({ filter : filter, start : _start, end : _end, currentIndex : currentIndex - 1 }) } } onPaginate(pageindex){ const { start, end, limit, listings } = this.state var _start = (limit * pageindex) - limit var _end = (limit * pageindex) var filter = listings.filter((item, index) => (index >= _start && index < _end)) if(filter.length){ this.setState({ filter : filter, start : _start, end : _end, currentIndex : pageindex }) } } onShowSorting(){ if(!this.state.showSorting){ this.setState({ showSorting : true }) } else{ this.setState({ showSorting : false }) } } render(){ const { search, prop_loading } = this.props const { is_loading, listings, filter, limit, currentIndex, showSorting } = this.state if(is_loading || prop_loading){ return ( <div className="container"> <div className="row justify-content-center"> <img src="/assets/img/loader.gif" width="100px"/> </div> </div> ) } return ( <section> <div className="container"> <div className="row"> <div className="col-lg-12 col-sm-12 list-layout"> <div className="row"> <div className="col-lg-12 col-md-12"> <div className="filter-fl"> <h4>Total Property Find is: <span className="theme-cl">{search.listings?.length}</span></h4> <div className="btn-group custom-drop"> <button type="button" className="btn btn-order-by-filt" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" onClick={(e) => this.onShowSorting()}> Sort By<i className="ti-angle-down"></i> </button> <div className={(showSorting) ? "dropdown-menu pull-right animated flipInX show" : "dropdown-menu pull-right animated flipInX"}> <a onClick={(e) => this.onPriceLowest()}>Price lowest</a> <a onClick={(e) => this.onPriceHighest()}>Price highest</a> <a onClick={(e) => this.onLatestPost()} >Latest Post</a> </div> </div> </div> </div> </div> <div className='row'> { filter.length ? filter.map((item, index) => { var vendorprice = currencyFormatter.format(item.vendor_requested_price, { locale: 'en-PH' }); var photo = BASE_URL + item.photo_url; if(item.photo_url.indexOf('http') != -1 || item.photo_url.indexOf('google') != -1){ photo = item.photo_url } return ( <div className='col-lg-4 col-md-5 col-sm-12' key={"property-"+index}> <div className='property-listing property-2'> <div className='listing-img-wrapper'> <SliderResultListing images={item.images} /> <span className="property-type">{item.listing_type}</span> </div> <div className="listing-detail-wrapper pb-0"> <div className="listing-short-detail"> <h4 className="listing-name"> <Link href={"/single-listing/" + item.property_id}><a>{item.property_name}</a></Link> </h4> </div> <div className="listing-price-fx"> <h6 className="listing-card-info-price">{vendorprice}</h6> </div> </div> <div className="price-features-wrapper"> <div className="listing-location"> <p>{item.line_1_number_building + ', ' + item.line_3_area_locality + ', ' + item.country_state_province + ', ' + item.zip_postcode}</p> </div> <div className="list-fx-features"> <div className="listing-card-info-icon"> <i className="las la-bed"></i><span className='info-label'>{item.bedrooms}</span> </div> <div className="listing-card-info-icon"> <i class="las la-hotel"></i><span className='info-label'>{item.property_type}</span> </div> </div> </div> <div className="price-features-wrapper"> <div className="list-fx-features"> <div className="listing-card-info-icon"> <i class="las la-bath"></i><span className='info-label'>{item.bathrooms}</span> </div> <div className="listing-card-info-icon"> <i class="las la-layer-group"></i><span className='info-label'>{item.lotarea}</span> </div> </div> </div> <div className="list-fx-features"> <div> <a href='#' className='btn btn-md btn-primary req-info'>Request Info</a> </div> <div> <Link href={"/single-listing/" + item.property_id}><a className='btn btn-md btn-primary prop-detail'>Property Detail</a></Link> </div> </div> <div className="modern-property-footer"> <div className="property-author"> <div className="path-img"><Link href={"/agent/" + item.owner_account_id} ><a><img src={photo} className="img-fluid" alt="" /></a></Link></div> <h5><Link href={"/agent/" + item.owner_account_id} ><a>{item.first_name + " " + item.last_name}</a></Link></h5> </div> </div> </div> </div> ) }) : <div className='col-lg-4 col-md-6 col-sm-12'><strong>No Result Available</strong></div> } </div> <div className="row"> <div className="col-lg-12 col-md-12 col-sm-12"> <ul className="pagination p-center"> { listings.length ? <li className="page-item"> <a className="page-link" onClick={(e) => this.onPagePrev()} aria-label="Previous"> <span className="ti-arrow-left"></span> <span className="sr-only">Previous</span> </a> </li> : <span></span> } {listings.length ? listings.map((item, index) => { if((index % limit) == 0){ var pagenum = (index / limit) + 1 return ( <li key={ 'paginate-' + index } className={ (currentIndex == pagenum) ? "page-item active" : 'page-item' }><a className="page-link" onClick={(e) => this.onPaginate(pagenum)}>{pagenum}</a></li> ) } return ( <span key={ 'paginate-empty' + index }></span> ) }) : <span></span> } { listings.length ? <li className="page-item"> <a className="page-link" aria-label="Next" onClick={(e) => this.onPageNext()}> <span className="ti-arrow-right"></span> <span className="sr-only">Next</span> </a> </li> : <span></span> } </ul> </div> </div> </div> </div> </div> </section> ) } } export default connect(mapStateToProps, mapDispatchToProps)(ResultListing)
import { setButtonColor } from "../../utils/htmlUtils"; import * as Registry from "../../core/registry"; import * as Colors from "../colors"; const inactiveButtonBackground = Colors.GREY_200; const inactiveButtonText = Colors.BLACK; const activeButtonText = Colors.WHITE; export default class LayerToolBar { constructor() { this.__toolBar = document.getElementById("layer-toolbar"); if (!this.__toolBar) { console.error("Could not find the LayerToolBar on the HTML page"); } this.__layerButtons = new Map(); //Simple Reference System this.__activeLayer = null; this.__levelCount = 0; this.__addNewLevelButton = document.getElementById("add-new-level"); let ref = this; let registryref = Registry; this.__addNewLevelButton.addEventListener("click", function(event) { //Create new layers in the data model registryref.viewManager.createNewLayerBlock(); //Update the UI ref.__levelCount += 1; ref.__generateUI(); }); this.__generateUI(); } __generateButtonHandlers() { let flowButtons = document.querySelectorAll(".flow-button"); let controlButtons = document.querySelectorAll(".control-button"); let ref = this; for (let i = 0; i < flowButtons.length; i++) { let flowButton = flowButtons[i]; flowButton.onclick = function(event) { Registry.currentLayer = Registry.currentDevice.layers[flowButton.dataset.layerindex]; ref.setActiveLayer(flowButton.dataset.layerindex); Registry.viewManager.updateActiveLayer(); }; } for (let i = 0; i < controlButtons.length; i++) { let controlButton = controlButtons[i]; controlButton.onclick = function(event) { Registry.currentLayer = Registry.currentDevice.layers[controlButton.dataset.layerindex]; ref.setActiveLayer(controlButton.dataset.layerindex); Registry.viewManager.updateActiveLayer(); }; } } setActiveLayer(layerName) { //Decolor the active button if (this.__activeLayer) { setButtonColor(this.__layerButtons.get(this.__activeLayer), inactiveButtonBackground, inactiveButtonText); } let bgColor; // = Colors.getDefaultLayerColor(Registry.currentLayer); if (layerName % 3 === 0) { bgColor = Colors.INDIGO_500; } else if (layerName % 3 === 1) { bgColor = Colors.RED_500; } else { bgColor = Colors.GREEN_500; } setButtonColor(this.__layerButtons.get(layerName), bgColor, activeButtonText); this.__activeLayer = layerName; } /** * Adds the UI elements for the new block * @private */ __addNewLevel(index) { //Copy the the first button group let buttongroup = document.querySelector("#template-layer-block"); let copy = buttongroup.cloneNode(true); //Make the delete button visible since the first layer ui keeps it hidden copy.querySelector(".delete-level").style.visibility = "visible"; //Change all the parameters for the UI elements //Update the level index for the layerblock copy.dataset.levelindex = String(index); //Change the Label let label = copy.querySelector(".level-index"); label.innerHTML = "LEVEL " + (index + 1); //Change the button indices let flowbutton = copy.querySelector(".flow-button"); flowbutton.dataset.layerindex = String(index * 3); setButtonColor(flowbutton, inactiveButtonBackground, inactiveButtonText); let controlbutton = copy.querySelector(".control-button"); controlbutton.dataset.layerindex = String(index * 3 + 1); setButtonColor(controlbutton, inactiveButtonBackground, inactiveButtonText); //Add reference to the deletebutton let deletebutton = copy.querySelector(".delete-level"); deletebutton.dataset.levelindex = String(index); return copy; } /** * Updates the button references held by the toolbar object, this is to allow me to easily modify * the buttons based on what layer index we are using * @private */ __updateLayerButtonReferences() { let flowButtons = document.querySelectorAll(".flow-button"); let controlButtons = document.querySelectorAll(".control-button"); for (let i = 0; i < flowButtons.length; i++) { let flowButton = flowButtons[i]; this.__layerButtons.set(flowButton.dataset.layerindex, flowButton); } for (let i = 0; i < controlButtons.length; i++) { let controlButton = controlButtons[i]; this.__layerButtons.set(controlButton.dataset.layerindex, controlButton); } } /** * Generates all the event handlers for the action buttons * @private */ __generateLevelActionButtonHandlers() { let deleteButtons = document.querySelectorAll(".delete-level"); let ref = this; for (let i = 0; i < deleteButtons.length; i++) { let deletebutton = deleteButtons[i]; deletebutton.addEventListener("click", function(event) { ref.deleteLevel(parseInt(deletebutton.dataset.levelindex)); }); } } /** * Deletes the level at the given index * @param levelindex Integer */ deleteLevel(levelindex) { //First tell the viewmanager to delete the levels Registry.viewManager.deleteLayerBlock(levelindex); //Next delete the ux buttons let buttongroups = this.__toolBar.querySelectorAll(".layer-block"); for (let i = 0; i < buttongroups.length; i++) { if (buttongroups[i].dataset.levelindex === levelindex) { this.__toolBar.removeChild(buttongroups[i]); } } this.__levelCount -= 1; this.__generateUI(); Registry.currentLayer = Registry.currentDevice.layers[0]; this.setActiveLayer("0"); Registry.viewManager.updateActiveLayer(); } __generateUI() { //Clear out all the UI elements let buttongroups = this.__toolBar.querySelectorAll(".layer-block"); //Delete all things except the first one for (let i = buttongroups.length - 1; i > 0; i--) { let node = buttongroups[i]; this.__toolBar.removeChild(node); } //Create the UI elements for everything for (let i = 1; i <= this.__levelCount; i++) { let copy = this.__addNewLevel(i); this.__toolBar.appendChild(copy); } this.__updateLayerButtonReferences(); this.__generateButtonHandlers(); this.__generateLevelActionButtonHandlers(); } }
export async function getSearchResult(searchUrl, searchItem) { try { let result = await fetch(searchUrl + searchItem) return result.json(); } catch (error) { throw error.toString(); }; }
function openOvermoreg() { document.getElementById("fiscalMoreg").style.visibility = "visible"; document.getElementById("mainFiscal2").style.height = "450px"; document.getElementById("bottomOver2").style.height = "5rem"; } function closeOvermo() { document.getElementById("fiscalMoreg").style.visibility = "hidden"; document.getElementById("mainFiscal2").style.height = "0"; document.getElementById("bottomOver2").style.height = "0"; } function openMosig() { document.getElementById("fiscalMo").style.visibility = "visible"; document.getElementById("mainOver").style.height = "450px"; document.getElementById("bottomOver").style.height = "5rem"; document.getElementById("fiscalMoreg").style.visibility = "hidden"; document.getElementById("mainFiscal2").style.height = "0"; document.getElementById("bottomOver2").style.height = "0"; }
import React from "react"; import "./ControlContainer.css"; const ControlContainer = ({ name, handleClick }) => ( <div className="control-container" onClick={handleClick}> <h2>{name}</h2> </div> ); export default React.memo(ControlContainer);
class Event { constructor(options) { let { error, message, data } = options this.error = error; this.message = message; this.data = data; } toString() { if (this.error) { return "ERROR: " + this.message; } else { return this.data.toString(); } } } export default class Result { constructor() { this.config = { /* AbsPathForKey: { input, output } */ } this._watcher = { /* AbsPathForKey: { input, output } */ } } watch(watch, callback) { if (!watch) { throw new Error("Please provid the rollup.watch"); } for (let i in this.config) { this._watcher[i] = watch(this.config[i].input); this._watcher[i].on("event", function (evt) { if (evt.code == "ERROR" || evt.code == "FATAL") { callback && callback(new Event({ error: true, message: i, data: evt })); } else { callback && callback(new Event({ error: false, message: i, data: evt })); } }); } } stop() { for (let i in this._watcher) { this._watcher[i].stop(); } } async build(rollup, callback) { if (!rollup) { throw new Error("Please provid the rollup.rollup"); } return new Promise(async (resolve, reject) => { for (let i in this.config) { let bundle = await rollup(this.config[i].input); for (let o in this.config[i].output) { let outputConfig = this.config[i].output[o]; try { await bundle.write(outputConfig) } catch (err) { let evt = new Event({ error: true, message: i, data: err }); callback && callback(evt); reject(evt); } } } let evt = new Event({ error: false, message: "done" }) callback && callback(evt) resolve(evt); }) } }
/** * Copyright (c) Benjamin Ansbach - all rights reserved. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ const Abstract = require('./Abstract'); const BC = require('@pascalcoin-sbx/common').BC; const NetProtocol = require('./NetProtocol'); const NetStats = require('./NetStats'); const NodeServer = require('./NodeServer'); const P_READY = Symbol('ready'); const P_READY_S = Symbol('ready_s'); const P_STATUS_S = Symbol('status_s'); const P_PORT = Symbol('port'); const P_LOCKED = Symbol('locked'); const P_TIMESTAMP = Symbol('timestamp'); const P_BLOCKS = Symbol('blocks'); const P_NODESERVERS = Symbol('nodeservers'); const P_NETSTATS = Symbol('netstats'); const P_VERSION = Symbol('version'); const P_NETPROTOCOL = Symbol('netprotocol'); const P_SBH = Symbol('sbh'); const P_POW = Symbol('pow'); const P_OPENSSL = Symbol('openssl'); class NodeStatus extends Abstract { static createFromRPC(data) { let nodeStatus = new NodeStatus(data); nodeStatus[P_READY] = !!data.ready; nodeStatus[P_READY_S] = data.ready_s; nodeStatus[P_STATUS_S] = data.status_s; nodeStatus[P_PORT] = parseInt(data.port, 10); nodeStatus[P_LOCKED] = !!data.locked; nodeStatus[P_TIMESTAMP] = parseInt(data.timestamp, 10); nodeStatus[P_BLOCKS] = parseInt(data.blocks, 10); nodeStatus[P_VERSION] = data.version; nodeStatus[P_SBH] = BC.fromHex(data.sbh); nodeStatus[P_POW] = BC.fromHex(data.pow); nodeStatus[P_OPENSSL] = BC.fromHex(data.openssl); nodeStatus[P_NETPROTOCOL] = NetProtocol.createFromRPC(data.netprotocol); nodeStatus[P_NETSTATS] = NetStats.createFromRPC(data.netstats); nodeStatus[P_NODESERVERS] = data.nodeservers.map(ns => NodeServer.createFromRPC(ns)); return nodeStatus; } /** * Gets a flag indicating whether the node is ready. * * @returns {Boolean} */ get ready() { return this[P_READY]; } /** * Gets a string explaining the ready status. * * @returns {String} */ get readyS() { return this[P_READY_S]; } /** * Gets a string defining the status of the node. * * @returns {String} */ get statusS() { return this[P_STATUS_S]; } /** * Gets the port of the node. * * @returns {Number} */ get port() { return this[P_PORT]; } /** * Gets a value indicating whether the wallet is locked. * * @returns {Boolean} */ get locked() { return this[P_LOCKED]; } /** * Gets the timestamp where the node runs. * * @returns {Number} */ get timestamp() { return this[P_TIMESTAMP]; } /** * Gets the number of known blocks. * * @returns {Number} */ get blocks() { return this[P_BLOCKS]; } /** * Gets the list of nodeservers. * * @returns {NodeServer[]} */ get nodeservers() { return this[P_NODESERVERS]; } /** * Gets the netstats * * @returns {NetStats} */ get netstats() { return this[P_NETSTATS]; } /** * Gets the node version info. * * @returns {Version} */ get version() { return this[P_VERSION]; } /** * Gets the info about the protocol versions. * * @returns {NetProtocol} */ get netprotocol() { return this[P_NETPROTOCOL]; } /** * Gets the last safebox hash. * * @returns {BC} */ get sbh() { return this[P_SBH]; } /** * Gets the last known POW. * * @returns {BC} */ get pow() { return this[P_POW]; } /** * Gets the openssl info. * * @returns {BC} */ get openssl() { return this[P_OPENSSL]; } } module.exports = NodeStatus;
$(function() { $('.delete-image').click(function(e) { e.preventDefault(); var fileLink = $(this).prev('a'); console.log(fileLink); // $(this).remove(); }); });
import React, { Fragment, useContext, useEffect } from 'react'; import { Route, Redirect } from 'react-router-dom'; import { AppContext } from '../../context/appContext'; import FeedNav from '../../components/FeedNav'; import ProfilePrivate from '../../containers/ProfilePrivate'; import ProfilePublic from '../../containers/ProfilePublic'; import GlobalFooter from '../../components/GlobalFooter'; const Profile = ({ match, location }) => { const [auth] = useContext(AppContext); useEffect(() => {}, [auth]); // if it's true, then it's my profile. // will redirect the user to the private profile page const myProfile = location.pathname === `/profile/${auth.uuid}`; return ( <Fragment> <FeedNav /> <Route exact path={`${match.path}`} component={ProfilePrivate} /> <Route path={`${match.path}/:uuid`} render={() => myProfile ? ( <Redirect to={`${match.path}`} /> ) : ( <ProfilePublic /> ) } /> <GlobalFooter /> </Fragment> ); }; export default Profile;
const express = require("express"); const router = express.Router(); const {Bills} = require("../models/billModel"); //return all bills router.get("/",(req,res) => { return Bills.find({}).limit(20) .then(bills => { console.log("Length: ",bills.length); return res.json({ status:200, data:bills.map(bill => bill.serialize()) }); }) .catch(err => { console.log("error getting data: ",err); return res.json({ status:500, message:"An error occured" }) }) }); router.get("/bill",(req,res) => { let legId = req.query.legid; return Bills.find({legisinfo_id:legId}) .then(bill => { console.log("Length single: ",bill.length); return res.json({ status:200, data:bill }); }) .catch(err => { console.log("error getting data: ",err); return res.json({ status:500, message:"An error occured" }) }) }); module.exports = {router};
$(document).ready(function() { //Set options var fadeSpeed = 500; var autoSlider = false; var autoSliderSpeed = 1000; var currentSlide = 1; var maxSlide = 5; $("#slider > .slide:first-child").toggleClass("active"); $("#slider > .slide:gt(0)").hide(); //Add event handlers for next and prev $("#prev").click(function() { $("#slider > .slide:nth-child(" + currentSlide + ")").fadeOut({ duration: fadeSpeed / 2 }); currentSlide--; if (currentSlide < 1) { currentSlide = maxSlide; } $("#slider > .slide").hide(); $("#slider > .slide:nth-child(" + currentSlide + ")").fadeIn({ duration: fadeSpeed }); }); $("#next").click(function() { $("#slider > .slide:nth-child(" + currentSlide + ")").fadeOut({ duration: fadeSpeed }); currentSlide++; if (currentSlide > maxSlide) { currentSlide = 1; } $("#slider > .slide").hide(); $("#slider > .slide:nth-child(" + currentSlide + ")").fadeIn({ duration: fadeSpeed }); }); });
import React from 'react'; import { Link } from 'react-router' import { connect } from 'react-redux' import * as actionCreators from '../../action_creators'; import jIf from '../../util/jsx-if'; var VelocityComponent = require('velocity-react/velocity-component'); require('velocity-animate/velocity.ui'); class Landing extends React.Component{ constructor(props) { super(props); this.state = { showCreateRoom: false, showJoinRoom: false, username: props.username } this.showCreateRoom = this.showCreateRoom.bind(this); this.showJoinRoom = this.showJoinRoom.bind(this); this.handleCreateRoomClick = this.handleCreateRoomClick.bind(this); this.handleJoinRoomClick = this.handleJoinRoomClick.bind(this); } // componentWillMount(){ // if(this.props.username){ // this.refs.createRoomName.value = this.props.username; // this.refs.joinRoomName.value = this.props.username; // } // } showCreateRoom(){ this.setState({ showCreateRoom: !this.state.showCreateRoom, showJoinRoom: false }) } showJoinRoom(){ this.setState({ showJoinRoom: !this.state.showJoinRoom, showCreateRoom: false }) } handleCreateRoomClick(e) { let name = this.refs.createRoomName.value; this.props.createRoom(name); } handleJoinRoomClick(e) { let name = this.refs.joinRoomName.value; let roomId = this.refs.roomId.value; this.props.joinRoom(name, roomId); } render(){ let containerStyle = { display: 'flex', width: '400px', justifyContent: 'center', margin: '5em auto' } let buttonStyle = { margin: '10px' } function getValue(val){ console.log('in getValue ' + val); return val; } // // let component; // if(false){ // component = <div>{getValue('true')}</div> // } else { // component = <div>{getValue('false')}</div> // } function test(val){ console.log(val) } let user = { isAuthed: true }; return( <div style={containerStyle}> <div> <h1>Welcome to agilePoker!</h1> <div> To start, either create a new room, or join an existing room by entering the room number. </div> <div> { (()=>{ if(false) { <div>{test('truthy')}truthy</div> } else{ <div>{test('falsey')}falsey</div> } })() } </div> { jIf(true, <div>{getValue('if')}</div>) .elsif(false, <div>{getValue('else if')}</div>) .els(<div>{getValue('else')}</div>)() } { user.isAuthed && <div>Welcome User!</div> } <VelocityComponent animation={this.state.showCreateRoom ? 'slideDown' : 'slideUp'} duration={150}> <div> <h4>Create New Room:</h4> <div className="form-group"> <label for="exampleInputEmail1">Name</label> <input type="text" className="form-control" ref="createRoomName" defaultValue={this.state.username} placeholder="Name" /> </div> <button className="btn btn-primary" onClick={this.handleCreateRoomClick}>Create Room</button> <button className="btn btn-primary" onClick={this.showCreateRoom}>Cancel</button> </div> </VelocityComponent> <VelocityComponent animation={this.state.showJoinRoom ? 'slideDown' : 'slideUp'} duration={150}> <div> <h4>Join Existing Room:</h4> <div className="form-group"> <label for="exampleInputEmail1">Name</label> <input type="text" className="form-control" ref="joinRoomName" defaultValue={this.state.username} placeholder="Name" /> </div> <div className="form-group"> <label for="exampleInputEmail1">Room Id</label> <input type="text" className="form-control" ref="roomId" placeholder="Room Id" /> </div> <button className="btn btn-primary" onClick={this.handleJoinRoomClick}>Join Room</button> <button className="btn btn-primary" onClick={this.showJoinRoom}>Cancel</button> </div> </VelocityComponent> <VelocityComponent animation={this.state.showCreateRoom || this.state.showJoinRoom ? 'fadeOut' : 'fadeIn'} duration={400}> <div> <button style={buttonStyle} className="btn btn-block btn-primary" onClick={this.showCreateRoom}>Create New Room</button> <button style={buttonStyle} className="btn btn-block btn-primary" onClick={this.showJoinRoom}>Join Existing Room</button> </div> </VelocityComponent> </div> </div> ) } } function select(state) { return { username: state.get('username') } } export default connect(select, actionCreators)(Landing);
const Task = require('../models/task') const SubTask = require('../models/subtask') const Project = require('../models/project') const _ = require('lodash') const ResponseService = require('../../helpers/responseService') const moment = require('moment') class TaskController { getTasks (req, res) { var query = {} if(req.query.name) query.name = req.query.name if(req.query.priority && req.query.priority !== 'null') query.priority = req.query.priority if(req.query.due_date && req.query.due_date !== 'null') query.due_date = { '$gt' : new Date(req.query.due_date)} if(req.query.overdue && req.query.overdue == 'true'){ query.due_date = { '$lt' : new Date() } query.is_completed = false } Task.find(query) .populate('project', 'name') .exec((err, tasks) => { if(err) return ResponseService.json(500, "error", res, 'An error occurred.', null, err) return ResponseService.json(200, "success", res, "All tasks", tasks) }) } getTask(req, res) { Task.findById(req.params.id) .populate('project', 'name') .populate('subtasks') .exec((err, task) => { if(err) return ResponseService.json(500, "error", res, 'An error occurred.', null, err) if(!task) return ResponseService.json(404, "error", res, "Task not found") return ResponseService.json(200, "success", res, "Task", task) }) } getSubTasks(req, res) { var query = SubTask.find({ task: req.params.id }) if(req.query.sort && req.query.direction){ let sort = {} sort[req.query.sort] = req.query.direction query.sort(sort) } query.exec((err, subtasks) => { if(err) return ResponseService.json(500, "error", res, 'An error occurred.', null, err) return ResponseService.json(200, "success", res, "Task's Sub Tasks", subtasks) }) } createTask(req, res) { req.checkBody('name', "Name field is required").notEmpty(); req.checkBody('due_date', "Due Date field is required").notEmpty(); req.checkBody('project', "Project field is required").notEmpty(); req.getValidationResult() .then((result) => { if(!result.isEmpty()){ return ResponseService.json(400, 'error', res, 'Data Failed to pass validation', result.array()) } var task_data = _.pick(req.body, ['name', 'description', 'due_date', 'priority']); task_data.due_date = new Date(task_data.due_date) // Get the project Project.findById(req.body.project) .exec((err, project) => { if(err) return ResponseService.json(500, "error", res, 'An error occurred.', null, err) if(!project) return ResponseService.json(404, "error", res, "Project you are trying to create a task for does exist") task_data.project = project._id // Check if the task with that same name exists in the project Task.findOne({ name: task_data.name, project: task_data.project }) .exec((err, task) => { if (err) return ResponseService.json(500, 'error', res, 'An error occurred.', null, err) if (task) return ResponseService.json(500, 'error', res, `Task with same name - ${task_data.name} already exists in project`) var new_task = new Task(task_data) new_task.save((err) => { if (err) return ResponseService.json(500, 'error', res, 'An error occurred.', null, err) return ResponseService.json(200, 'success', res, 'Task Created', new_task) }) }) }) }) } updateTask(req, res) { Task.findById(req.params.id) .exec((err, task) => { if (err) return ResponseService.json(500, 'error', res, 'An error occurred.', null, err) if(!task) return ResponseService.json(404, 'error', res, 'Task not found.') let task_data = _.pick(req.body, ['name', 'description', 'is_completed', 'due_date', 'priority']) if(task_data.due_date) task_data.due_date = new Date(task_data.due_date) task = Object.assign(task, task_data) task.save((err)=> { if (err) return ResponseService.json(500, 'error', res, 'An error occurred.', null, err) if(req.body.is_completed != true){ return ResponseService.json(200, 'success', res, 'Task Updated', task) } // If the task was being set to completed // Check if all the tasks in the project have been completed Task.find({ project: task.project }) .exec((err, tasks) => { let tasks_done_count = 0 tasks.forEach((task) => { if(task.is_completed == true) tasks_done_count++ }) // if completed count doesn't equal tasks count if(tasks_done_count != tasks.length){ return ResponseService.json(200, 'success', res, 'Task Updated', task) } // If it does // Mark Project as done Project.findByIdAndUpdate(task.project, { is_completed: true }, (err, project) => { if (err) return ResponseService.json(500, 'error', res, 'An error occurred.', null, err) return ResponseService.json(200, 'success', res, 'Task Updated', task) }) }) }) }) } deleteTask(req, res) { Task.findByIdAndRemove(req.params.id, (err) => { if (err) return ResponseService.json(500, 'error', res, 'An error occurred.', null, err) return ResponseService.json(200, 'success', res, 'Task Deleted') }); } } module.exports = new TaskController
"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1 = require('@angular/core'); var side_panel_component_1 = require('../side-panel.component'); var LeftSideComponent = (function (_super) { __extends(LeftSideComponent, _super); function LeftSideComponent() { _super.call(this); } LeftSideComponent.prototype.ngOnInit = function () { }; LeftSideComponent.prototype.ngOnDestroy = function () { }; LeftSideComponent = __decorate([ core_1.Component({ moduleId: module.id, selector: 'left-side-panel', templateUrl: 'left-side-panel.component.html', styleUrls: ['left-side-panel.component.css'], animations: [ // Define the animation used on the containing dev where the width of the // panel is determined. Here we define the expanded width to be 300px, and // the collapsed width to be 38px. // // When expanding the panel we transition over a 200ms interval. // // When collapsing the panel we again use 200ms for the transition, but // we add a delay of 200ms to allow some other animations to complete before // shrinking the panel down. // core_1.trigger('panelWidthTrigger', [ core_1.state('expanded', core_1.style({ width: '380px' })), core_1.state('collapsed', core_1.style({ width: '38px' })), core_1.transition('collapsed => expanded', core_1.animate('200ms ease-in')), core_1.transition('expanded => collapsed', core_1.animate('200ms 200ms ease-out')) ]), // Define the animation used in the title bar where the colors swap from // a red foreground with white background, to the opposite. In this case // we use the same timings as the width animation above so these two // transitions happen at the same time // core_1.trigger('titleColorTrigger', [ core_1.state('collapsed', core_1.style({ backgroundColor: '#FFFFFF', color: '#E74C3C' })), core_1.state('expanded', core_1.style({ backgroundColor: '#E74C3C', color: '#FFFFFF' })), core_1.transition('collapsed => expanded', core_1.animate('200ms ease-in')), core_1.transition('expanded => collapsed', core_1.animate('200ms 200ms ease-out')) ]), // The title text trigger is a little different because it's an animation // for an element being added to the DOM. Here we take advantage of the 'void' // transition using a hard-coded state called 'in' (which is also hard coded in // the template). // // What we do in this animation is say when the element is added to the DOM // it should have an opacity of 0 (i.e., hidden), wait 300ms, and then animate // it's opacity change to 1 over a 100 ms time span. This effectively delays the // appearance of the text until after the panel has slid out to the full size. // // When the element is removed we take a different approach and animate the // opacity change back to 0 over a short 50ms interval. This ensures it's gone before // the panel starts to slide back in, creating a nice effect. // core_1.trigger('titleTextTrigger', [ core_1.state('in', core_1.style({ opacity: '1' })), core_1.transition('void => *', [core_1.style({ opacity: '0' }), core_1.animate('100ms 300ms') ]), core_1.transition('* => void', [ core_1.animate('50ms', core_1.style({ opacity: '0' })) ]) ]), // Define the animation used in the arrow icon where it rotates to point left // or right based on the state of the panel. In this case we use the same // timings as the width animation above so these two transitions happen at // the same time. // core_1.trigger('iconTrigger', [ core_1.state('collapsed', core_1.style({ transform: 'rotate(180deg)' })), core_1.state('expanded', core_1.style({ transform: 'rotate(0deg)' })), core_1.transition('collapsed => expanded', core_1.animate('200ms ease-in')), core_1.transition('expanded => collapsed', core_1.animate('200ms ease-out')) ]) ] }), __metadata('design:paramtypes', []) ], LeftSideComponent); return LeftSideComponent; }(side_panel_component_1.SideComponent)); exports.LeftSideComponent = LeftSideComponent;
import React, { Component } from 'react'; import { StyleSheet, Text, View } from 'react-native'; import Module1 from "./Module1.js"; import Module2 from "./Module2.js"; export default class HuyHoang extends React.Component{ constructor(props){ super(props); console.log("Hello contructor HuyHoang"); } componentWillMount(){ console.log("Hello ComponentWillMount"); } render() { console.log("Hello render HuyHoang"); return ( <View style={styles.bao}> <Text style={{backgroundColor:'yellow', margin: 10}}>Cach 1</Text> <Text style={styles.cach2}>Cach 2</Text> <Module1 /> <Module2 /> </View> ); } componentDidMount(){ console.log("Hello ComponentDidMount"); } } const styles = StyleSheet.create({ bao:{ backgroundColor : 'pink', flex:1, //ti le phu kin so voi thang cung cap flexDirection: "column",// chieu chia flex }, cach2: { fontSize: 20, textAlign: 'center', margin: 10, backgroundColor : 'blue', }, });
const mongoose = require('mongoose'); const User = require('./models/User'); mongoose.connect('mongodb://localhost:27017/teashop'); User.find({}, (err, datos) => { datos.forEach(usuario => { console.log("-------------------") console.log(`nombre ${usuario.nombre}`) console.log(`sabores ${usuario.sabores}`) console.log(`funciones: ${usuario.funciones}`) console.log(`pedidos:${usuario.pedidos}`) }) process.exit(0) })
import {citiesCopy} from "./CityDataProvider.js" import {citiesHTML} from "./CityHTMLConverter.js" const contentElement = document.querySelector(".content--left") export const citiesList = () => { let citiesHTMLRepresentation = "" const citiesArray= citiesCopy() for (const citiesObj of citiesArray) { citiesHTMLRepresentation += citiesHTML(citiesObj) } contentElement.innerHTML += ` <article class = "cities"> <h2 class ="articleHeader">Cities</h2> ${citiesHTMLRepresentation} </article>` }
/** * Created by xuwusheng on 15/12/18. */ define(['../../../app','../../../services/platform/integral-mall/giftTransfersConfirmService'], function (app) { var app = angular.module('app'); app.controller('giftTransfersConfirmCtrl', ['$rootScope', '$scope', '$state', '$sce', '$filter', 'HOST', '$window','giftTransfersConfirm','uploadFileService', function ($rootScope, $scope, $state, $sce, $filter, HOST, $window,giftTransfersConfirm,uploadFileService) { // 配置查询 $scope.querySeting = { items: [ { type: 'text', model: 'goodsName', title: '礼品名称' }, { type: 'text', model: 'sku', title: '礼品编码' }, { type: 'select', model: 'giftTypeList',//下拉框数组 selectedModel: 'giftTypeSelect',//设置下拉框选中状态id title: '礼品分类' }], btns: [{ text: $sce.trustAsHtml('查询'), click: 'searchClick' }] }; //tableͷ $scope.thHeader = giftTransfersConfirm.getThead0(); $scope.addThHeader = giftTransfersConfirm.getThead1(); //分页下拉框 $scope.pagingSelect = [ {value: 5, text: 5}, {value: 10, text: 10, selected: true}, {value: 20, text: 20}, {value: 30, text: 30}, {value: 50, text: 50} ]; //分页对象 $scope.paging = { totalPage: 1, currentPage: 1, showRows: 30, }; //初始化查询 var pmsSearch = giftTransfersConfirm.getSearch(); pmsSearch.then(function (data) { $scope.searchModel = data.query; $scope.searchModel.giftTypeSelect=-1;//设置下拉框默认选中 //获取table数据 //get(); }, function (error) { console.log(error) }); //查询 $scope.searchClick = function () { //重新设置分页从第一页开始 $scope.paging = { totalPage: 1, currentPage: 1, showRows: $scope.paging.showRows }; get(); } $scope.giftTransfersConfirmModel={ rdcId:{ id:'-1', select:[], }, wlCompId:{ id:'-1', select:[] }, } //初始化添加调拨礼品下拉框的数据 giftTransfersConfirm.getDataTable('/giftAllotted/getCkBaseInfoList', {param:{}}) .then(function (data) { $scope.giftTransfersConfirmModel.rdcId.select=data.grid; $scope.giftTransfersConfirmModel.wlCompId.select=data.grid; }) function get() { //获取选中 设置对象参数 var opts = angular.extend({}, $scope.searchModel, {}); //克隆出新的对象,防止影响scope中的对象 opts.giftType=$scope.searchModel.giftTypeSelect;//设置下拉框数据 delete opts.giftTypeList; opts.id=$scope.giftTransfersConfirmModel.rdcId.id; opts.pageNo = $scope.paging.currentPage; opts.pageSize = $scope.paging.showRows; var promise = giftTransfersConfirm.getDataTable( '/giftAllotted/getGiftStockList', { param: { query: opts } } ); promise.then(function (data) { if(data.code==-1){ alert(data.message); $scope.result2 = []; $scope.paging = { totalPage: 1, currentPage: 1, showRows: $scope.paging.showRows, }; return false; } $scope.result2 = data.grid; //设置分页 $scope.paging = { totalPage: data.total, currentPage: $scope.paging.currentPage, showRows: $scope.paging.showRows, }; // $scope.paging.totalPage = data.total; }, function (error) { console.log(error); }); } //分页跳转回调 $scope.goToPage = function () { get(); } //确认调拨 $scope.confirmTransfers= function () { $scope.skuDisabled=true; if($scope.giftTransfersConfirmModel.wlCompId.id=='-1'){ alert('请选择收货仓库!'); return; } if($scope.giftTransfersConfirmModel.wlCompId.id==$scope.giftTransfersConfirmModel.rdcId.id){ alert('收货仓库不能与发货仓库相同!'); return; } var isChecked=true; angular.forEach($scope.result1, function (item) { if(!item.count){ alert('调拨数量不能为空!'); isChecked=false; return false; } }); if(!isChecked) return; //确认调拨的时候传给后台的数据 var opts = { query:{ giftList:$scope.result1, sendId:$scope.giftTransfersConfirmModel.rdcId.id, rejectedId:$scope.giftTransfersConfirmModel.wlCompId.id, }, } giftTransfersConfirm.getDataTable('/giftAllotted/confirmAllotted', {param:opts}) .then(function (data) { if(data.status.code=="0000") { alert(data.status.msg, function () { $state.go('main.giftTransfers'); }); }else alert(data.status.msg); }); } //添加调拨礼品 $scope.addTransfersGift = function () { if($scope.giftTransfersConfirmModel.rdcId.id=='-1'){ alert('请选择发货仓库!'); return; } $scope.giftTtle = "添加调拨礼品"; $('#createTransfersGift').modal('show'); get(); } //删除 $scope.deleteGift= function (i,item) { $scope.result1.splice(i,1); } //添加选择 $scope.skuDisabled=false; $scope.isDisabled=true; $scope.addTransfers= function () { $scope.skuDisabled=true; $scope.isDisabled=false; var results = []; angular.forEach($scope.result2, function (item) { if (item.pl4GridCheckbox.checked) { results.push(item); } }); if(results.length==0){ alert('请选择!'); return; } $scope.result1=results; $("#createTransfersGift").modal('hide'); } }]) });
import React from 'react'; export const PeopleContext = React.createContext({});