code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
package tmp; /** SpiralMatrixSolution to: http://stackoverflow.com/questions/35737102/difference-between-two-recursive-methods * Created by kmhaswade on 3/1/16. */ public class ReflectBinaryTree { static class TreeNode<T> { TreeNode<T> left; TreeNode<T> right; T key; TreeNode(T key) { this.key = key; } } static <T> TreeNode<T> reflect(TreeNode<T> node) { TreeNode<T> left = node.left; node.left = node.right; node.right = left; if (node.left != null) reflect(node.left); if (node.right != null) reflect(node.right); return node; } }
kedarmhaswade/impatiently-j8
src/main/java/tmp/ReflectBinaryTree.java
Java
mit
680
from flask.ext.restful import Resource from common.models import Link from flask import jsonify, abort from . import api class TrafficLinkResource(Resource): def get(self, id): req_fields = ['linkId','linkName', 'borough', 'owner', 'linkPoints', 'encodedPolyLine', 'encodedPolyLineLvls'] link = Link.objects(linkId = str(id)).only(*req_fields) if len(link) == 0: abort(404) return jsonify({'Link': link}) class TrafficLinkListResource(Resource): def get(self): req_fields = ['linkId', 'linkName', 'borough', 'owner', 'linkPoints', 'encodedPolyLine', 'encodedPolyLineLvls'] links = Link.objects().only(*req_fields) if len(links) == 0: abort(404) return jsonify({'trafficLinkList': links}) # def post(self): # # # Read data from the website # try: # response = requests.get("http://207.251.86.229/nyc-links-cams/LinkSpeedQuery.txt") # except Exception as e: # abort(500) # # # Split to lines # trafficData = (response.text).split('\n') # # skip first line (headers) and last line (empty); read lines # # "Id" "Speed" "TravelTime" "Status" "DataAsOf" "linkId" "linkPoints" "EncodedPolyLine" "EncodedPolyLineLvls" "Owner" "Transcom_id" "Borough" "linkName" # for line in csv.reader(trafficData[1:-1], delimiter="\t"): # link = Link(linkId = line[5], # linkPoints = line[6], # encodedPolyLine = line[7], # encodedPolyLineLvls = line[8], # owner = line[9], # borough = line[11], # linkName = line[12]) # link.save() # # return {}, 201 api.add_resource(TrafficLinkResource, '/trafficLink/<int:id>') api.add_resource(TrafficLinkListResource, '/trafficLink/')
tcufer/nyc_traffic_speed_api
resources/link_data.py
Python
mit
1,679
namespace Mordor_s_Cruelty_Plan.Mood { public class Angry : MoodFactory { } }
MihailDobrev/SoftUni
C# Fundamentals/C# OOP Basics/08. Inheritance - Exercise/Mordor’s Cruelty Plan/Mood/Angry.cs
C#
mit
93
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.1.1.css"> <script src="../node_modules/mobilecaddy-codeflow/js/MockCordova.js"></script> <title>MobileCaddy Electron Test Suite</title> </head> <body> <div id="qunit"></div> <div id="qunit-fixture"></div> <script src="https://code.jquery.com/qunit/qunit-2.1.1.js"></script> <script src="tests.js"></script> </body> </html>
MobileCaddy/mobilecaddy-electron
test/launcher.html
HTML
mit
483
module Lobbyist module V2 class CampaignsFrontTemplates < Lobbyist::V2::HashieBase attr_accessor :id, :communication_campaign_id, :company_id, :image_filename attr_accessor :message_position, :content, :custom_image, :created_at, :updated_at attr_accessor :image_resize_status, :category_default_front_template_id, :status attr_accessor :offset def self.list(params = {}) response = get("/v2/campaigns-front-templates.json", params) create_response(response) end end end end
customerlobby/lobbyist-ruby
lib/lobbyist/v2/campaigns_front_templates.rb
Ruby
mit
540
import os import re from hwt.serializer.hwt import HwtSerializer from hwt.serializer.systemC import SystemCSerializer from hwt.serializer.verilog import VerilogSerializer from hwt.serializer.vhdl import Vhdl2008Serializer from hwt.synthesizer.unit import Unit from hwt.synthesizer.utils import to_rtl_str from hwt.simulator.simTestCase import SimTestCase rmWhitespaces = re.compile(r'\s+', re.MULTILINE) class BaseSerializationTC(SimTestCase): # file should be set on child class because we want the pats in tests # to be raltive to a current test case __FILE__ = None SERIALIZER_BY_EXT = { "v": VerilogSerializer, "vhd": Vhdl2008Serializer, "cpp": SystemCSerializer, "py": HwtSerializer, } def tearDown(self): self.rmSim() SimTestCase.tearDown(self) def strStructureCmp(self, cont, tmpl): if not isinstance(cont, str): cont = repr(cont) _tmpl = rmWhitespaces.sub(" ", tmpl).strip() _cont = rmWhitespaces.sub(" ", cont).strip() self.assertEqual(_tmpl, _cont) def assert_serializes_as_file(self, u: Unit, file_name: str): ser = self.SERIALIZER_BY_EXT[file_name.split(".")[-1]] s = to_rtl_str(u, serializer_cls=ser) self.assert_same_as_file(s, file_name) def assert_same_as_file(self, s, file_name: str): assert self.__FILE__ is not None, "This should be set on child class" THIS_DIR = os.path.dirname(os.path.realpath(self.__FILE__)) fn = os.path.join(THIS_DIR, file_name) # with open(fn, "w") as f: # f.write(s) with open(fn) as f: ref_s = f.read() self.strStructureCmp(s, ref_s)
Nic30/hwtLib
hwtLib/examples/base_serialization_TC.py
Python
mit
1,714
/*global jQuery:false */ /*jshint browser:true */ /*global angular:false */ /*global $:false */ var myApp = angular.module('myApp', []); myApp.controller('mainController',['$rootScope','$scope', '$http','$window', function($rootScope,$scope, $http,$window){ "use strict"; $scope.userList=[]; $scope.getUsers=function(){ $http.get('/getUserList') .then(function(response){ var inc = response.data; $scope.userList=inc.users; }); }; $scope.getUsers(); $scope.deleteUser=function(user){ var toSend={}; toSend.user=user; var toSubmitString=encodeURIComponent(JSON.stringify(toSend)); $http.get('/deleteUser/'+toSubmitString) .then(function(response){ var inc = response.data; location.reload(); }); }; }]);
adamdboult/yetipredict
src/js/users.js
JavaScript
mit
780
import { Injectable } from '@angular/core'; @Injectable() export class ValidateService { constructor() { } validateRegister(user){ if(user.name == undefined || user.email == undefined || user.username == undefined || user.password == undefined){ return false; } else { return true; } } validateEmail(email){ var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } }
calebgasser/mean-auth-app
angular-source/src/app/services/validate.service.ts
TypeScript
mit
545
<div class="commune_descr limited"> <p> Tordouet est un village géographiquement positionné dans le département des Calvados en Basse-Normandie. Elle totalisait 288 habitants en 2008.</p> <p>Le nombre d'habitations, à Tordouet, se décomposait en 2011 en zero appartements et 158 maisons soit un marché plutôt équilibré.</p> <p>À coté de Tordouet sont localisées les communes de <a href="{{VLROOT}}/immobilier/saint-pierre-de-mailloc_14647/">Saint-Pierre-de-Mailloc</a> à 2&nbsp;km, 457 habitants, <a href="{{VLROOT}}/immobilier/saint-denis-de-mailloc_14571/">Saint-Denis-de-Mailloc</a> située à 4&nbsp;km, 319 habitants, <a href="{{VLROOT}}/immobilier/saint-martin-de-bienfaite-la-cressonniere_14621/">Saint-Martin-de-Bienfaite-la-Cressonnière</a> localisée à 2&nbsp;km, 479 habitants, <a href="{{VLROOT}}/immobilier/saint-julien-de-mailloc_14599/">Saint-Julien-de-Mailloc</a> à 4&nbsp;km, 450 habitants, <a href="{{VLROOT}}/immobilier/courtonne-les-deux-eglises_14194/">Courtonne-les-Deux-Églises</a> localisée à 4&nbsp;km, 582 habitants, <a href="{{VLROOT}}/immobilier/saint-martin-de-mailloc_14626/">Saint-Martin-de-Mailloc</a> localisée à 5&nbsp;km, 815 habitants, entre autres. De plus, Tordouet est située à seulement treize&nbsp;km de <a href="{{VLROOT}}/immobilier/lisieux_14366/">Lisieux</a>.</p> <p>Si vous envisagez de emmenager à Tordouet, vous pourrez aisément trouver une maison à vendre. </p> </div>
donaldinou/frontend
src/Viteloge/CoreBundle/Resources/descriptions/14693.html
HTML
mit
1,462
#!/bin/bash set -euo pipefail readonly SCRIPT_NAME="$( basename "${BASH_SOURCE[0]}" )" readonly SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" # shellcheck source=./utils.sh source "${SCRIPT_DIR}/utils.sh" main() { log "Cleaning up tox" rm -rfv "${BASE_DIR}/.tox" log "Cleaning up pytest cache" rm -rfv "${BASE_DIR}/.pytest_cache" log "Cleaning up pycache files" find "${BASE_DIR}" -iname '__pycache__' -type d -print0 | xargs -0 rm -rfv log "Cleaning up test results" rm -fv "${BASE_DIR}/TEST-*.xml" log "Cleaning up coverage files" rm -fv "${BASE_DIR}/.coverage" rm -fv "${BASE_DIR}/coverage.xml" rm -rfv "${BASE_DIR}/coverage_html_report" log "Cleaning up dist packages" rm -rfv "${DIST_DIR}" log "Cleaning up build packages" rm -rfv "${BUILD_DIR}" log "Cleaning up built docs" rm -rfv "${DOCS_BUILD_DIR}" } main "$@"
szopu/django-rest-registration
scripts/clean.sh
Shell
mit
921
import React, { Component, PropTypes } from 'react'; import Paper from 'material-ui/Paper'; import {grey400} from 'material-ui/styles/colors'; import {DropTarget} from 'react-dnd'; /** * Required by react-dnd, contains the functionality which is used by other react-dnd components to interect. * @type {Object} */ const target = { /** * Called when a DragSource aka CourseDnD is dropped on the container. * Returns the id of the category for this DropTarget component. * @param {Object} props The properties of SimpleDropTarget * @return {Object} Object which identifies the DropTarget. */ drop(props) { return {id: props.id, sort: props.sort}; } }; /** * Creates a wrapper around a native element to make a drop container. * Creates a Material-ui/Paper and wraps it with connectDropTarget of react-dnd. * Sets a 2px dashed border when an draggable component is hovering of the instance. * @example * <DropPanel id={myIdentifier} sort="example" className="col-xs-12" style={overrideStyle}> * <div> A container </div> * </DropPanel */ @DropTarget('any', target, (connect, monitor) => ({ connectDropTarget: connect.dropTarget(), isOver: monitor.isOver(), canDrop: monitor.canDrop() })) export default class DropPanel extends Component { static propTypes = { // Set by React-DnD, true if a draggable component is allowed to drop on this panel isOver: PropTypes.bool.isRequired, // Set by React-DnD, the wrapper function to create a droppable container/panel connectDropTarget: PropTypes.func.isRequired, // The id and sort combined are the identifiers of this instance id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired, sort: PropTypes.string.isRequired, style: PropTypes.object, className: PropTypes.string, children: PropTypes.arrayOf(PropTypes.element).isRequired } render() { const isOver = { border: `2px dashed ${grey400}` }; const {connectDropTarget } = this.props; const style = Object.assign({}, this.props.style, this.props.isOver ? isOver : {}); return connectDropTarget(<div className={this.props.className}> <Paper style={style} transitionEnabled={false}> {this.props.children} </Paper> </div>); } }
Pouja/tudscheduler
src/components/dnd/DropPanel.js
JavaScript
mit
2,401
/* !!!! GENERATED FILE - DO NOT EDIT !!!! */ /* * Copyright (c) 2014 liblcf authors * This file is released under the MIT License * http://opensource.org/licenses/MIT */ #ifndef LCF_RPG_SAVEEVENTDATA_H #define LCF_RPG_SAVEEVENTDATA_H // Headers #include <vector> #include "rpg_saveeventcommands.h" /** * RPG::SaveEventData class. */ namespace RPG { class SaveEventData { public: SaveEventData(); std::vector<SaveEventCommands> commands; bool show_message; int unknown_0d; bool keyinput_wait; int keyinput_variable; bool keyinput_all_directions; bool keyinput_decision; bool keyinput_cancel; bool keyinput_numbers; bool keyinput_operators; bool keyinput_shift; bool keyinput_value_right; bool keyinput_value_up; int time_left; int keyinput_time_variable; bool keyinput_down; bool keyinput_left; bool keyinput_right; bool keyinput_up; bool keyinput_timed; }; } #endif
glynnc/liblcf
src/generated/rpg_saveeventdata.h
C
mit
923
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Module description ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This module is re-pack of some pickle utility functions. - :func:`load_pk`: Load Python Object from Pickle file. - :func:`dump_pk`: Dump Picklable Python Object to file. - :func:`safe_dump_pk`: An atomic write version of dump_pk, silently overwrite existing file. - :func:`obj2bytestr`: Convert arbitrary pickable Python Object to bytestr. - :func:`bytestr2obj`: Parse Python object from bytestr. - :func:`obj2str`: convert arbitrary object to database friendly string, using base64encode algorithm. - :func:`str2obj`: Parse object from base64 encoded string. Highlight ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - :func:`load_pk`, :func:`dump_pk`, :func:`safe_dump_pk` support gzip compress, size is **10 - 20 times** smaller in average. Compatibility ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Python2: Yes - Python3: Yes Prerequisites ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - None Class, method, function, exception ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ from __future__ import print_function, unicode_literals import os import sys import gzip import shutil import time import base64 import pickle is_py2 = (sys.version_info[0] == 2) if is_py2: pk_protocol = 2 else: pk_protocol = 3 try: from ..gadget.messenger import Messenger except: from angora.gadget.messenger import Messenger def load_pk(abspath, compress=False, enable_verbose=True): """Load Python Object from Pickle file. :param abspath: File path. Use absolute path as much as you can. File extension has to be ``.pickle`` or ``.gz``. (for compressed Pickle) :type abspath: string :param compress: (default False) Load from a gzip compressed Pickle file. Check :func:`dump_pk()<dump_pk>` function for more information. :type compress: boolean :param enable_verbose: (default True) Trigger for message. :type enable_verbose: boolean Usage:: >>> from weatherlab.lib.dataIO.pk import load_pk >>> load_pk("test.pickle") # if you have a Pickle file Loading from test.pickle... Complete! Elapse 0.000272 sec. {'a': 1, 'b': 2} **中文文档** 从Pickle文件中读取数据 参数列表 :param abspath: 文件路径, 扩展名需为 ``.pickle`` 或 ``.gz`` :type abspath: ``字符串`` :param compress: (默认 False) 是否从一个gzip压缩过的Pickle文件中读取数据。 请 参考 :func:`dump_pk()<dump_pk>` 获得更多信息. :type compress: ``布尔值`` :param enable_verbose: (默认 True) 是否打开信息提示开关, 批处理时建议关闭. :type enable_verbose: ``布尔值`` """ abspath = str(abspath) # try stringlize msg = Messenger(enable_verbose=enable_verbose) if compress: # check extension name if os.path.splitext(abspath)[1] != ".gz": raise Exception("compressed pickle has to use extension '.gz'!") else: if os.path.splitext(abspath)[1] != ".pickle": raise Exception("file extension are not '.pickle'!") msg.show("\nLoading from %s..." % abspath) st = time.clock() if compress: with gzip.open(abspath, "rb") as f: obj = pickle.loads(f.read()) else: with open(abspath, "rb") as f: obj = pickle.load(f) if enable_verbose: msg.show(" Complete! Elapse %.6f sec" % (time.clock() - st)) return obj def dump_pk(obj, abspath, pk_protocol=pk_protocol, replace=False, compress=False, enable_verbose=True): """Dump Picklable Python Object to file. Provides multiple choice to customize the behavior. :param obj: Picklable Python Object. :param abspath: ``save as`` path, file extension has to be ``.pickle`` or ``.gz`` (for compressed Pickle). :type abspath: string :param pk_protocol: (default your python version) use 2, to make a py2.x/3.x compatible pickle file. But 3 is faster. :type pk_protocol: int :param replace: (default False) If ``True``, when you dump Pickle to a existing path, it silently overwrite it. If False, an exception will be raised. Default False setting is to prevent overwrite file by mistake. :type replace: boolean :param compress: (default False) If ``True``, use GNU program gzip to compress the Pickle file. Disk usage can be greatly reduced. But you have to use :func:`load_pk(abspath, compress=True)<load_pk>` in loading. :type compress: boolean :param enable_verbose: (default True) Trigger for message. :type enable_verbose: boolean Usage:: >>> from weatherlab.lib.dataIO.pk import dump_pk >>> pk = {"a": 1, "b": 2} >>> dump_pk(pk, "test.pickle", replace=True) Dumping to test.pickle... Complete! Elapse 0.001763 sec **中文文档** 将Python对象以Pickle的方式序列化, 保存至本地文件。(有些自定义类无法被序列化) 参数列表 :param obj: 可Pickle化的Python对象 :param abspath: 写入文件的路径。扩展名必须为 ``.pickle`` 或 ``.gz``, 其中gz用于被压 缩的Pickle :type abspath: ``字符串`` :param pk_protocol: (默认 等于你Python的大版本号) 使用2可以使得保存的文件能被 py2.x/3.x都能读取。但是协议3的速度更快, 体积更小, 性能更高。 :type pk_protocol: ``整数`` :param replace: (默认 False) 当为``True``时, 如果写入路径已经存在, 则会自动覆盖 原文件。而为``False``时, 则会抛出异常。防止误操作覆盖源文件。 :type replace: ``布尔值`` :param compress: (默认 False) 当为``True``时, 使用开源压缩标准gzip压缩Pickle文件。 通常能让文件大小缩小10-20倍不等。如要读取文件, 则需要使用函数 :func:`load_pk(abspath, compress=True)<load_pk>`. :type compress: ``布尔值`` :param enable_verbose: (默认 True) 是否打开信息提示开关, 批处理时建议关闭. :type enable_verbose: ``布尔值`` """ abspath = str(abspath) # try stringlize msg = Messenger(enable_verbose=enable_verbose) if compress: # check extension name root, ext = os.path.splitext(abspath) if ext != ".gz": if ext != ".tmp": raise Exception( "compressed pickle has to use extension '.gz'!") else: _, ext = os.path.splitext(root) if ext != ".gz": raise Exception( "compressed pickle has to use extension '.gz'!") else: root, ext = os.path.splitext(abspath) if ext != ".pickle": if ext != ".tmp": raise Exception("file extension are not '.pickle'!") else: _, ext = os.path.splitext(root) if ext != ".pickle": raise Exception("file extension are not '.pickle'!") msg.show("\nDumping to %s..." % abspath) st = time.clock() if os.path.exists(abspath): # if exists, check replace option if replace: # replace existing file if compress: with gzip.open(abspath, "wb") as f: f.write(pickle.dumps(obj, protocol=pk_protocol)) else: with open(abspath, "wb") as f: pickle.dump(obj, f, protocol=pk_protocol) else: # stop, print error message raise Exception("\tCANNOT WRITE to %s, " "it's already exists" % abspath) else: # if not exists, just write to it if compress: with gzip.open(abspath, "wb") as f: f.write(pickle.dumps(obj, protocol=pk_protocol)) else: with open(abspath, "wb") as f: pickle.dump(obj, f, protocol=pk_protocol) msg.show(" Complete! Elapse %.6f sec" % (time.clock() - st)) def safe_dump_pk(obj, abspath, pk_protocol=pk_protocol, compress=False, enable_verbose=True): """A stable version of dump_pk, silently overwrite existing file. When your program been interrupted, you lose nothing. Typically if your program is interrupted by any reason, it only leaves a incomplete file. If you use replace=True, then you also lose your old file. So a bettr way is to: 1. dump pickle to a temp file. 2. when it's done, rename it to #abspath, overwrite the old one. This way guarantee atomic write. :param obj: Picklable Python Object. :param abspath: ``save as`` path, file extension has to be ``.pickle`` or ``.gz`` (for compressed Pickle). :type abspath: string :param pk_protocol: (default your python version) use 2, to make a py2.x/3.x compatible pickle file. But 3 is faster. :type pk_protocol: int :param compress: (default False) If ``True``, use GNU program gzip to compress the Pickle file. Disk usage can be greatly reduced. But you have to use :func:`load_pk(abspath, compress=True)<load_pk>` in loading. :type compress: boolean :param enable_verbose: (default True) Trigger for message. :type enable_verbose: boolean Usage:: >>> from weatherlab.lib.dataIO.pk import safe_dump_pk >>> pk = {"a": 1, "b": 2} >>> safe_dump_pk(pk, "test.pickle") Dumping to test.pickle... Complete! Elapse 0.001763 sec **中文文档** 在对文件进行写入时, 如果程序中断, 则会留下一个不完整的文件。如果你使用了覆盖式 写入, 则你同时也丢失了原文件。所以为了保证写操作的原子性(要么全部完成, 要么全部 都不完成), 更好的方法是: 首先将文件写入一个临时文件中, 完成后再讲文件重命名, 覆盖旧文件。这样即使中途程序被中断, 也仅仅是留下了一个未完成的临时文件而已, 不会 影响原文件。 参数列表 :param obj: 可Pickle化的Python对象 :param abspath: 写入文件的路径。扩展名必须为 ``.pickle`` 或 ``.gz`` , 其中gz用于被压 缩的Pickle :type abspath: ``字符串`` :param pk_protocol: (默认 等于你Python的大版本号) 使用2可以使得保存的文件能被 py2.x/3.x都能读取。但是协议3的速度更快, 体积更小, 性能更高。 :type pk_protocol: ``整数`` :param compress: (默认 False) 当为 ``True`` 时, 使用开源压缩标准gzip压缩Pickle文件。 通常能让文件大小缩小10-20倍不等。如要读取文件, 则需要使用函数 :func:`load_pk(abspath, compress=True)<load_pk>`. :type compress: ``布尔值`` :param enable_verbose: (默认 True) 是否打开信息提示开关, 批处理时建议关闭. :type enable_verbose: ``布尔值`` """ abspath = str(abspath) # try stringlize temp_abspath = "%s.tmp" % abspath dump_pk(obj, temp_abspath, pk_protocol=pk_protocol, replace=True, compress=compress, enable_verbose=enable_verbose) shutil.move(temp_abspath, abspath) def obj2bytestr(obj, pk_protocol=pk_protocol): """Convert arbitrary pickable Python Object to bytestr. Usage:: >>> from weatherlab.lib.dataIO.pk import obj2bytestr >>> data = {"a": 1, "b": 2} >>> obj2bytestr(data, pk_protocol=2) b'\x80\x02}q\x00(X\x01\x00\x00\x00aq\x01K\x01X\x01\x00\x00\x00bq\x02K\x02u.' **中文文档** 将可Pickle化的Python对象转化为bytestr """ return pickle.dumps(obj, protocol=pk_protocol) def bytestr2obj(bytestr): """Parse Python object from bytestr. Usage:: >>> from weatherlab.lib.dataIO.pk import bytestr2obj >>> b = b'\x80\x02}q\x00(X\x01\x00\x00\x00aq\x01K\x01X\x01\x00\x00\x00bq\x02K\x02u.' >>> bytestr2obj(b) {"a": 1, "b": 2} **中文文档** 从bytestr中恢复Python对象 """ return pickle.loads(bytestr) def obj2str(obj, pk_protocol=pk_protocol): """Convert arbitrary object to utf-8 string, using base64encode algorithm. Usage:: >>> from weatherlab.lib.dataIO.pk import obj2str >>> data = {"a": 1, "b": 2} >>> obj2str(data, pk_protocol=2) 'gAJ9cQAoWAEAAABhcQFLAVgBAAAAYnECSwJ1Lg==' **中文文档** 将可Pickle化的Python对象转化为utf-8编码的"字符串" """ return base64.b64encode(pickle.dumps( obj, protocol=pk_protocol)).decode("utf-8") def str2obj(textstr): """Parse object from base64 encoded string. Usage:: >>> from weatherlab.lib.dataIO.pk import str2obj >>> str2obj("gAJ9cQAoWAEAAABhcQFLAVgBAAAAYnECSwJ1Lg==") {"a": 1, "b": 2} **中文文档** 从"字符串"中恢复Python对象 """ return pickle.loads(base64.b64decode(textstr.encode("utf-8"))) #--- Unittest --- if __name__ == "__main__": import unittest import sqlite3 class PKUnittest(unittest.TestCase): def test_write_and_read(self): data = {1: [1, 2], 2: ["是", "否"]} safe_dump_pk(data, "data.pickle") data = load_pk("data.pickle") # should be a self.assertEqual(data[1][0], 1) self.assertEqual(data[2][0], "是") def test_handle_object(self): python_object = {"a": 1} self.assertEqual(str2obj(obj2str(python_object)), python_object) def test_obj2bytestr(self): """pickle.dumps的结果是bytes, 而在python2中的sqlite不支持bytes直接 插入数据库,必须使用base64.encode将bytes编码成字符串之后才能存入数据 库。而在python3中, 可以直接将pickle.dumps的bytestr存入数据库, 这样 就省去了base64编码的开销。 注: 在python2中也有通过设定 connect.text_factory 的方法解决该问题, 具体内容请google This test will not pass in Python2, because sqlite python2 API doens't support bytes. """ conn = sqlite3.connect(":memory:") c = conn.cursor() c.execute("CREATE TABLE test (dictionary BLOB) ") # BLOB is byte c.execute("INSERT INTO test VALUES (?)", (obj2bytestr({1: "a", 2: "你好"}),)) # see what stored in database print(c.execute("select * from test").fetchone()) # recovery object from byte str self.assertDictEqual( bytestr2obj(c.execute("select * from test").fetchone()[0]), {1: "a", 2: "你好"}, ) def test_obj2str(self): """如果将任意python对象dump成pickle bytestr, 再通过base64 encode转化 成ascii字符串, 就可以任意地存入数据库了。 """ conn = sqlite3.connect(":memory:") c = conn.cursor() c.execute("CREATE TABLE test (name TEXT) ") c.execute("INSERT INTO test VALUES (?)", (obj2str({1: "a", 2: "你好"}),)) # see what stored in database print(c.execute("select * from test").fetchone()) # recovery object from text str self.assertDictEqual( str2obj(c.execute("select * from test").fetchone()[0]), {1: "a", 2: "你好"}, ) def test_compress(self): data = {"a": list(range(32)), "b": list(range(32)), } safe_dump_pk(data, "data.gz", compress=True) print(load_pk("data.gz", compress=True)) def tearDown(self): for path in ["data.pickle", "data.gz"]: try: os.remove(path) except: pass unittest.main()
MacHu-GWU/angora-project
angora/dataIO/pk.py
Python
mit
16,257
angular.module('coloring') .controller('ColoringsController', function (ColoringsService, $state, DTOptionsBuilder, DTColumnDefBuilder) { var self = this; self.colorings = []; self.dtOptions = DTOptionsBuilder.newOptions(); self.dtColumnDefs = [ DTColumnDefBuilder.newColumnDef(4).notSortable(), DTColumnDefBuilder.newColumnDef(5).notSortable() ]; ColoringsService.query(function(results) { self.colorings = results; }); self.deleteColoring = function(id, index) { ColoringsService.delete({id: id}, function(success) { self.colorings.splice(index, 1); }); }; });
devshawn/vertex-coloring
server/src/main/resources/static/components/colorings/colorings.controller.js
JavaScript
mit
721
using System; using System.Diagnostics; using GitHub.Services; using Microsoft.TeamFoundation.Controls; namespace GitHub.Extensions { public static class VSExtensions { public static T TryGetService<T>(this IServiceProvider serviceProvider) where T : class { return serviceProvider.TryGetService(typeof(T)) as T; } public static object TryGetService(this IServiceProvider serviceProvider, Type type) { var ui = serviceProvider as IUIProvider; if (ui != null) return ui.TryGetService(type); else { try { return serviceProvider.GetService(type); } catch (Exception ex) { Debug.Print(ex.ToString()); } return null; } } public static T GetService<T>(this IServiceProvider serviceProvider) { return (T)serviceProvider.GetService(typeof(T)); } public static T GetExportedValue<T>(this IServiceProvider serviceProvider) { var ui = serviceProvider as IUIProvider; return ui != null ? ui.GetService<T>() : VisualStudio.Services.ComponentModel.DefaultExportProvider.GetExportedValue<T>(); } public static ITeamExplorerSection GetSection(this IServiceProvider serviceProvider, Guid section) { return serviceProvider?.GetService<ITeamExplorerPage>()?.GetSection(section); } } }
bradthurber/VisualStudio
src/GitHub.Exports/Extensions/VSExtensions.cs
C#
mit
1,626
using FluentAutomation.Exceptions; using OpenQA.Selenium; using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; namespace FluentAutomation.Tests.Actions { public class ClickTests : BaseTest { public ClickTests() : base() { InputsPage.Go(); } [Fact] public void LeftClick() { I.Click(InputsPage.ButtonControlSelector) .Assert.Text("Button Clicked").In(InputsPage.ButtonClickedTextSelector); I.Click(InputsPage.InputButtonControlSelector) .Assert.Text("Input Button Clicked").In(InputsPage.ButtonClickedTextSelector); } [Fact] public void RightClick() { I.RightClick(InputsPage.ButtonControlSelector) .Assert.Text("Button Right Clicked").In(InputsPage.ButtonClickedTextSelector); I.RightClick(InputsPage.InputButtonControlSelector) .Assert.Text("Input Button Right Clicked").In(InputsPage.ButtonClickedTextSelector); } [Fact] public void DoubleClick() { I.DoubleClick(InputsPage.ButtonControlSelector) .Assert.Text("Button Double Clicked").In(InputsPage.ButtonClickedTextSelector); I.DoubleClick(InputsPage.InputButtonControlSelector) .Assert.Text("Input Button Double Clicked").In(InputsPage.ButtonClickedTextSelector); } [Fact] public void XYClicks() { var el = I.Find(InputsPage.ButtonControlSelector); I.Click(el.Element.PosX + 10, el.Element.PosY + 10) .Wait(3) .Assert.Text("Button Clicked").In(InputsPage.ButtonClickedTextSelector); I.DoubleClick(el.Element.PosX + 10, el.Element.PosY + 10) .Assert.Text("Button Double Clicked").In(InputsPage.ButtonClickedTextSelector); I.RightClick(el.Element.PosX + 10, el.Element.PosY + 10) .Assert.Text("Button Right Clicked").In(InputsPage.ButtonClickedTextSelector); I.Click(InputsPage.ButtonControlSelector, 10, 10) .Assert.Text("Button Clicked").In(InputsPage.ButtonClickedTextSelector); I.DoubleClick(InputsPage.ButtonControlSelector, 10, 10) .Assert.Text("Button Double Clicked").In(InputsPage.ButtonClickedTextSelector); I.RightClick(InputsPage.ButtonControlSelector, 10, 10) .Assert.Text("Button Right Clicked").In(InputsPage.ButtonClickedTextSelector); } [Fact] public void AlertClicks() { AlertsPage.Go(); // No alerts present Assert.Throws<FluentException>(() => I.Click(Alert.OK)); // Can't 'click' these fields Assert.Throws<FluentException>(() => I.Click(Alert.Input)); Assert.Throws<FluentException>(() => I.Click(Alert.Message)); // Alert box: // Alerts don't have OK/Cancel but both work, so we test as if Cancel was clicked I.Click(AlertsPage.TriggerAlertSelector) .Click(Alert.OK) .Assert.Text("Clicked Alert Cancel").In(AlertsPage.ResultSelector); I.Click(AlertsPage.TriggerAlertSelector) .Click(Alert.Cancel) .Assert.Text("Clicked Alert Cancel").In(AlertsPage.ResultSelector); // Confirmation box: I.Click(AlertsPage.TriggerConfirmSelector) .Click(Alert.OK) .Assert.Text("Clicked Confirm OK").In(AlertsPage.ResultSelector); I.Click(AlertsPage.TriggerConfirmSelector) .Click(Alert.Cancel) .Assert.Text("Clicked Confirm Cancel").In(AlertsPage.ResultSelector); // Prompt box: I.Click(AlertsPage.TriggerPromptSelector) .Enter("1").In(Alert.Input) .Assert.Text("Clicked Prompt OK: 1").In(AlertsPage.ResultSelector); I.Click(AlertsPage.TriggerPromptSelector) .Click(Alert.Cancel) .Assert.Text("Clicked Prompt Cancel").In(AlertsPage.ResultSelector); } } }
mirabeau-nl/WbTstr.Net
FluentAutomation.Tests/Actions/ClickTests.cs
C#
mit
4,169
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery.turbolinks //= require jquery_ujs //= require turbolinks //= require_tree .
lukasjones/support_hero
app/assets/javascripts/application.js
JavaScript
mit
692
'use strict'; // USUARIOS CRUD var Museo = require('../../models/model'); /* Rutas que terminan en /intervencion // router.route('/intervencion') */ // POST /usuarios exports.create = function (req, res) { // bodyParser debe hacer la magia var metodologia = req.body.metodologia; var fechaRestauracion = req.body.fechaRestauracion; var apellidoRestaurador = req.body.apellidoRestaurador; var descripcion = req.body.descripcion; var usuario = Museo.Intervencion.build({ metodologia: metodologia, fechaRestauracion: fechaRestauracion, descripcion: descripcion }); intervencion.add(function (success) { res.json({ message: 'Intervencion creada!' }); }, function (err) { res.send(err); }); }; /* (trae todos las intervenciones) // GET /intervencion */ exports.list = function (req, res) { var intervencion = Museo.Intervencion.build(); intervencion.retrieveAll(function (intervenciones) { if (intervenciones) { res.json(intervenciones); } else { res.send(401, 'No se encontraron Intervenciones'); } }, function (error) { res.send('Intervencion no encontrada'); }); }; /* Rutas que terminan en /intervenciones/:IntervencionesId // router.route('/intervenciones/:intervencioneId') // PUT /intervenciones/:intervencioneId // Actualiza intervencion */ exports.update = function (req, res) { var intervencion = Museo.Intervencion.build(); intervencion.metodologia = req.body.metodologia; intervencion.fechaRestauracion = req.body.fechaRestauracion; intervencion.apellidoRestaurador = req.body.apellidoRestaurador; intervencion.descripcion = req.body.descripcion; intervencion.updateById(req.params.intervencionId, function (success) { if (success) { res.json({ message: 'Intervencion actualizada!' }); } else { res.send(401, 'Intervencion no encontrada'); } }, function (error) { res.send('Intervencion no encontrada'); }); }; // GET /intervencion/:intervencionId // Toma un intervencion por id exports.read = function (req, res) { var intervencion = Museo.Intervencion.build(); intervencion.retrieveById(req.params.intervencionId, function (usuario) { if (intervencion) { res.json(intervencion); } else { res.send(401, 'Intervencion no encontrada'); } }, function (error) { res.send('Intervencion no encontrada'); }); }; // DELETE /intervencion/intervencionId // Borra el intervencionId exports.delete = function (req, res) { var intervencion = Museo.Intervencion.build(); intervencion.removeById(req.params.intervencionId, function (usuario) { if (intervencion) { res.json({ message: 'Intervencion borrada!' }); } else { res.send(401, 'Intervencion no encontrada'); } }, function (error) { res.send('Intervencion no encontrada'); }); };
JoparatonSIG/museolucho
src/controllers/API/intervencion.js
JavaScript
mit
2,827
lista.Any(x => x == 1) lista.Contains(1) lista.Exists(x => x == 1) //https://pt.stackoverflow.com/q/103050/101
maniero/SOpt
CSharp/Linq/ContainsXExistsXAny.cs
C#
mit
114
/* * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.jcodings.transcode.specific; import org.jcodings.transcode.AsciiCompatibility; import org.jcodings.transcode.TranscodeFunctions; import org.jcodings.transcode.Transcoder; public class Eucjp2sjis_Transcoder extends Transcoder { protected Eucjp2sjis_Transcoder () { super("EUC-JP", "Shift_JIS", 88, "Japanese", 1, 3, 2, AsciiCompatibility.CONVERTER, 0); } public static final Transcoder INSTANCE = new Eucjp2sjis_Transcoder(); @Override public int startToOutput(byte[] statep, byte[] s, int sStart, int l, byte[] o, int oStart, int oSize) { return TranscodeFunctions.funSoEucjp2Sjis(statep, s, sStart, l, o, oStart, oSize); } }
jruby/jcodings
src/org/jcodings/transcode/specific/Eucjp2sjis_Transcoder.java
Java
mit
1,761
# Use `hub` as our git wrapper: # http://defunkt.github.com/hub/ # hub_path=$(which hub) # if [[ -f $hub_path ]] # then # alias git=$hub_path # fi # The rest of my fun git aliases alias gl='git pull --prune' alias glog="git log --graph --pretty=format:'%Cred%h%Creset %an: %s - %Creset %C(yellow)%d%Creset %Cgreen(%cr)%Creset' --abbrev-commit --date=relative" alias gp='git push origin HEAD' alias gd='git diff' alias gc='git commit' alias gca='git commit -a' alias gco='git checkout' alias gb='git branch' alias gs='git status -sb' # upgrade your git if -sb breaks for you. it's fun. alias grm="git status | grep deleted | awk '{print \$3}' | xargs git rm"
alexrudy/dotfiles
git/aliases.sh
Shell
mit
663
// Package setup helps initialize the database and all queries. package setup import ( "context" "database/sql" "errors" "fmt" "sync" "time" "github.com/kevinburke/rickover/metrics" "github.com/kevinburke/rickover/models/db" "github.com/kevinburke/rickover/models/queued_jobs" "github.com/kevinburke/rickover/newmodels" _ "github.com/lib/pq" ) var mu sync.Mutex // TODO not sure for the best place for this to live. var activeQueriesStmt *sql.Stmt func prepare(ctx context.Context) (err error) { if !db.Connected() { return errors.New("setup: no DB connection was established, can't query") } activeQueriesStmt, err = db.Conn.PrepareContext(ctx, `-- setup.GetActiveQueries SELECT count(*) FROM pg_stat_activity WHERE state='active' `) return } func GetActiveQueries(ctx context.Context) (count int64, err error) { err = activeQueriesStmt.QueryRowContext(ctx).Scan(&count) return } // TODO all of these should use a different database connection than the server // or the worker, to avoid contention. func MeasureActiveQueries(ctx context.Context, interval time.Duration) { ticker := time.NewTicker(interval) defer ticker.Stop() for { count, err := GetActiveQueries(ctx) if err == nil { metrics.Measure("active_queries.count", count) } else { metrics.Increment("active_queries.error") } select { case <-ctx.Done(): return case <-ticker.C: } } } func MeasureQueueDepth(ctx context.Context, interval time.Duration) { ticker := time.NewTicker(interval) defer ticker.Stop() for { allCount, readyCount, err := queued_jobs.CountReadyAndAll(ctx) if err == nil { metrics.Measure("queue_depth.all", int64(allCount)) metrics.Measure("queue_depth.ready", int64(readyCount)) } else { metrics.Increment("queue_depth.error") } select { case <-ctx.Done(): return case <-ticker.C: } } } func MeasureInProgressJobs(ctx context.Context, interval time.Duration) { ticker := time.NewTicker(interval) defer ticker.Stop() for { m, err := queued_jobs.GetCountsByStatus(ctx, newmodels.JobStatusInProgress) if err == nil { count := int64(0) for k, v := range m { count += v metrics.Measure(fmt.Sprintf("queued_jobs.%s.in_progress", k), v) } metrics.Measure("queued_jobs.in_progress", count) } else { metrics.Increment("queued_jobs.in_progress.error") } select { case <-ctx.Done(): return case <-ticker.C: } } } // DB initializes a connection to the database, and prepares queries on all // models. If connector is nil, db.DefaultConnection will be used. func DB(ctx context.Context, connector db.Connector, dbConns int) error { mu.Lock() defer mu.Unlock() if db.Conn != nil { if err := db.Conn.PingContext(ctx); err == nil { // Already connected. return nil } } var dbConnector db.Connector = connector if dbConnector == nil { dbConnector = db.DefaultConnection } conn, err := dbConnector.Connect(dbConns) if err != nil { return errors.New("setup: could not establish a database connection: " + err.Error()) } db.Conn = conn if err := db.Conn.PingContext(ctx); err != nil { return errors.New("setup: could not establish a database connection: " + err.Error()) } return PrepareAll(ctx) } func PrepareAll(ctx context.Context) error { if err := newmodels.Setup(ctx); err != nil { return err } if err := prepare(ctx); err != nil { return err } return nil }
kevinburke/rickover
setup/setup.go
GO
mit
3,406
DayZ Logger v1.0 beta ===================== DayZ Logger is a simple logging tool for DayZ servers, it is intended as a console application and there is no need for an UI. With DayZ Logger you can track all player character changes and save everything to local log files. You can easily customize what data to query and how often to log them. Every player will get their own log file for each day, so you will not end up with one big log file after some time. ## Requirements * DayZ Logger is a simple Java console application, so all you need to get it to work is the Java Runtime Environment (JRE) installed on your computer. The minimum required version is JRE 7. * Access to your DayZ MySQL database. For this application to work it is sufficient to use an MySQL user who has only the SELECT privilege, because it will only query data and never change anything in the database. * For the character query to work properly, the character data table needs a "timestamp on update" field to determine recently active players. If your character data table does not already have a field like this, you can add it with a SQL query: ```sql ALTER TABLE `character_data` ADD `LastUpdated` TIMESTAMP on update CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP; ``` ## Installation Just extract the ZIP file anywhere on your local hard drive. ### Config file Many options and default behaviours can be changed with the provided config file (default name config.cfg). All options have default values, for more information take a look at the provided config.cfg as an example. ## Startup and command line arguments The application can be started from the console like any other JAR file, or use one of the provided Windows BAT files to let it detect your JRE installation and launch it like any Windows application. ``` java -jar DayZLogger.jar [-c <filename>] [-d <debug-level>] ``` The filename can be any valid filename or path to a filename relative to your working directory. The debug-level can be used to get more detailed messages shown in the console window, valid values are: - ALL - shows detailed messages about every action (**Attention**: with this option enabled you will get player name logging, adjust the option *player_name_query* in the debug section of your config file) - TRACE - same as ALL - DEBUG - shows debug messages like log file infos - INFO - default, shows only relevant messages to the user - WARN - shows only warning and errors messages - ERROR - shows only error messages - OFF - shows no messages at all (not recommended) for example ``` java -jar DayZLogger.jar -c config.cfg -d DEBUG ``` It is recommended to run DayZ Logger on the DayZ database server itself. If you just have remote access to the database server, you can run DayZ Logger from anywhere you want. ## Performance and storage usage DayZ Logger is a light weight application, it has almost no CPU impact and a small memory profile as it only caches the current and last values of every player currently playing on the DayZ server and file handles to each log file. Log files will be kept open for appending data until the cleanup routine will close it and remove the player from the cache after an configurable idle time (default 15 minutes). With data pruning enabled (disabled by default, see config file) the storage consumption is about 100 KB a day for every active player (about 5 MB with 50 active players each day). Furthermore old logs can be archived or removed to compress the data even more. ## Copyright and License Copyright (c) 2013 Alexander Vos. Distributed under the The MIT License (MIT). See the LICENSE file for more information.
vos/dayzlogger
README.md
Markdown
mit
3,661
/** * marcstark:meteor-angular-jade-extended * * The plugin file of the extended handler * for Jade in Meteor-Angular projects. * * @see {@link https://github.com/marcstark/meteor-angular-jade-extended.git} * @license MIT */ (function() { 'use strict'; /* jshint validthis:true */ // ***************************************************************************** // Includes // ***************************************************************************** var minify = Npm.require('html-minifier').minify; var jade = Npm.require('jade'); var path = Npm.require('path'); var cheerio = Npm.require('cheerio'); // ***************************************************************************** // Local variables // ***************************************************************************** /** * Local string to identify files ending on "ng.jade". These files are included * into the Angular template cache. * * @type {String} */ var __strMatchNgJade = 'ng.jade'; /** * Local string to identify files ending on "include.jade". These files are * ignored since they should be included by other jade files. * * @type {String} */ var __strMatchIncludeJade = 'include.jade'; /** * Local string to identify files ending on "jade". These files - the rest - are * included into the "body" section of the Meteor layout file. * * @type {String} */ var __strMatchJade = 'jade'; /** * Jade compiling options. Contain file options to include jade files into other * jade files. * * @type {Object} */ var __objJadeOptions = { basedir : process.env.PWD, pretty : true, compileDebug : false, filename : path.join(process.env.PWD, 'index') }; /** * Object of cheerio jQuery interpretation. * * @type {Object} */ var $; // ***************************************************************************** // Plug in register compiler // ***************************************************************************** Plugin.registerCompiler({ extensions: [__strMatchJade], }, function createCompiler() { return (new AngularJadeCompiler()); }); // ***************************************************************************** // Compiler class // ***************************************************************************** /** * This is the Angular Jade compiler class function to be instantiated in * the compiler register method. * * @class AngularJadeCompiler */ function AngularJadeCompiler() {} // ***************************************************************************** /** * Prototype function to process files for target. * @memberof AngularJadeCompiler * * @param {Array} arrFiles array of files to be compiled */ AngularJadeCompiler.prototype.processFilesForTarget = function(arrFiles) { return arrFiles.forEach(_handleFile.call(this)); }; // ***************************************************************************** // Helper functions // ***************************************************************************** /** * @function _handleFile * @private * * Helper function to handle each file separately. * * @return {Function} function handler to handle the file object */ function _handleFile() { var that = this; return function(objFile) { var strFileName; var strFilePath; var strFileContent; var strContentCompiled; var strContentMinified; var objContentMinified; var objHead; var strHead; var objBody; var strBody; var strBodyClasses; var objBodyAttrsRest; var objTemplates; var objScripts; // get file name and content and compile it strFileName = objFile.getBasename(); strFileContent = objFile.getContentsAsString().toString('utf8'); // compile Jade strContentCompiled = _compileJade.call(that, strFileContent, strFileName); // if file ends on "include.jade" if (_isFileOfType(strFileName, __strMatchIncludeJade)) { return; } // if file ends on "ng.jade" else if (_isFileOfType(strFileName, __strMatchNgJade)) { strContentMinified = _minifyHtml.call(that, strContentCompiled); return _addHtmlToAngularTemplateCache.call(that, objFile, strContentMinified); } // get rid of more than one empty space, all new line and tabulator characters strContentCompiled = strContentCompiled .replace(/\s+/, ' ') .replace(/\t/, '') .replace(/\n/g, '') ; // load the compiled HTML into "cheerio" and let it look like jQuery $ = cheerio.load(strContentCompiled); // get DOM of head, body and template if available objHead = $('head'); objBody = $('body'); objTemplates = $('template[name]'); objScripts = $('script[type="text/ng-template"][id]'); // Get strings of inner HTML of each of them but only if they are // root tags. Tags with a parent element are ignored since it is // invalid HTML anyway. Also, minify the strings. // Also, only the first head and body tag is considered. strHead = objHead && objHead[0] && !objHead[0].parent && 'function' === typeof objHead.html && _minifyHtml.call(that, objHead.html()); strBody = objBody && objBody[0] && !objBody[0].parent && 'function' === typeof objBody.html && _minifyHtml.call(that, objBody.html()); strBodyClasses = objBody && 'function' === typeof objBody.attr && objBody.attr('class'); objBodyAttrsRest = objBody && objBody[0] && objBody[0].attribs; // remove "class" attribute if (objBodyAttrsRest && objBodyAttrsRest.class) { delete objBodyAttrsRest.class; } // handle each template and script separately var _templateHandler = _handleTemplate.call(that, objFile); objTemplates.each(_templateHandler); objScripts.each(_templateHandler); // otherwise add head and body to layout separately objContentMinified = { strHead : strHead, strBody : strBody, strBodyClasses : strBodyClasses, objBodyAttrsRest: objBodyAttrsRest, }; return _addHtmlToLayout.call(that, objFile, objContentMinified); }; } // ***************************************************************************** /** * @function _handleTemplate * @private * * Helper function to handle each template in a file separately. * * @param {Object} objFile object of the current file. */ function _handleTemplate(objFile) { var that = this; // if cheerio's jquery is not defined, return an empty function. if (!$) { return function() {}; } return function(numIndex, objTemplate) { var strTemplate, strTemplateName; var objTemplateWrapper = $(this); // Get strings of inner HTML of the template tag only if it is a // root tags. Tags with a parent element are ignored since it is // invalid HTML anyway. Also, minify the strings. // Also, only the first head and body tag is considered. strTemplate = objTemplate && !objTemplate.parent && 'function' === typeof objTemplateWrapper.html && _minifyHtml.call(that, objTemplateWrapper.html()); // Get the template name from the "id" attribute (if the template is a // "script" tag) or - if not available - from the "name" attribute (if // the template is a "template" tag). strTemplateName = (objTemplate.attribs && objTemplate.attribs.id) || (objTemplate.attribs && objTemplate.attribs.name); // If there is a template in the jade file, parse it as if // the file ended in "ng.jade". if (strTemplate && strTemplateName) { _addHtmlToAngularTemplateCache.call(that, objFile, strTemplate, strTemplateName); } }; } // ***************************************************************************** /** * @function _testFileType * @private * * Helper function to compile the jade content and wrap it with an Angular * script tag eventually. * * @param {String} strFileContent string of file content to be compiled * @param {String} strFileName string of file name * @return {String} string of compiled content */ function _compileJade(strFileContent) { return jade.compile(strFileContent.toString('utf8'), __objJadeOptions)({}); } // ***************************************************************************** /** * @function _minifyHtml * @private * * Helper function to minify the HTML content including the * inner HTML of Angular script tags. * * @param {String} strContent string of content to be minified * @return {String} string of result that is minified */ function _minifyHtml(strContent) { if (!strContent) { return null; } // escape single quotes in content strContent = strContent.replace(/'/g, "\\'"); // minify content including the inner of Angular script tags var strResult = minify(strContent, { collapseWhitespace : true, conservativeCollapse : true, removeComments : true, minifyJS : true, minifyCSS : true, processScripts : ['text/ng-template'], }); // escape newline characters strResult.replace(/\n/g, '\\n'); return strResult; } // ***************************************************************************** /** * @function _addHtmlToAngularTemplateCache * @private * * Helper function to add the compiled and minified HTML as a Template to the * Angular Template cache. * * @param {Object} objFile object of the file that was compiled and minified * @param {String} strContentMinified string of the compiled and minified content of the file * @param {String} [strTemplateName] string of the name/path of the template (optional) */ function _addHtmlToAngularTemplateCache(objFile, strContentMinified, strTemplateName) { var strFilePath, strFileName, strFileNameEscaped, strVarName, strAngularTemplateCacheCommand; // If there is a name for the template, use the name. if (strTemplateName) { strFileName = strTemplateName; strFilePath = path.join(objFile.getDirname(), strTemplateName).replace(/\\/g, '/'); } // Otherwise use the base name. else { strFileName = objFile.getBasename(); strFileName = strFileName && strFileName.replace(__strMatchNgJade, 'html'); strFilePath = objFile.getPathInPackage(); strFilePath = strFilePath.replace(/\\/g, '/'); // replace back slashes (if necessary) strFilePath = strFilePath.replace(__strMatchNgJade, 'html'); } // If file name or path is not set, return. if (!strFileName || !strFilePath) { return; } strFileNameEscaped = strFileName.replace(/[^a-zA-Z]/g, '_'); strAngularTemplateCacheCommand = [ "angular.module('angular-meteor')", ".constant('C_", strFileNameEscaped, "', '", strContentMinified, "')", ".run(['$templateCache', 'C_", strFileNameEscaped, "', function($templateCache, C_", strFileNameEscaped, ") { ", "$templateCache.put('", strFileName, "', C_", strFileNameEscaped, ");", "$templateCache.put('", strFilePath, "', C_", strFileNameEscaped, ");", "}]);", ].join(''); objFile.addJavaScript({ data : strAngularTemplateCacheCommand, path : strFilePath, sourcePath : objFile.getPathInPackage(), }); // ************************************************************************* // // delete everything except letters // strVarName = '__' + strFileName.replace(/[^a-zA-Z]+/g, ''); // // Alternative: // strAngularTemplateCacheCommand = [ // "angular.module('angular-meteor').run(['$templateCache', function($templateCache) { ", // "var ", strVarName, " = '", strContentMinified, "';", // "$templateCache.put('", strFileName, "', ", strVarName , ");", // "$templateCache.put('", strFilePath, "', ", strVarName , ");", // "}]);", // ].join(''); } // ***************************************************************************** /** * @function _addHtmlToLayout * @private * * Helper function to add the final HTML to the file object. * * @param {Object} objFile object of file the HTML will be added to * @param {Object} objContentMinified object of compiled and minified content * @param {String} objContentMinified.strHead string of the compiled and minified HTML head * @param {String} objContentMinified.strBody string of the compiled and minified HTML body * @param {String} objContentMinified.strBodyClasses string of the body's class attribute * @param {String} objContentMinified.objBodyAttrsRest string of the body's attributes other than "class" */ function _addHtmlToLayout(objFile, objContentMinified) { var strFilePath, strJavaScript = ''; // if "jade" files are not in web targets, aboard if (objFile.getArch().indexOf('web.browser') < 0) { console.log('\n'); console.log('WARNING from package "marcstark:meteor-angular-jade-extended":' + '\n'); console.log([ 'Document sections can only be emitted to web targets. ', 'This error appears if you use ".jade" files outside ', 'of the web target arch. ', 'To avoid this, move all ".jade" files into the "client" ', 'folder or corresponding sub-folders.' ].join('') + '\n'); return; } if (objContentMinified.strHead) { objFile.addHtml({ section : 'head', data : objContentMinified.strHead, }); } if (objContentMinified.strBody) { objFile.addHtml({ section : 'body', data : objContentMinified.strBody, }); } if (objContentMinified.strBody && objContentMinified.strBodyClasses) { strJavaScript += [ "$('body').addClass('", objContentMinified.strBodyClasses , "');" ].join(''); } if (objContentMinified.strBody && objContentMinified.objBodyAttrsRest) { strJavaScript += [ "$('body').attr(", JSON.stringify(objContentMinified.objBodyAttrsRest) , ");", ].join(''); } if (objContentMinified.strBody && (objContentMinified.strBodyClasses || objContentMinified.objBodyAttrsRest)) { strFilePath = objFile.getPathInPackage(); strFilePath = strFilePath.replace(/\\/g, '/'); // replace back slashes (if necessary) strFilePath = strFilePath.replace(__strMatchNgJade, 'html'); strJavaScript = ["Meteor.startup(function() { ", strJavaScript, " });"].join(''); objFile.addJavaScript({ path: strFilePath, data: strJavaScript, }); } } // ***************************************************************************** /** * @function _isFileOfType * @private * * Helper function to test whether a given file name is type of a given * extension or not. * * @param {String} strFileName string of name of file to be compiled * @param {String} strExtension string of the extension to test the file for */ function _isFileOfType(strFileName, strExtension) { var regexIdentification = new RegExp(strExtension + '$', 'gi'); var isExtension = !!regexIdentification.test(strFileName); return isExtension; } // ***************************************************************************** })();
marcstark/meteor-angular-jade-extended
plugin/plugin.js
JavaScript
mit
16,117
<?php /** * $Id$ * * @author Martin Lindhe, 2011 <[email protected]> */ //STATUS: early wip namespace cd; // types: define('RESERVED_USERNAME', 1); class ReservedWord { var $id; var $type; var $value; protected static $tbl_name = 'tblReservedWords'; public static function getAll($type) { $q = 'SELECT * FROM '.self::$tbl_name. ' WHERE type = ?'. ' ORDER BY value ASC'; $res = Sql::pSelect($q, 'i', $type); return SqlObject::loadObjects($res, __CLASS__); } public static function get($id) { return SqlObject::getById($id, self::$tbl_name, __CLASS__); } public static function isReservedUsername($s) { $s = trim($s); $q = 'SELECT COUNT(*) FROM '.self::$tbl_name. ' WHERE type = ?'. ' AND value = ?'; $val = Sql::pSelectItem($q, 'is', RESERVED_USERNAME, $s); if ($val) return true; return false; } } ?>
martinlindhe/core_dev
core/ReservedWord.php
PHP
mit
1,002
#!/usr/bin/env python # # Copyright (C) 2014 # Brian Caswell <[email protected]> # Narf Industries <[email protected]> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # import string import sys import os from generator.actions import Actions from random import choice,randint from struct import * from os.path import dirname, abspath, join from commands import getoutput from re import escape from collections import OrderedDict cb_base = dirname(dirname(dirname(abspath(__file__)))) cb = join(cb_base, "build/release/bin/NRFIN_00071") req = { "MKDIR":0, "LIST":1, "PUT":2, "GET":3, "RM":4, "RMDIR":5, "QUIT":6, } resp = { "MKDIR_OK":0, "MKDIR_FAIL":1, "LIST_OK":2, "LIST_FAIL":3, "PUT_OK":4, "PUT_FAIL":5, "GET_OK":6, "GET_FAIL":7, "RM_OK":8, "RM_FAIL":9, "RMDIR_OK":10, "RMDIR_FAIL":11, "QUIT_OK":12 } README = "This is a sample file! Feel free to add your own!" def random_alpha(a, b): return ''.join(choice(string.letters) for _ in range(randint(a, b))) x,y,z,w = 0,0,0,0 def getshifty(): global x, y, z, w tmp = x ^ ((x<<12)&0xffffffff) x = y y = z z = w w = w ^ (w>>18) ^ tmp ^ (tmp >> 9) return w def xor(x,y): return x^y def chunks(l, n): for i in xrange(0, len(l), n): yield l[i:i+n] class SBTP(Actions): def start(self): #self.delay(100) #init prng global x, y, z, w x = reduce(xor, unpack("<II",self.magic_page[:8])) y = reduce(xor,unpack("<II",self.magic_page[8:16])) z = reduce(xor,unpack("<II",self.magic_page[16:24])) w = reduce(xor,unpack("<II",self.magic_page[24:32])) #set up our config self.version = randint(0xc0ff33,0xffffffff) self.min_ver = randint(0,0xc0ff32) #we make a point to always "encrypt" #and see if competitors discover/choose to use plaintext self.encrypt = 0 self.allow_reconnect = 1 self.buf_size = 0 self.files = OrderedDict([("#README",README)]) self.subdir = None def do_session(self): #want to ensure teams can't just get rid of reconnects #but don't want to make polls take *overly* long if randint(0,50) == 42: self.doreconn() options = [ self.add_rootfile, self.add_subdir, self.add_subfile, self.list_root, self.list_root, self.list_subdir, self.get_all_files, self.rm_subdir_file, self.rm_subdir, self.rm_all_files, self.add_subdir, self.add_subfile, self.get_all_files, ] for i in range(randint(10,50)): choice(options)() def verify(self): #ensure cb is built if not os.path.exists(cb): os.system("make -C %s build" % cb_base) readcgcef = getoutput("readcgcef -a %s" % cb) for line in readcgcef.split("\n"): parts = line.split() if len(parts) != 7: continue if parts[6] == "go": start = int(parts[1],16)-0x8048000 if parts[6] == "longjmp": end = int(parts[1],16)-0x8048000 csum = getshifty(); magic = 0x1337b33f ^ reduce(xor, unpack("<II",self.magic_page[:8])) cbdata = open(cb,"r").read() for i in range(start,end,4): csum ^= unpack("<I",cbdata[i:i+4])[0] magic = pack(">I",magic).encode("hex").upper() csum = pack(">I",csum).encode("hex").upper() #leaving debug magic in on the off chance anyone manages to brute force it self.read(length=8, expect="("+magic+"|"+csum+")", expect_format="pcre") self.write(pack("<I",1)) def read_seed(self): global x, y, z, w if self.encrypt: x = xor(*unpack("<II",self.magic_page[32:40])) y = xor(*unpack("<II",self.magic_page[40:48])) z = xor(*unpack("<II",self.magic_page[48:56])) w = xor(*unpack("<II",self.magic_page[56:64])) else: x,y,z,w = 0,0,0,0 self.read(length=16, expect=pack("<IIII",x,y,z,w)) def send_conf(self): self.write(pack("<IIIII",self.version, self.min_ver, self.encrypt, self.allow_reconnect, self.buf_size)) self.read(length=4, expect=pack("<I",1)) def doreconn(self): self.delay(3000) self.write(pack("<IIIII",self.version, self.min_ver, self.encrypt, self.allow_reconnect, self.buf_size)) self.write(pack("<I",0)) self.doread(pack("<I1024s", resp['GET_OK'], README)) def _enc(self,s): if (len(s) % 4) != 0: raise Exception("Must be 4 byte aligned.") res = [] for dword in chunks(s,4): tmp = getshifty() res.append(pack("<I",tmp^unpack("<I",dword)[0])) return "".join(res) def dowrite(self,s): if (self.encrypt): s = self._enc(s) self.write(s) def doread(self,s): if (self.encrypt): s = self._enc(s) self.read(length=len(s), expect=s) def get_file(self, fn, data): self.dowrite(pack("<I1024s", req['GET'], fn)) self.doread(pack("<I1024s", resp['GET_OK'], data)) def get_file_fail(self,fn): self.dowrite(pack("<I1024s", req['GET'], fn)) self.doread(pack("<I1024s", resp['GET_FAIL'], "")) def get_readme(self): self.get_file("#README", README) def put_file(self, fn, data): self.dowrite(pack("<I1024s", req['PUT'],fn+'\x00'+data)) self.doread(pack("<I1024s", resp['PUT_OK'], '')) self.files[fn] = data def add_rootfile(self): for i in range(randint(0,5)): fn = "#"+random_alpha(4,20) if fn not in self.files: data = random_alpha(1,900) self.put_file(fn, data) def ls_dir(self, path, files=[]): files = [f.split("#")[-1] for f in files] self.dowrite(pack("<I1024s", req['LIST'],path+'\x00')) self.doread(pack("<I1024s", resp['LIST_OK'],":".join(files))) def list_root(self): self.ls_dir("#", [fn for fn in self.files if fn.count("#") == 1]) def list_subdir(self): if not self.subdir: self.add_subdir() self.ls_dir(self.subdir, [fn for fn in self.files if fn.startswith(self.subdir+"#")]) def add_subdir(self): if self.subdir: self.rm_subdir() self.subdir = "#"+random_alpha(4,20) self.dowrite(pack("<I1024s", req['MKDIR'], self.subdir)) self.doread(pack("<I1024s", resp['MKDIR_OK'], '')) def add_subfile(self): if not self.subdir: self.add_subdir() for i in range(randint(0,5)): fn = self.subdir+"#"+random_alpha(4,20) if fn not in self.files: data = random_alpha(1,900) self.put_file(fn, data) def get_all_files(self): for fn,data in self.files.items(): self.get_file(fn,data) def rm(self, path): self.dowrite(pack("<I1024s", req['RM'], path)) self.doread(pack("<I1024s", resp['RM_OK'], '')) #confirm deletion self.get_file_fail(path) del(self.files[path]) def rm_dir(self, path): self.dowrite(pack("<I1024s", req['RMDIR'], path)) self.doread(pack("<I1024s", resp['RMDIR_OK'], '')) deleted = [fn for fn in self.files if fn.startswith(path+"#")] #confirm deletion for fn in deleted: self.get_file_fail(fn) del(self.files[fn]) def rm_all_files(self): for fn in self.files: self.rm(fn) self.files = OrderedDict() def rm_subdir_file(self): if not self.subdir: self.add_subdir() sfiles = [fn for fn in self.files if fn.startswith(self.subdir+"#")] if len(sfiles) != 0: self.rm(choice(sfiles)) def rm_subdir(self): if not self.subdir: self.add_subdir() self.rm_dir(self.subdir) self.subdir = None def quit(self): self.dowrite(pack("<I1024s", req['QUIT'],""))
f0rki/cb-multios
disabled-challenges/SBTP/poller/for-release/machine.py
Python
mit
9,303
<html> <body> The common controllers are shared by builder and game. </body> </html>
Betta-Testers/Imbrius-Kabasuji
src/controllers/common/package.html
HTML
mit
84
var Schema = storage.Schema , utils = storage.utils , random = utils.random; var StorageArray = storage.Types.Array , collection = 'avengers_'+random(); var UserSchemaArrayTest = new Schema({ name: String , pets: [Schema.ObjectId] }); var UserCollection = storage.createCollection('UserArrayTest', UserSchemaArrayTest); var PetSchema = new Schema({ name: String }); var PetCollection = storage.createCollection('Pet', PetSchema); /** * Test. */ describe('types array', function(){ it('behaves and quacks like an Array', function(done){ var a = new StorageArray; assert.ok( a instanceof Array ); assert.ok( a.isStorageArray ); assert.equal(true, Array.isArray(a)); done(); }); describe('indexOf()', function(){ it('works', function(done){ var tj = UserCollection.add({ name: 'tj' }) , tobi = PetCollection.add({ name: 'tobi' }) , loki = PetCollection.add({ name: 'loki' }) , jane = PetCollection.add({ name: 'jane' }); tj.pets.push(tobi); tj.pets.push(loki); tj.pets.push(jane); var pending = 3; ;[tobi, loki, jane].forEach(function(pet){ pet.save(function(){ --pending || cb(); }); }); function cb() { tj.save(function(){ assert.equal(tj.pets.length, 3); assert.equal(tj.pets.indexOf(tobi.id),0); assert.equal(tj.pets.indexOf(loki.id),1); assert.equal(tj.pets.indexOf(jane.id),2); assert.equal(tj.pets.indexOf(tobi._id),0); assert.equal(tj.pets.indexOf(loki._id),1); assert.equal(tj.pets.indexOf(jane._id),2); done(); }); } }); }); describe('splice()', function(){ it('works', function(done){ var schema = new Schema({ numbers: [Number] }) , A = storage.createCollection('splicetestNumber', schema ); var a = A.add({ numbers: [4,5,6,7] }); a.save(function ( doc ) { var removed = doc.numbers.splice(1, 1, "10"); assert.deepEqual(removed, [5]); assert.equal('number', typeof doc.numbers[1]); assert.deepEqual(doc.numbers.toObject(),[4,10,6,7]); doc.save(function (doc1) { assert.deepEqual(doc1.numbers.toObject(), [4,10,6,7]); done(); }); }); }); it('on embedded docs', function(done){ var schema = new Schema({ types: [new Schema({ type: String }) ]}) , A = storage.createCollection('splicetestEmbeddedDoc', schema ); var a = A.add({ types: [{type:'bird'},{type:'boy'},{type:'frog'},{type:'cloud'}] }); a.save(function (doc) { var removed = doc.types.splice(1, 1); assert.equal(removed.length,1); assert.equal(removed[0].type,'boy'); var obj = doc.types.toObject(); assert.equal(obj[0].type,'bird'); assert.equal(obj[1].type,'frog'); doc.save(function ( doc1 ) { var obj = doc1.types.toObject(); assert.equal(obj[0].type,'bird'); assert.equal(obj[1].type,'frog'); done(); }); }); }); }); describe('unshift()', function(){ it('works', function(done){ var schema = new Schema({ types: [new Schema({ type: String })] , nums: [Number] , strs: [String] }) , A = storage.createCollection('unshift', schema); var a = A.add({ types: [{type:'bird'},{type:'boy'},{type:'frog'},{type:'cloud'}] , nums: [1,2,3] , strs: 'one two three'.split(' ') }); a.save(function ( doc ) { var tlen = doc.types.unshift({type:'tree'}); var nlen = doc.nums.unshift(0); var slen = doc.strs.unshift('zero'); assert.equal(tlen,5); assert.equal(nlen,4); assert.equal(slen,4); doc.types.push({type:'worm'}); var obj = doc.types.toObject(); assert.equal(obj[0].type,'tree'); assert.equal(obj[1].type,'bird'); assert.equal(obj[2].type,'boy'); assert.equal(obj[3].type,'frog'); assert.equal(obj[4].type,'cloud'); assert.equal(obj[5].type,'worm'); obj = doc.nums.toObject(); assert.equal(obj[0].valueOf(),0); assert.equal(obj[1].valueOf(),1); assert.equal(obj[2].valueOf(),2); assert.equal(obj[3].valueOf(),3); obj = doc.strs.toObject(); assert.equal(obj[0],'zero'); assert.equal(obj[1],'one'); assert.equal(obj[2],'two'); assert.equal(obj[3],'three'); doc.save(function (doc1) { var obj = doc1.types.toObject(); assert.equal(obj[0].type,'tree'); assert.equal(obj[1].type,'bird'); assert.equal(obj[2].type,'boy'); assert.equal(obj[3].type,'frog'); assert.equal(obj[4].type,'cloud'); assert.equal(obj[5].type,'worm'); obj = doc1.nums.toObject(); assert.equal(obj[0].valueOf(),0); assert.equal(obj[1].valueOf(),1); assert.equal(obj[2].valueOf(),2); assert.equal(obj[3].valueOf(),3); obj = doc1.strs.toObject(); assert.equal(obj[0],'zero'); assert.equal(obj[1],'one'); assert.equal(obj[2],'two'); assert.equal(obj[3],'three'); done(); }); }); }); }); describe('shift()', function(){ it('works', function(done){ var schema = new Schema({ types: [new Schema({ type: String })] , nums: [Number] , strs: [String] }); var A = storage.createCollection('shift', schema ); var a = A.add({ types: [{type:'bird'},{type:'boy'},{type:'frog'},{type:'cloud'}] , nums: [1,2,3] , strs: 'one two three'.split(' ') }); a.save(function (doc) { var t = doc.types.shift(); var n = doc.nums.shift(); var s = doc.strs.shift(); assert.equal(t.type,'bird'); assert.equal(n,1); assert.equal(s,'one'); var obj = doc.types.toObject(); assert.equal(obj[0].type,'boy'); assert.equal(obj[1].type,'frog'); assert.equal(obj[2].type,'cloud'); doc.nums.push(4); obj = doc.nums.toObject(); assert.equal(2, obj[0].valueOf()); assert.equal(obj[1].valueOf(),3); assert.equal(obj[2].valueOf(),4); obj = doc.strs.toObject(); assert.equal(obj[0],'two'); assert.equal(obj[1],'three'); doc.save(function (doc1) { var obj = doc1.types.toObject(); assert.equal(obj[0].type,'boy'); assert.equal(obj[1].type,'frog'); assert.equal(obj[2].type,'cloud'); obj = doc1.nums.toObject(); assert.equal(obj[0].valueOf(),2); assert.equal(obj[1].valueOf(),3); assert.equal(obj[2].valueOf(),4); obj = doc1.strs.toObject(); assert.equal(obj[0],'two'); assert.equal(obj[1],'three'); done(); }); }); }); }); describe('pop()', function(){ it('works', function(done){ var schema = new Schema({ types: [new Schema({ type: String })] , nums: [Number] , strs: [String] }); var A = storage.createCollection('pop', schema); var a = A.add({ types: [{type:'bird'},{type:'boy'},{type:'frog'},{type:'cloud'}] , nums: [1,2,3] , strs: 'one two three'.split(' ') }); a.save(function (doc) { var t = doc.types.pop(); var n = doc.nums.pop(); var s = doc.strs.pop(); assert.equal(t.type,'cloud'); assert.equal(n,3); assert.equal(s,'three'); var obj = doc.types.toObject(); assert.equal(obj[0].type,'bird'); assert.equal(obj[1].type,'boy'); assert.equal(obj[2].type,'frog'); doc.nums.push(4); obj = doc.nums.toObject(); assert.equal(obj[0].valueOf(),1); assert.equal(obj[1].valueOf(),2); assert.equal(obj[2].valueOf(),4); obj = doc.strs.toObject(); assert.equal(obj[0],'one'); assert.equal(obj[1],'two'); doc.save(function (doc1) { var obj = doc1.types.toObject(); assert.equal(obj[0].type,'bird'); assert.equal(obj[1].type,'boy'); assert.equal(obj[2].type,'frog'); obj = doc1.nums.toObject(); assert.equal(obj[0].valueOf(),1); assert.equal(obj[1].valueOf(),2); assert.equal(obj[2].valueOf(),4); obj = doc1.strs.toObject(); assert.equal(obj[0],'one'); assert.equal(obj[1],'two'); done(); }); }); }); }); describe('pull()', function(){ it('works', function(done){ var catSchema = new Schema({ name: String }) var Cat = storage.createCollection('Cat', catSchema); var schema = new Schema({ a: [{ type: Schema.ObjectId, ref: 'Cat' }] }); var A = storage.createCollection('TestPull', schema); var cat = Cat.add({ name: 'peanut' }); cat.save(function () { var a = A.add({ a: [cat._id] }); a.save(function ( doc ) { assert.equal(1, doc.a.length); doc.a.pull(cat.id); assert.equal(doc.a.length,0); done(); }); }); }); }); describe('addToSet()', function(){ it('works', function(done){ var e = new Schema({ name: String, arr: [] }) , schema = new Schema({ num: [Number] , str: [String] , doc: [e] , date: [Date] , id: [Schema.ObjectId] }); var collection = storage.createCollection('testAddToSet', schema); var doc = collection.add(); doc.num.push(1,2,3); doc.str.push('one','two','tres'); doc.doc.push({ name: 'Dubstep', arr: [1] }, { name: 'Polka', arr: [{ x: 3 }]}); var d1 = new Date; var d2 = new Date( +d1 + 60000); var d3 = new Date( +d1 + 30000); var d4 = new Date( +d1 + 20000); var d5 = new Date( +d1 + 90000); var d6 = new Date( +d1 + 10000); doc.date.push(d1, d2); var id1 = new storage.Types.ObjectId; var id2 = new storage.Types.ObjectId; var id3 = new storage.Types.ObjectId; var id4 = new storage.Types.ObjectId; var id5 = new storage.Types.ObjectId; var id6 = new storage.Types.ObjectId; doc.id.push(id1, id2); doc.num.addToSet(3,4,5); assert.equal(5, doc.num.length); doc.str.addToSet('four', 'five', 'two'); assert.equal(doc.str.length,5); doc.id.addToSet(id2, id3); assert.equal(doc.id.length,3); doc.doc.addToSet(doc.doc[0]); assert.equal(doc.doc.length,2); doc.doc.addToSet({ name: 'Waltz', arr: [1] }, doc.doc[0]); assert.equal(doc.doc.length,3); assert.equal(doc.date.length,2); doc.date.addToSet(d1); assert.equal(doc.date.length,2); doc.date.addToSet(d3); assert.equal(doc.date.length,3); doc.save(function (doc) { assert.equal(doc.num.length,5); assert.ok(~doc.num.indexOf(1)); assert.ok(~doc.num.indexOf(2)); assert.ok(~doc.num.indexOf(3)); assert.ok(~doc.num.indexOf(4)); assert.ok(~doc.num.indexOf(5)); assert.equal(doc.str.length,5); assert.ok(~doc.str.indexOf('one')); assert.ok(~doc.str.indexOf('two')); assert.ok(~doc.str.indexOf('tres')); assert.ok(~doc.str.indexOf('four')); assert.ok(~doc.str.indexOf('five')); assert.equal(doc.id.length,3); assert.ok(~doc.id.indexOf(id1)); assert.ok(~doc.id.indexOf(id2)); assert.ok(~doc.id.indexOf(id3)); assert.equal(doc.date.length,3); assert.ok(~doc.date.indexOf(d1.toString())); assert.ok(~doc.date.indexOf(d2.toString())); assert.ok(~doc.date.indexOf(d3.toString())); assert.equal(doc.doc.length,3); assert.ok(doc.doc.some(function(v){return v.name === 'Waltz'})) assert.ok(doc.doc.some(function(v){return v.name === 'Dubstep'})) assert.ok(doc.doc.some(function(v){return v.name === 'Polka'})) // test single $addToSet doc.num.addToSet(3,4,5,6); assert.equal(doc.num.length,6); doc.str.addToSet('four', 'five', 'two', 'six'); assert.equal(doc.str.length,6); doc.id.addToSet(id2, id3, id4); assert.equal(doc.id.length,4); doc.date.addToSet(d1, d3, d4); assert.equal(doc.date.length,4); doc.doc.addToSet(doc.doc[0], { name: '8bit' }); assert.equal(doc.doc.length,4); doc.save(function (doc) { assert.equal(doc.num.length,6); assert.ok(~doc.num.indexOf(1)); assert.ok(~doc.num.indexOf(2)); assert.ok(~doc.num.indexOf(3)); assert.ok(~doc.num.indexOf(4)); assert.ok(~doc.num.indexOf(5)); assert.ok(~doc.num.indexOf(6)); assert.equal(doc.str.length,6); assert.ok(~doc.str.indexOf('one')); assert.ok(~doc.str.indexOf('two')); assert.ok(~doc.str.indexOf('tres')); assert.ok(~doc.str.indexOf('four')); assert.ok(~doc.str.indexOf('five')); assert.ok(~doc.str.indexOf('six')); assert.equal(doc.id.length,4); assert.ok(~doc.id.indexOf(id1)); assert.ok(~doc.id.indexOf(id2)); assert.ok(~doc.id.indexOf(id3)); assert.ok(~doc.id.indexOf(id4)); assert.equal(doc.date.length,4); assert.ok(~doc.date.indexOf(d1.toString())); assert.ok(~doc.date.indexOf(d2.toString())); assert.ok(~doc.date.indexOf(d3.toString())); assert.ok(~doc.date.indexOf(d4.toString())); assert.equal(doc.doc.length,4); assert.ok(doc.doc.some(function(v){return v.name === 'Waltz'})); assert.ok(doc.doc.some(function(v){return v.name === 'Dubstep'})); assert.ok(doc.doc.some(function(v){return v.name === 'Polka'})); assert.ok(doc.doc.some(function(v){return v.name === '8bit'})); // test multiple $addToSet doc.num.addToSet(7,8); assert.equal(doc.num.length,8); doc.str.addToSet('seven', 'eight'); assert.equal(doc.str.length,8); doc.id.addToSet(id5, id6); assert.equal(doc.id.length,6); doc.date.addToSet(d5, d6); assert.equal(doc.date.length,6); doc.doc.addToSet(doc.doc[1], { name: 'BigBeat' }, { name: 'Funk' }); assert.equal(doc.doc.length,6); doc.save(function (doc) { assert.equal(doc.num.length,8); assert.ok(~doc.num.indexOf(1)); assert.ok(~doc.num.indexOf(2)); assert.ok(~doc.num.indexOf(3)); assert.ok(~doc.num.indexOf(4)); assert.ok(~doc.num.indexOf(5)); assert.ok(~doc.num.indexOf(6)); assert.ok(~doc.num.indexOf(7)); assert.ok(~doc.num.indexOf(8)); assert.equal(doc.str.length,8); assert.ok(~doc.str.indexOf('one')); assert.ok(~doc.str.indexOf('two')); assert.ok(~doc.str.indexOf('tres')); assert.ok(~doc.str.indexOf('four')); assert.ok(~doc.str.indexOf('five')); assert.ok(~doc.str.indexOf('six')); assert.ok(~doc.str.indexOf('seven')); assert.ok(~doc.str.indexOf('eight')); assert.equal(doc.id.length,6); assert.ok(~doc.id.indexOf(id1)); assert.ok(~doc.id.indexOf(id2)); assert.ok(~doc.id.indexOf(id3)); assert.ok(~doc.id.indexOf(id4)); assert.ok(~doc.id.indexOf(id5)); assert.ok(~doc.id.indexOf(id6)); assert.equal(doc.date.length,6); assert.ok(~doc.date.indexOf(d1.toString())); assert.ok(~doc.date.indexOf(d2.toString())); assert.ok(~doc.date.indexOf(d3.toString())); assert.ok(~doc.date.indexOf(d4.toString())); assert.ok(~doc.date.indexOf(d5.toString())); assert.ok(~doc.date.indexOf(d6.toString())); assert.equal(doc.doc.length,6); assert.ok(doc.doc.some(function(v){return v.name === 'Waltz'})); assert.ok(doc.doc.some(function(v){return v.name === 'Dubstep'})); assert.ok(doc.doc.some(function(v){return v.name === 'Polka'})); assert.ok(doc.doc.some(function(v){return v.name === '8bit'})); assert.ok(doc.doc.some(function(v){return v.name === 'BigBeat'})); assert.ok(doc.doc.some(function(v){return v.name === 'Funk'})); done(); }); }); }); }); it('handles sub-documents that do not have an _id gh-1973', function(done) { var e = new Schema({ name: String, arr: [] }, { _id: false }) , schema = new Schema({ doc: [e] }); var M = storage.createCollection('gh1973', schema); var m = M.add(); m.doc.addToSet({ name: 'Rap' }); m.save(function(m) { assert.equal(1, m.doc.length); assert.equal('Rap', m.doc[0].name); m.doc.addToSet({ name: 'House' }); assert.equal(2, m.doc.length); m.save(function(m) { assert.equal(2, m.doc.length); assert.ok(m.doc.some(function(v) { return v.name === 'Rap' })); assert.ok(m.doc.some(function(v) { return v.name === 'House' })); done(); }); }); }); }); describe('sort()', function(){ it('order should be saved', function(done){ var M = storage.createCollection('ArraySortOrder', new Schema({ x: [Number] })); var m = M.add({ x: [1,4,3,2] }); m.save(function (m) { assert.equal(1, m.x[0]); assert.equal(4, m.x[1]); assert.equal(3, m.x[2]); assert.equal(2, m.x[3]); m.x.sort(); m.save(function (m1) { assert.equal(1, m1.x[0]); assert.equal(2, m1.x[1]); assert.equal(3, m1.x[2]); assert.equal(4, m1.x[3]); m1.x.sort(function(a,b){ return b - a; }); m1.save(function (m2) { assert.equal(4, m2.x[0]); assert.equal(3, m2.x[1]); assert.equal(2, m2.x[2]); assert.equal(1, m2.x[3]); done(); }); }); }); }); }); describe('set()', function(){ var N, S, B, M, D; function save (doc, cb) { doc.save(function (doc) { cb( doc ); }, true) } before(function(done){ N = storage.createCollection('arraySet', Schema({ arr: [Number] })); S = storage.createCollection('arraySetString', Schema({ arr: [String] })); M = storage.createCollection('arraySetMixed', Schema({ arr: [] })); D = storage.createCollection('arraySetSubDocs', Schema({ arr: [{ name: String}] })); done(); }); it('works combined with other ops', function(done){ var m = N.add({ arr: [3,4,5,6] }); save(m, function (doc) { assert.equal(4, doc.arr.length); doc.arr.push(20); doc.arr.set(2, 10); assert.equal(5, doc.arr.length); assert.equal(10, doc.arr[2]); assert.equal(20, doc.arr[4]); save(doc, function (doc) { assert.equal(5, doc.arr.length); assert.equal(3, doc.arr[0]); assert.equal(4, doc.arr[1]); assert.equal(10, doc.arr[2]); assert.equal(6, doc.arr[3]); assert.equal(20, doc.arr[4]); doc.arr.set(4, 99); assert.equal(5, doc.arr.length); assert.equal(99, doc.arr[4]); doc.arr.remove(10); assert.equal(4, doc.arr.length); assert.equal(3, doc.arr[0]); assert.equal(4, doc.arr[1]); assert.equal(6, doc.arr[2]); assert.equal(99, doc.arr[3]); save(doc, function (doc) { assert.equal(4, doc.arr.length); assert.equal(3, doc.arr[0]); assert.equal(4, doc.arr[1]); assert.equal(6, doc.arr[2]); assert.equal(99, doc.arr[3]); done(); }); }); }); // after this works go back to finishing doc.populate() branch }); it('works with numbers', function(done){ var m = N.add({ arr: [3,4,5,6] }); save(m, function (doc) { assert.equal(4, doc.arr.length); doc.arr.set(2, 10); assert.equal(4, doc.arr.length); assert.equal(10, doc.arr[2]); doc.arr.set(doc.arr.length, 11); assert.equal(5, doc.arr.length); assert.equal(11, doc.arr[4]); save(doc, function ( doc) { assert.equal(5, doc.arr.length); assert.equal(3, doc.arr[0]); assert.equal(4, doc.arr[1]); assert.equal(10, doc.arr[2]); assert.equal(6, doc.arr[3]); assert.equal(11, doc.arr[4]); // casting + setting beyond current array length doc.arr.set(8, "1"); assert.equal(9, doc.arr.length); assert.strictEqual(1, doc.arr[8]); assert.equal(undefined, doc.arr[7]); save(doc, function ( doc) { assert.equal(9, doc.arr.length); assert.equal(3, doc.arr[0]); assert.equal(4, doc.arr[1]); assert.equal(10, doc.arr[2]); assert.equal(6, doc.arr[3]); assert.equal(11, doc.arr[4]); assert.equal(null, doc.arr[5]); assert.equal(null, doc.arr[6]); assert.equal(null, doc.arr[7]); assert.strictEqual(1, doc.arr[8]); done(); }) }); }); }); it('works with strings', function(done){ var m = S.add({ arr: [3,4,5,6] }); save(m, function (doc) { assert.equal('4', doc.arr.length); doc.arr.set(2, 10); assert.equal(4, doc.arr.length); assert.equal('10', doc.arr[2]); doc.arr.set(doc.arr.length, '11'); assert.equal(5, doc.arr.length); assert.equal('11', doc.arr[4]); save(doc, function (doc) { assert.equal(5, doc.arr.length); assert.equal('3', doc.arr[0]); assert.equal('4', doc.arr[1]); assert.equal('10', doc.arr[2]); assert.equal('6', doc.arr[3]); assert.equal('11', doc.arr[4]); // casting + setting beyond current array length doc.arr.set(8, "yo"); assert.equal(9, doc.arr.length); assert.strictEqual("yo", doc.arr[8]); assert.equal(undefined, doc.arr[7]); save(doc, function (doc) { assert.equal('9', doc.arr.length); assert.equal('3', doc.arr[0]); assert.equal('4', doc.arr[1]); assert.equal('10', doc.arr[2]); assert.equal('6', doc.arr[3]); assert.equal('11', doc.arr[4]); assert.equal(null, doc.arr[5]); assert.equal(null, doc.arr[6]); assert.equal(null, doc.arr[7]); assert.strictEqual('yo', doc.arr[8]); done(); }) }); }); }); it('works with mixed', function(done){ var m = M.add({ arr: [3,{x:1},'yes', [5]] }); save(m, function (doc) { assert.equal(4, doc.arr.length); doc.arr.set(2, null); assert.equal(4, doc.arr.length); assert.equal(null, doc.arr[2]); doc.arr.set(doc.arr.length, "last"); assert.equal(5, doc.arr.length); assert.equal("last", doc.arr[4]); save(doc, function (doc) { assert.equal(5, doc.arr.length); assert.equal(3, doc.arr[0]); assert.strictEqual(1, doc.arr[1].x); assert.equal(null, doc.arr[2]); assert.ok(Array.isArray(doc.arr[3])); assert.equal(5, doc.arr[3][0]); assert.equal("last", doc.arr[4]); doc.arr.set(8, Infinity); assert.equal(9, doc.arr.length); assert.strictEqual(Infinity, doc.arr[8]); assert.equal(undefined, doc.arr[7]); assert.equal(9, doc.arr.length); save(doc, function (doc) { assert.equal(9, doc.arr.length); assert.equal(3, doc.arr[0]); assert.strictEqual(1, doc.arr[1].x); assert.equal(null, doc.arr[2]); assert.ok(Array.isArray(doc.arr[3])); assert.equal(5, doc.arr[3][0]); assert.equal("last", doc.arr[4]); assert.strictEqual(undefined, doc.arr[5]); assert.strictEqual(undefined, doc.arr[6]); assert.strictEqual(undefined, doc.arr[7]); assert.strictEqual(Infinity, doc.arr[8]); done(); }) }); }); }); it('works with sub-docs', function(done){ var m = D.add({ arr: [{name:'aaron'}, {name:'moombahton '}] }); save(m, function (doc) { assert.equal(2, doc.arr.length); doc.arr.set(0, {name:'vdrums'}); assert.equal(2, doc.arr.length); assert.equal('vdrums', doc.arr[0].name); doc.arr.set(doc.arr.length, {name:"Restrepo"}); assert.equal(3, doc.arr.length); assert.equal("Restrepo", doc.arr[2].name); save(doc, function (doc) { // validate assert.equal(3, doc.arr.length); assert.equal('vdrums', doc.arr[0].name); assert.equal("moombahton ", doc.arr[1].name); assert.equal("Restrepo", doc.arr[2].name); doc.arr.set(10, { name: 'temple of doom' }) assert.equal(11, doc.arr.length); assert.equal('temple of doom', doc.arr[10].name); assert.equal(null, doc.arr[9]); save(doc, function (doc) { // validate assert.equal(11, doc.arr.length); assert.equal('vdrums', doc.arr[0].name); assert.equal("moombahton ", doc.arr[1].name); assert.equal("Restrepo", doc.arr[2].name); assert.equal(null, doc.arr[3]); assert.equal(null, doc.arr[9]); assert.equal('temple of doom', doc.arr[10].name); doc.arr.remove(doc.arr[0]); doc.arr.set(7, { name: 7 }) assert.strictEqual("7", doc.arr[7].name); assert.equal(10, doc.arr.length); save(doc, function (doc) { assert.equal(10, doc.arr.length); assert.equal("moombahton ", doc.arr[0].name); assert.equal("Restrepo", doc.arr[1].name); assert.equal(null, doc.arr[2]); assert.ok(doc.arr[7]); assert.strictEqual("7", doc.arr[7].name); assert.equal(null, doc.arr[8]); assert.equal('temple of doom', doc.arr[9].name); done(); }); }); }); }); }); }); describe('setting a doc array', function(){ it('should adjust path positions', function(done){ var D = storage.createCollection('subDocPositions', new Schema({ em1: [new Schema({ name: String })] })); var d = D.add({ em1: [ { name: 'pos0' } , { name: 'pos1' } , { name: 'pos2' } ] }); d.save(function (d) { var n = d.em1.slice(); n[2].name = 'position two'; var x = []; x[1] = n[2]; x[2] = n[1]; x = x.filter(Boolean); d.em1 = x; d.save(function (d) { assert.equal(d.em1[0].name,'position two'); assert.equal(d.em1[1].name,'pos1'); done(); }); }); }); }); describe('paths with similar names', function(){ it('should be saved', function(done){ var D = storage.createCollection('similarPathNames', new Schema({ account: { role: String , roles: [String] } , em: [new Schema({ name: String })] })); var d = D.add({ account: { role: 'teacher', roles: ['teacher', 'admin'] } , em: [{ name: 'bob' }] }); d.save(function (d) { d.account.role = 'president'; d.account.roles = ['president', 'janitor']; d.em[0].name = 'memorable'; d.em = [{ name: 'frida' }]; d.save(function (d) { assert.equal(d.account.role,'president'); assert.equal(d.account.roles.length, 2); assert.equal(d.account.roles[0], 'president'); assert.equal(d.account.roles[1], 'janitor'); assert.equal(d.em.length, 1); assert.equal(d.em[0].name, 'frida'); done(); }); }); }); }); describe('of number', function(){ it('allows nulls', function(done){ var schema = new Schema({ x: [Number] }); var M = storage.createCollection('nullsareallowed', schema); var m; m = M.add({ x: [1, null, 3] }); m.save(function () { // undefined is not allowed m = M.add({ x: [1, undefined, 3] }); m.save( true ).fail(function (err) { assert.ok(err); done(); }); }); }) }); it('modifying subdoc props and manipulating the array works (gh-842)', function(done){ var schema = new Schema({ em: [new Schema({ username: String })]}); var M = storage.createCollection('modifyingSubDocAndPushing', schema); var m = M.add({ em: [ { username: 'Arrietty' }]}); m.save(function (m) { assert.equal(m.em[0].username, 'Arrietty'); m.em[0].username = 'Shawn'; m.em.push({ username: 'Homily' }); m.save(function (m) { assert.equal(m.em.length, 2); assert.equal(m.em[0].username, 'Shawn'); assert.equal(m.em[1].username, 'Homily'); m.em[0].username = 'Arrietty'; m.em[1].remove(); m.save(function (m) { assert.equal(m.em.length, 1); assert.equal(m.em[0].username, 'Arrietty'); done(); }); }); }); }); it('pushing top level arrays and subarrays works (gh-1073)', function(done){ var schema = new Schema({ em: [new Schema({ sub: [String] })]}); var M = storage.createCollection('gh1073', schema); var m = M.add({ em: [ { sub: [] }]}); m.save(function (m) { m.em[m.em.length-1].sub.push("a"); m.em.push({ sub: [] }); assert.equal(2, m.em.length); assert.equal(1, m.em[0].sub.length); m.save(function (m) { assert.equal(2, m.em.length); assert.equal(1, m.em[0].sub.length); assert.equal('a', m.em[0].sub[0]); done(); }); }); }); describe('default type', function(){ it('casts to Mixed', function(done){ var DefaultArraySchema = new Schema({ num1: Array, num2: [] }); var DefaultArray = storage.createCollection('DefaultArraySchema', DefaultArraySchema); var arr = DefaultArray.add(); assert.equal(arr.get('num1').length, 0); assert.equal(arr.get('num2').length, 0); var threw1 = false , threw2 = false; try { arr.num1.push({ x: 1 }) arr.num1.push(9) arr.num1.push("woah") } catch (err) { threw1 = true; } assert.equal(threw1, false); try { arr.num2.push({ x: 1 }) arr.num2.push(9) arr.num2.push("woah") } catch (err) { threw2 = true; } assert.equal(threw2, false); done(); }); }); describe('removing from an array atomically using StorageArray#remove', function(){ var B; before(function(done){ var schema = Schema({ numbers: ['number'] , numberIds: [{ _id: 'number', name: 'string' }] , stringIds: [{ _id: 'string', name: 'string' }] , oidIds: [{ name: 'string' }] }); B = storage.createCollection('BlogPost', schema); done(); }); it('works', function(done){ var post = B.add(); post.numbers.push(1, 2, 3); post.save(function (doc) { doc.numbers.remove('1'); doc.save(function (doc) { assert.equal(doc.numbers.length, 2); doc.numbers.remove('2', '3'); doc.save(function (doc) { assert.equal(0, doc.numbers.length); done(); }); }); }); }); describe('with subdocs', function(){ function docs (arr) { return arr.map(function (val) { return { _id: val } }); } it('supports passing strings', function(done){ var post = B.add({ stringIds: docs('a b c d'.split(' ')) }); post.save(function (post) { post.stringIds.remove('b'); post.save(function (post) { assert.equal(3, post.stringIds.length); assert.ok(!post.stringIds.id('b')); done(); }); }); }); it('supports passing numbers', function(done){ var post = B.add({ numberIds: docs([1,2,3,4]) }); post.save(function (post) { post.numberIds.remove(2,4); post.save(function (post) { assert.equal(2, post.numberIds.length); assert.ok(!post.numberIds.id(2)); assert.ok(!post.numberIds.id(4)); done(); }); }); }); it('supports passing objectids', function(done){ var OID = storage.Types.ObjectId; var a = new OID; var b = new OID; var c = new OID; var post = B.add({ oidIds: docs([a,b,c]) }); post.save(function (post) { post.oidIds.remove(a,c); post.save(function (post) { assert.equal(1, post.oidIds.length); assert.ok(!post.oidIds.id(a)); assert.ok(!post.oidIds.id(c)); done(); }); }); }); }); }); });
archangel-irk/storage-experiments
test/types.array.test.js
JavaScript
mit
33,950
namespace ArtistsSystem.Services.Data { using System; using System.Linq; using ArtistsSystem.Data; using ArtistsSystem.Data.Repositories; using Contracts; using Models; public class ArtistsService : IArtistsService { private IGenericRepository<Artist> artists; public ArtistsService(IGenericRepository<Artist> artists) { this.artists = artists; } public Artist Add(Artist artist) { if (artist.DateOfBirth == default(DateTime)) { artist.DateOfBirth = DateTime.Now.AddYears(-30); } if (artist.CountryId == default(int)) { artist.CountryId = 1; } artist = this.artists.Add(artist); this.artists.SaveChanges(); return artist; } public IQueryable<Artist> All() { return this.artists.All(); } public void Delete(int id) { var artistToDelete = this.GetById(id).FirstOrDefault(); this.artists.Delete(artistToDelete); this.artists.SaveChanges(); } public IQueryable<Artist> GetById(int id) { return this.artists .SearchFor(a => a.Id == id); } public Artist Update(int id, Artist artist) { var artistToUpdate = this.GetById(id).FirstOrDefault(); artistToUpdate.Name = artist.Name ?? artistToUpdate.Name; artistToUpdate.DateOfBirth = artist.DateOfBirth != default(DateTime) ? artist.DateOfBirth : artistToUpdate.DateOfBirth; artistToUpdate.Country = artist.Country ?? artistToUpdate.Country; artistToUpdate = this.artists.Update(artistToUpdate); this.artists.SaveChanges(); return artist; } } }
TsvetanMilanov/TelerikAcademyHW
13_WebServicesAndCloud/01_ASP_NET-Web-API/ASP_NET-Web-API/ArtistsSystem/Server/ArtistsSystem.Services.Data/ArtistsService.cs
C#
mit
1,902
namespace Cars.Tests.JustMock { using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using Microsoft.VisualStudio.TestTools.UnitTesting; using Cars.Contracts; using Cars.Tests.JustMock.Mocks; using Cars.Controllers; using Cars.Models; [TestClass] public class CarsControllerTests { private readonly ICarsRepository carsData; private CarsController controller; private ICarsRepositoryMock mockedCarsData; public CarsControllerTests() : this(new MoqCarsRepository()) { } private CarsControllerTests(ICarsRepositoryMock carsDataMock) { this.mockedCarsData = carsDataMock; this.carsData = carsDataMock.CarsData; } [TestInitialize] public void CreateController() { this.controller = new CarsController(this.carsData); } [TestMethod] public void IndexShouldReturnAllCars() { var model = (ICollection<Car>)this.GetModel(() => this.controller.Index()); Assert.AreEqual(5, model.Count); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void AddingCarShouldThrowArgumentNullExceptionIfCarIsNull() { var model = (Car)this.GetModel(() => this.controller.Add(null)); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void AddingCarShouldThrowArgumentNullExceptionIfCarMakeIsNull() { var car = new Car { Id = 15, Make = "", Model = "330d", Year = 2014 }; var model = (Car)this.GetModel(() => this.controller.Add(car)); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void AddingCarShouldThrowArgumentNullExceptionIfCarModelIsNull() { var car = new Car { Id = 15, Make = "BMW", Model = "", Year = 2014 }; var model = (Car)this.GetModel(() => this.controller.Add(car)); } [TestMethod] public void AddingCarShouldReturnADetail() { var car = new Car { Id = 0, Make = "BMW", Model = "330d", Year = 2014 }; var model = (Car)this.GetModel(() => this.controller.Add(car)); Assert.AreEqual(1, model.Id); Assert.AreEqual("Audi", model.Make); Assert.AreEqual("A5", model.Model); Assert.AreEqual(2005, model.Year); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void GettingDetailsOnNotExistingCarShouldThrow() { var details = (Car)this.GetModel(() => this.controller.Details(4)); } [TestMethod] public void SearchingDetailsShouldReturnValidData() { var details = (IList<Car>)this.GetModel(() => this.controller.Search("test")); Assert.AreEqual(0, details[0].Id); Assert.AreEqual("searchedCar", details[0].Make); Assert.AreEqual("searchedModel", details[0].Model); Assert.AreEqual(2000, details[0].Year); } [TestMethod] public void SortingByMakeShouldReturnValidData() { var details = (IList<Car>)this.GetModel(() => this.controller.Sort("make")); Assert.AreEqual(0, details[0].Id); Assert.AreEqual("sortedByMake", details[0].Make); Assert.AreEqual("sortedByMake", details[0].Model); Assert.AreEqual(2000, details[0].Year); } [TestMethod] public void SortingByYearShouldReturnValidData() { var details = (IList<Car>)this.GetModel(() => this.controller.Sort("year")); Assert.AreEqual(0, details[0].Id); Assert.AreEqual("sortedByYear", details[0].Make); Assert.AreEqual("sortedByYear", details[0].Model); Assert.AreEqual(2000, details[0].Year); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void SortingByInvalidStringShouldThrow() { var details = (IList<Car>)this.GetModel(() => this.controller.Sort("invalid")); } [TestMethod] public void RepositoryWithDefaultConstructorShouldNotThrow() { var controllerTest = new CarsController(); } private object GetModel(Func<IView> funcView) { var view = funcView(); return view.Model; } } }
atanas-georgiev/TelerikAcademy
10.High-Quality-Code/Homeworks/20. Mocking and JustMock/Cars.Tests.JustMock/CarsControllerTests.cs
C#
mit
4,998
app.controller('VarsCtrl', function($scope, $compile, $route, $location, VariableData) { $scope.varValue = []; VariableData.get().then(function(results) { $.each(results.data, function(key, value) { $('.activeVars') .append($("<tr id='tr" + key + "'></tr>")); $scope.varValue[key] = value; $('#tr' + key) .append($("<td>" + key + "</td>")) .append($("<td><input class='form-control' type='text' value='" + value + "' ng-model='varValue[\"" + key + "\"]' disabled></td>")) .append($("<td id='options" + key + "'><button type='button' class='btn btn-primary editBtn' ng-click='editRow(\"" + key + "\")'>Edit</button> <button type='button' class='btn btn-danger delBtn' ng-click='delVar(\"" + key + "\")'>Delete</td>")); }); $compile($('#editVarsForm'))($scope); }); $scope.addVar = function() { $('.addBtn').hide(); $('.activeVars') .append($("<tr id='newVar'></tr>")); $('#newVar') .append($("<td><input class='form-control' type='text' ng-model='varTitle[\"newVar\"]'></td>")) .append($("<td><input class='form-control' type='text' ng-model='varValue[\"newVar\"]'></td>")) .append($("<td id='optionsVar'><button type='button' class='btn' ng-click='saveVar(\"newVar\", \"post\")'>Save</button></td>")); $compile($('#editVarsForm'))($scope); }; $scope.saveVar = function(row, type) { var varName = row var varValue = $scope.varValue[row]; var vars = { "varName": varName, "varValue": varValue }; if (type === 'post') { VariableData.post(varName, vars).then(function(results) { alertify.notify("Result: " + results.error, 'success', 5); $route.reload(); $location.path('/variables'); }); } if(type === 'update'){ VariableData.update(varName, vars).then(function(results) { alertify.notify("Result: " + results.error, 'success', 5); $route.reload(); $location.path('/variables'); }); } }; $scope.editRow = function(row) { $('#tr' + row).find('input').each(function() { $(this).prop("disabled", false); }); $('#options' + row).append($("<button type='button' class='btn' ng-click='saveVar(\"" + row + "\", \"update\")'>Save</button>")); $('.editBtn').hide(); $('.delBtn').hide(); var code = {}; $compile($("#editVarsForm"))($scope); }; $scope.delVar = function(vars) { var confirm = window.confirm("Are you sure you want to delete the variable " + vars + "?"); if (confirm) { EndpointData.delete(endpoint).then(function(results) { alertify.notify("Result: " + results.error, 'warning', 5); $route.reload(); $location.path('/variables'); }); } }; });
Madpilot0/HomesPi
public/javascripts/controllers/Variables.js
JavaScript
mit
3,064
import React from 'react' import styled from 'styled-components' import ObjectProperty from 'components/ObjectProperty' import StyledTextarea from 'components/StyledTextarea' import StyledInput from 'components/StyledInput' const StyledObjectCreator = styled.div` width: 100%; ` const StyledContainer = styled.div` display: flex; ` const Category = styled(StyledInput)` margin-top: 2px; margin-bottom: 10px; ` const Notes = styled(StyledTextarea)` min-height: 4rem; resize: vertical; margin-top: 2px; margin-bottom: 10px; ` const Label = styled.div` font-weight: bold; margin-top: 4px; ` export default function ObjectCreator (props: { info: { resolution: { solution?: string, special?: string, error?: string}, name: string, text: string, mathml: string, context: Object, inheritedContext: Object, missingContext: Array<string>, requiredContext: Array<string>, solvableEquation: string }, onContextChange: Function, category: string, onCategoryChange: Function, notes: string, onNotesChage: Function }) { return ( <StyledObjectCreator> <Label>Name</Label> <ObjectProperty id='base' info={props.info} onChange={props.onContextChange} /> <Label>Category</Label> <StyledContainer> <Category value={props.category || ''} type='textarea' onChange={props.onCategoryChange} /> </StyledContainer> <Label>Notes</Label> <StyledContainer> <Notes value={props.notes || ''} type='textarea' onChange={props.onNotesChange} /> </StyledContainer> </StyledObjectCreator> ) }
jtmckay/TQL
src/components/ObjectCreator/index.js
JavaScript
mit
1,756
import torch.nn as nn class VAE(nn.Module): def __init__(self, input_dims, code_dims): super(VAE, self).__init__() self.name = "abstract_VAE" self.input_dims = input_dims self.code_dims = code_dims def encode(self, x): self.handle_unsupported_op() return None def decode(self, z): self.handle_unsupported_op() return None def handle_unsupported_op(self): print("Unsupported Operation") raise(Exception("Unsupported Operation"))
Jueast/DisentangleVAE
model/abstract_VAE.py
Python
mit
530
<?php /** * abstract base class simplifying sending and receiving to/from multiple client streams * * @author Christian Lück <[email protected]> * @copyright Copyright (c) 2011, Christian Lück * @license http://www.opensource.org/licenses/mit-license MIT License * @package Stream_Master * @version v0.0.1 * @link https://github.com/clue/Stream_Master */ abstract class Stream_Master{ /** * wait on given streams for incoming/outgoing changes once * * this will issue stream_select() once only and return immediately when * something interesting happens. * * @param array[Stream_Master_Client]|Stream_Master_Client clients to wait for * @param float|NULL $timeout maximum(!) timeout in seconds to wait, NULL = wait forever * @throws Stream_Master_Exception on error * @uses Stream_Master_Client::getStreamRead() to get incoming client stream * @uses Stream_Master_Client::getStreamWrite() to get outgoing client stream * @uses stream_select() internally to check streams for changes * @uses Stream_Master_Client::onCanWrite() when data is ready to be sent * @uses Stream_Master_Client::onCanRead() when data is ready to be received */ protected function streamSelect($clients,$timeoutIn=NULL){ if(!is_array($clients)){ $clients = array($clients); } $oread = array(); $owrite = array(); foreach($clients as $id=>$client){ // cycle through clients to initialize streams if(($r = $client->getStreamRead()) !== NULL){ $oread[$id] = $r; } if(($w = $client->getStreamWrite()) !== NULL){ $owrite[$id] = $w; } } if(!$oread && !$owrite){ // nothing to be done return; } $ssleep = NULL; $usleep = NULL; if($timeoutIn !== NULL){ // calculate timeout into ssleep/usleep $ssleep = (int)$timeoutIn; $usleep = (int)(($timeoutIn - $ssleep)*1000000); } $read = $oread; $write = $owrite; $ignore = NULL; $ret = stream_select($read,$write,$ignore,$ssleep,$usleep); if($ret === false){ throw new Stream_Master_Exception('stream_select() failed'); } foreach($write as $stream){ $id = array_search($stream,$owrite,true); if($id === false){ throw new Stream_Master_Exception('Invalid stream to write to'); } $clients[$id]->onCanWrite($this); } foreach($read as $stream){ $id = array_search($stream,$oread,true); if($id === false){ throw new Stream_Master_Exception('Invalid stream to read from'); } $clients[$id]->onCanRead($this); } } }
clue-legacy/Stream_Master
Stream/Master.php
PHP
mit
3,050
module.exports = { getLanguages : function () { var languages = []; for(var lang in this) { if(typeof this[lang] === "string") languages.push(this[lang]); } return languages; }, EN: "en" }
magatz/jitsi-meet-mod
service/translation/languages.js
JavaScript
mit
268
# has-tags `has-tags` is a small command line utility for OS X Mavericks that tests whether a file or folder matches a set of tags. ## Installation ```sh make [sudo] make install ``` ## Usage ```sh has-tags path tag [tag ...] ``` This tests that `path` has _all_ of the given tags applied to it. The program will exit with code 0 if the path matches, or a non-zero code if it doesn't. Only one path can be specified at a time. Each `tag` is case-sensitive. ## Example ```sh has-tags README.md Red && echo "This README is totes red" ``` To find all files matching a set of tags within a folder: ```sh find . -exec has-tags {} Red Green Blue \; -print ```
jspahrsummers/has-tags
README.md
Markdown
mit
665
<?php namespace Success\NotificationBundle\Service; use Buzz\Browser; class SMSBytehand { const SERVICE_URL = "http://bytehand.com:3800/"; const ID = "15993"; const KEY = "B0BE02F4608FED36"; const MSG_FROM = "4Success"; private $browser; public function __construct() { $this->browser = new Browser(); $this->serviceInit(); } public function serviceInit() { } /** * * @param type $toNumber * @param type $text * @return string msgId or 0 if not success */ public function msgSend($toNumber,$text) { $msgText = urlencode($text); $msgToNumber = urlencode($toNumber); $sendUrl = $this::SERVICE_URL."send?id=".$this::ID."&key=".$this::KEY."&to=$msgToNumber&from=".$this::MSG_FROM."&text=$msgText"; $response_json = $this->browser->get($sendUrl); $response = json_decode($response_json); if($response['status']==0){ return $response['description']; } else { return 0; } } public function checkMsgStatus($id) { $msgId = urlencode($id); $sendUrl = $this::SERVICE_URL."status?id=".$this::ID."&key=".$this::KEY."&message=$msgId"; $response_json = $this->browser->get($sendUrl); $response = json_decode($response_json); if($response['status']==0){ return $response['description']; } else { return false; } } }
Stas81/4successCopy
src/Success/NotificationBundle/Service/SMSBytehand.php
PHP
mit
1,582
var fs = require("fs"); module.exports = function(grunt) { grunt.initConfig({ jade: { compile: { files: [ { cwd: "docs", src: "**/*.html.jade", dest: "docs/", expand: true, ext: ".html" } ] } }, concat: { options: { separator: "\n\n" }, basic_and_extras: { files: { "temp/test.html": ["src/test.html", "src/plugins/**/test.html"], "temp/readme.md": ["src/readme.md", "src/plugins/**/readme.md"] } } }, copy: { main: { files: [ { src: "picnic.min.css", dest: "releases/picnic.min.css" }, { src: "picnic.min.css", dest: "releases/plugins.min.css" } ] } }, usebanner: { taskName: { options: { position: "top", banner: "/* Picnic CSS v" + grunt.file.readJSON("package.json").version + " http://picnicss.com/ */", linebreak: true }, files: { src: "picnic.min.css" } } }, watch: { scripts: { files: ["package.js", "Gruntfile.js", "src/**/*.*", "docs/**/*.*"], tasks: ["default"], options: { spawn: false } } }, bytesize: { all: { src: ["picnic.min.css"] } } }); grunt.loadNpmTasks("grunt-contrib-watch"); grunt.loadNpmTasks("grunt-contrib-concat"); grunt.loadNpmTasks("grunt-banner"); grunt.loadNpmTasks("grunt-contrib-copy"); grunt.loadNpmTasks("grunt-contrib-jade"); grunt.loadNpmTasks("grunt-bytesize"); grunt.registerTask("default", [ "concat", "usebanner", "copy", "jade", "bytesize" ]); };
picnicss/picnic
Gruntfile.js
JavaScript
mit
1,753
/* global require */ var Application = require('books/app')['default']; var Router = require('books/router')['default']; import Ember from 'ember'; export default function startApp(attrs) { var App; var attributes = Ember.merge({ // useful Test defaults rootElement: '#ember-testing', LOG_ACTIVE_GENERATION:false, LOG_VIEW_LOOKUPS: false }, attrs); // but you can override; Router.reopen({ location: 'none' }); Ember.run(function(){ App = Application.create(attributes); App.setupForTesting(); App.injectTestHelpers(); }); App.reset(); // this shouldn't be needed, i want to be able to "start an app at a specific URL" return App; }
twar59/ember-cli-simple-crud
tests/helpers/start-app.js
JavaScript
mit
690
# baseSlice 函数调用 `baseSlice(array, start, end)` 实现方式: 1. 参数修正,目的是获取开始拷贝的位置 `start` 和拷贝的数据数目 `length` - 修正 start 参数,主要针对 start 参数为负的情况: - start 绝对值大于数组长度, start 修正为 0; - 否则, 修正为 array.length + start - 修正 end 参数: - end 大于 array.length , 修正其为 array.length - end 为负数, 修正为 length + array.length - 针对 start 和 end 的大小比较进行参数修正, 主要是得出需拷贝的数组项的数目 length - start > end, 拷贝 0 个 - start <= end, 拷贝 end - start 个 2. 执行拷贝, 从 start 的位置开始拷贝 length 个数据到新的数组中并返回
new4/lodash4Fun
src/_common/_baseSlice.md
Markdown
mit
762
'use strict'; module.exports = function( images, callback ){ if ( Object.prototype.toString.call( images ) !== '[object Array]' ) { var req = {}; if ( process.env.HOST_PORT === '2376' ) { req.url = 'https://' + process.env.HOST_IP + ':2376/images/json?all=true'; req.cert = fs.readFileSync( __dirname + '/../cert/cert.pem' ); req.key = fs.readFileSync( __dirname + '/../cert/key.pem' ); req.ca = fs.readFileSync( __dirname + '/../cert/ca.pem' ); } else { req.url = 'http://' + process.env.HOST_IP + ':2375/images/json?all=true'; } request.get( req, function( error, http, body ){ images = new Array(); body = JSON.parse( body ); for (var i = 0; i < body.length; i++) { images = body[i].RepoTags.filter(function ( image ) { return image.indexOf(':latest'); }); } updateImage( images, callback ); }); } else { updateImage( images, callback ); } }; function updateImage( images, callback ) { async.map( images, function ( image, callback ) { var req = { headers : { 'X-Registry-Auth' : new Buffer( JSON.stringify({ username : process.env.REGISTRY_USER || '', password : process.env.REGISTRY_PASS || '', email : process.env.REGISTRY_MAIL || '' }) ).toString('base64') } }; if ( process.env.HOST_PORT === '2376' ) { req.url = 'https://' + process.env.HOST_IP + ':2376/images/create?fromImage=' + image; req.cert = fs.readFileSync( __dirname + '/../cert/cert.pem' ); req.key = fs.readFileSync( __dirname + '/../cert/key.pem' ); req.ca = fs.readFileSync( __dirname + '/../cert/ca.pem' ); } else { req.url = 'http://' + process.env.HOST_IP + ':2375/images/create?fromImage=' + image; } request.post( req, function ( error, http, body ) { callback( error, body ); }); }, function ( err, res ) { callback(err, JSON.parse(res[0].split('\r\n')[2]).status); }); }
Inevio/magallanes-monitor
cmd/monitorUpdateImages.js
JavaScript
mit
2,040
from tehbot.plugins import * class DeathlistPlugin(StandardPlugin): def execute(self, connection, event, extra, dbconn): return "blanky" register_plugin("deathlist", DeathlistPlugin())
spaceone/tehbot
tehbot/plugins/deathlist/__init__.py
Python
mit
199
<div class="container text-center"> <div class="col-xs-12"> <!-- TODO this string needs to be translated --> <h4>turno {{::vm.round}}</h4> </div> <div class="col-xs-12"> <h2 ng-bind="vm.player.name"></h2> </div> <div class="col-xs-12"> <div ng-class="vm.isShutoutRisk() ? 'col-xs-6' : ''"> <!-- TODO this string needs to be translated --> <h4>punti rimanenti</h4> <h3 ng-bind="vm.getMissingPoints()"></h3> </div> <div class="col-xs-6" ng-if="vm.isShutoutRisk()"> <h4>punti per la salvezza</h4> <h3 ng-bind="vm.getMissingRedemptionPoints()"></h3> </div> </div> <div class="col-xs-4" ng-repeat="index in [0, 1, 2]"> <h4>tiro {{::index + 1}}</h4> <h3 ng-if="vm.isShotMade(index)" ng-bind="vm.getShot(index)"></h3> <h3 ng-if="!vm.isShotMade(index)" ng-class="{'blink': vm.isCurrentShot(index)}">-</h3> </div> <div class="col-xs-12"> <!-- TODO this string needs to be translated --> <h4>totale round</h4> <h3 ng-bind="vm.getRoundSum()"></h3> </div> <div class="col-xs-12"> <button class="btn btn-default btn-info adt-btn" ng-repeat="point in vm.points" ng-click="!vm.isButtonDisabled(point) && vm.addPoint(point)" ng-disabled="vm.isButtonDisabled(point)" ng-bind="point.number"></button> </div> <div class="col-xs-6"> <button class="btn btn-danger btn-lg" ng-disabled="!vm.isShotMade(0)" ng-click="vm.undo()"> <span class="glyphicon glyphicon-arrow-left"></span> </button> </div> <div class="col-xs-6"> <button class="btn btn-success btn-lg" ng-disabled="!vm.isButtonTapped() || vm.isRoundCompleted()" ng-click="!vm.isRoundCompleted() && vm.confirm()"> <span class="glyphicon glyphicon-ok"></span> </button> </div> <div class="col-xs-12"> <!-- TODO this string needs to be translated --> <button class="btn btn-primary btn-lg btn-block" ng-if="vm.isRoundCompleted()" ng-click="vm.isRoundCompleted() && vm.viewSummary()"> summary <span class="glyphicon glyphicon-circle-arrow-right"></span> </button> </div> </div>
the-software-factory/angular-darts-tournament
src/app/modules/round/round.view.html
HTML
mit
2,173
# -*- coding: utf-8 -*- """ Label delay space ================= Using WrightTools to label delay space. """ import matplotlib.pyplot as plt import WrightTools as wt from WrightTools import datasets fig, gs = wt.artists.create_figure(width="double", cols=[1, 1, "cbar"]) def set_lim(ax): ax.set_xlim(-175, 175) ax.set_ylim(-175, 175) # traditional delay space ax = plt.subplot(gs[0, 0]) p = datasets.PyCMDS.d1_d2_000 data = wt.data.from_PyCMDS(p) data.convert("fs") data.channels[0].symmetric_root(2) data.channels[0].normalize() data.channels[0].clip(min=0, replace="value") ax.pcolor(data) wt.diagrams.delay.label_sectors(ax=ax) # using default labels set_lim(ax) ax.set_title(r"$\mathsf{\vec{k}_1 - \vec{k}_2 + \vec{k}_{2^\prime}}$", fontsize=20) # conjugate delay space ax = plt.subplot(gs[0, 1]) p = datasets.PyCMDS.d1_d2_001 data = wt.data.from_PyCMDS(p) data.convert("fs") data.channels[0].symmetric_root(2) data.channels[0].normalize() data.channels[0].clip(min=0, replace="value") ax.pcolor(data) labels = ["II", "I", "III", "V", "VI", "IV"] wt.diagrams.delay.label_sectors(ax=ax, labels=labels) set_lim(ax) ax.set_title(r"$\mathsf{\vec{k}_1 + \vec{k}_2 - \vec{k}_{2^\prime}}$", fontsize=20) # label wt.artists.set_fig_labels(xlabel=data.d1.label, ylabel=data.d2.label) # colorbar cax = plt.subplot(gs[:, -1]) wt.artists.plot_colorbar(cax=cax, label="amplitude")
wright-group/WrightTools
examples/label_delay_space.py
Python
mit
1,391
import {Component} from '@angular/core'; import {DrWordCloudComponent} from '../dr-word-cloud/dr-word-cloud.component'; import {DrDomainRankComponent} from '../dr-domain-rank/dr-domain-rank.component'; import {DrBrowsingTimelineComponent} from '../dr-browsing-timeline/dr-browsing-timeline.component'; @Component({ selector: 'as-dashboard', templateUrl: 'app/dr-dashboard/dr-dashboard.html', styleUrls: [ 'app/dr-dashboard/dr-dashboard.css' ], directives: [ DrWordCloudComponent, DrDomainRankComponent, DrBrowsingTimelineComponent, ] }) export class DrDashBoardComponent { constructor() { console.log('dashboard init'); } }
westlab/door-front
src/app/dr-dashboard/dr-dashboard.component.ts
TypeScript
mit
695
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("UseApiDemo")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("UseApiDemo")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("ec7d4683-8eee-459c-904c-894bd42c9715")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
liqipeng/MyDemoCode
012-C#/02UseRestSharp/UseApiDemo/Properties/AssemblyInfo.cs
C#
mit
1,308
#include <iostream> #include <vector> #include <algorithm> #include <functional> const int N = 4; // # of document types + 1 // Prototype class Document { public: virtual Document* clone() const = 0; virtual void store() const = 0; virtual ~Document() { } }; // Concrete prototypes : xmlDoc, plainDoc, spreadsheetDoc class xmlDoc : public Document { public: Document* clone() const { return new xmlDoc; } void store() const { std::cout << "xmlDoc\n"; } }; class plainDoc : public Document { public: Document* clone() const { return new plainDoc; } void store() const { std::cout << "plainDoc\n"; } }; class spreadsheetDoc : public Document { public: Document* clone() const { return new spreadsheetDoc; } void store() const { std::cout << "spreadsheetDoc\n"; } }; // makeDocument() calls Concrete Portotype's clone() method // inherited from Prototype class DocumentManager { public: static Document* makeDocument( int choice ); ~DocumentManager(){} private: static Document* mDocTypes[N]; }; Document* DocumentManager::mDocTypes[] = { 0, new xmlDoc, new plainDoc, new spreadsheetDoc }; Document* DocumentManager::makeDocument( int choice ) { return mDocTypes[choice]->clone(); } // for_each op () struct Destruct { void operator()(Document *a) const { delete a; } }; // Client int main(int argc, char** argv) { std::vector<Document*> docs(N); int choice; std::cout << "quit(0), xml(1), plain(2), spreadsheet(3): " << std::endl; while(true) { std::cout << "Type in your choice (0-3)\n"; std::cin >> choice; if(choice <= 0 || choice >= N) break; docs[choice] = DocumentManager::makeDocument( choice ); } for(int i = 1; i < docs.size(); ++i) if(docs[i]) docs[i]->store(); Destruct d; // this calls Destruct::operator() std::for_each(docs.begin(), docs.end(), d); return 0; }
kks32/cpp-software-development
Ex05_Prototype/src/1_document_manager/docmanager.cc
C++
mit
1,953
package com.algolia.search.responses; import java.util.List; public class SearchFacetResult { private List<FacetHit> facetHits; public List<FacetHit> getFacetHits() { return facetHits; } public SearchFacetResult setFacetHits(List<FacetHit> facetHits) { this.facetHits = facetHits; return this; } }
algoliareadmebot/algoliasearch-client-java-2
algoliasearch-common/src/main/java/com/algolia/search/responses/SearchFacetResult.java
Java
mit
325
<div class="col-md-12"> <div class="box box-danger"> <div class="box-header with-border"> <h3 class="box-title"> <span id="titulo_lt"></span> Usuario</h3> </div> <form class="form-horizontal" id="agregar_usuario" name="agregar_frm" method="post" enctype="multipart/form-data"> <div class="box-body"> <div class="col-md-6"> <div class="form-group"> <label for="dni_usuario" class="col-sm-4 control-label">Dni</label> <div class="col-sm-8"> <input type="text" class="form-control" id="dni_usuario" name="dni_usuario_txt" placeholder="Ingrese el número de Dni" title="Ingrese el número de Dni" pattern="[0-9]{8}" required> </div> </div> <div class="form-group"> <label for="nomb_usu" class="col-sm-4 control-label">Nombres</label> <div class="col-sm-8"> <input type="text" class="form-control" id="nomb_usu" name="nomb_usu_txt" placeholder="Ingrese el Nombre Completo" title="Ingrese el Nombre Completo" pattern="[a-Z]" required> </div> </div> <div class="form-group"> <label for="ap_pusu" class="col-sm-4 control-label">Ap. Paterno</label> <div class="col-sm-8"> <input type="text" class="form-control" id="ap_pusu" name="ap_pusu_txt" placeholder="Ingrese el Apellido Paterno" title="Ingrese el Apellido Paterno" pattern="[a-Z]" required> </div> </div> <div class="form-group"> <label for="ap_musu" class="col-sm-4 control-label">Ap. Materno</label> <div class="col-sm-8"> <input type="text" class="form-control" id="ap_musu" name="ap_musu_txt" placeholder="Ingrese el Apellido Materno" title="Ingrese el Apellido Materno" pattern="[a-Z]" required> </div> </div> <div class="form-group"> <label for="fech_nac" class="col-sm-4 control-label">Fec. Nac.</label> <div class="col-sm-8"> <input type="date" class="form-control" id="fech_nac" name="fech_nac_txt" size="20%" required> </div> </div> <div class="form-group"> <label for="direc_usu" class="col-sm-4 control-label">Dirección</label> <div class="col-sm-8"> <input type="text" class="form-control" id="direc_usu" name="direc_usu_txt" placeholder="Ingresa la Dirección" title="Ingresa la Dirección" size="20%" required> </div> </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="telef_usu" class="col-sm-4 control-label">Teléfono</label> <div class="col-sm-8"> <input type="text" class="form-control" id="telef_usu" name="telef_usu_txt" placeholder="Ingrese número de telefono" title="Ejemplo:076345678 O 999999999" pattern="[0-9]{9}" required> </div> </div> <div class="form-group"> <label for="e_mail" class="col-sm-4 control-label">Email</label> <div class="col-sm-8"> <input type="email" class="form-control" id="e_mail" name="e_mail_txt" placeholder="Ingrese el email" title="Email" required> </div> </div> <div class="form-group"> <label for="id_tipo" class="col-sm-4 control-label">Tipo Usuario</label> <div class="col-sm-8"> <select id="id_tipo" name="id_tipo_slc" class="form-control" required> <option value="">Seleccione Tipo de Usuario</option> <option value="5">Administrativo</option> <option value="4">Docente</option> </select> </div> </div> <div class="form-group"> <label for="id_lugar" class="col-sm-4 control-label">Lugar Trabajo</label> <div class="col-sm-8"> <select id="id_lugar" name="id_lugar_slc" class="form-control" required> <option value="">Seleccione Lugar de Trabajo</option> <?php include("SeleccionarLugarUsuario.php");?> </select> </div> </div> <div class="form-group" id="input_contrasenia"> <label for="pass_usu" class="col-sm-4 control-label">Contraseña</label> <div class="col-sm-8"> <input type="pass_usu" class="form-control" id="pass_usu" name="pass_usu_txt" placeholder="Ingrese contraseña" title="Contraseña" > </div> </div> </div> <div class="col-md-12"> <div class="box-footer" align="center"> <button type="submit" id="enviar" name="enviar_sb" value="Guardar" class="btn btn-success">Guardar</button> <button type="submit" id="editar" name="editar_sb" value="Editar" class="btn btn-success">Editar</button > </div> </div> </form> </div> </div> <?php if(isset($_REQUEST['enviar_sb'])){ $dni_usuario=$_POST["dni_usuario_txt"]; $nomb_usu=$_POST["nomb_usu_txt"]; $ap_pusu=$_POST["ap_pusu_txt"]; $ap_musu=$_POST["ap_musu_txt"]; $fech_nac=$_POST["fech_nac_txt"]; $direc_usu=$_POST["direc_usu_txt"]; $telef_usu=$_POST["telef_usu_txt"]; $e_mail=$_POST["e_mail_txt"]; $id_tipo_usu=$_POST["id_tipo_slc"]; $id_lugar_usu=$_POST["id_lugar_slc"]; include ("conexion.php"); $consulta="INSERT INTO usuario(dni_usuario, nomb_usu, ap_pusu, ap_musu, fech_nac, direc_usu, telef_usu, e_mail, pass_usu, id_tipo_usu, id_lugar_usu) VALUES ('$dni_usuario','$nomb_usu','$ap_pusu','$ap_musu','$fech_nac','$direc_usu','$telef_usu','$e_mail','$dni_usuario','$id_tipo_usu','$id_lugar_usu')"; $ejecutar_consulta=$conexion->query($consulta); if ($ejecutar_consulta) { echo "<script> alert('Usuario Registrado');</script>"; } else{ echo "<script> alert('Usuario No Registrado');</script>"; } } if(isset($_REQUEST["editar_sb"])){ $direc_usu=$_POST["direc_usu_txt"]; $telef_usu=$_POST["telef_usu_txt"]; $e_mail=$_POST["e_mail_txt"]; $pass_usu=$_POST["pass_usu_txt"]; $id_lugar_usu=$_POST["id_lugar_slc"]; include ("conexion.php"); $consulta="UPDATE usuario SET direc_usu = '$direc_usu', telef_usu = '$telef_usu', e_mail = '$e_mail', pass_usu = '$pass_usu', id_lugar_usu = '$id_lugar_usu' where dni_usuario = '$dni_usuario'"; $ejecutar_consulta=$conexion->query($consulta); if ($ejecutar_consulta) { echo "<script> alert('Usuario Actualizado');</script>"; } else{ echo "<script> alert('Usuario No Actualizado');</script>"; } } ?>
MaguiAGonzales/dreCajamarca
Dre-Logica/LCrearUsuario.php
PHP
mit
7,169
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03 // <scoped_allocator> // template <class OtherAlloc, class ...InnerAlloc> // class scoped_allocator_adaptor // template <class U1, class U2> // void scoped_allocator_adaptor::construct(pair<U1, U2>*) #include <scoped_allocator> #include <type_traits> #include <utility> #include <tuple> #include <cassert> #include <cstdlib> #include "uses_alloc_types.hpp" #include "controlled_allocators.hpp" void test_no_inner_alloc() { using VoidAlloc = CountingAllocator<void>; AllocController P; { using T = UsesAllocatorV1<VoidAlloc, 0>; using U = UsesAllocatorV2<VoidAlloc, 0>; using Pair = std::pair<T, U>; using Alloc = CountingAllocator<Pair>; using SA = std::scoped_allocator_adaptor<Alloc>; static_assert(std::uses_allocator<T, CountingAllocator<T> >::value, ""); Pair * ptr = (Pair*)std::malloc(sizeof(Pair)); Alloc CA(P); SA A(CA); A.construct(ptr); assert(checkConstruct<>(ptr->first, UA_AllocArg, CA)); assert(checkConstruct<>(ptr->second, UA_AllocLast, CA)); assert((P.checkConstruct<std::piecewise_construct_t const&, std::tuple<std::allocator_arg_t, SA&>&&, std::tuple<SA&>&& >(CA, ptr))); A.destroy(ptr); std::free(ptr); } P.reset(); { using T = UsesAllocatorV3<VoidAlloc, 0>; using U = NotUsesAllocator<VoidAlloc, 0>; using Pair = std::pair<T, U>; using Alloc = CountingAllocator<Pair>; using SA = std::scoped_allocator_adaptor<Alloc>; static_assert(std::uses_allocator<T, CountingAllocator<T> >::value, ""); Pair * ptr = (Pair*)std::malloc(sizeof(Pair)); Alloc CA(P); SA A(CA); A.construct(ptr); assert(checkConstruct<>(ptr->first, UA_AllocArg, CA)); assert(checkConstruct<>(ptr->second, UA_None)); assert((P.checkConstruct<std::piecewise_construct_t const&, std::tuple<std::allocator_arg_t, SA&>&&, std::tuple<>&& >(CA, ptr))); A.destroy(ptr); std::free(ptr); } } void test_with_inner_alloc() { using VoidAlloc1 = CountingAllocator<void, 1>; using VoidAlloc2 = CountingAllocator<void, 2>; AllocController POuter; AllocController PInner; { using T = UsesAllocatorV1<VoidAlloc2, 0>; using U = UsesAllocatorV2<VoidAlloc2, 0>; using Pair = std::pair<T, U>; using Outer = CountingAllocator<Pair, 1>; using Inner = CountingAllocator<Pair, 2>; using SA = std::scoped_allocator_adaptor<Outer, Inner>; using SAInner = std::scoped_allocator_adaptor<Inner>; static_assert(!std::uses_allocator<T, Outer>::value, ""); static_assert(std::uses_allocator<T, Inner>::value, ""); Pair * ptr = (Pair*)std::malloc(sizeof(Pair)); Outer O(POuter); Inner I(PInner); SA A(O, I); A.construct(ptr); assert(checkConstruct<>(ptr->first, UA_AllocArg, I)); assert(checkConstruct<>(ptr->second, UA_AllocLast)); assert((POuter.checkConstruct<std::piecewise_construct_t const&, std::tuple<std::allocator_arg_t, SAInner&>&&, std::tuple<SAInner&>&& >(O, ptr))); A.destroy(ptr); std::free(ptr); } PInner.reset(); POuter.reset(); { using T = UsesAllocatorV3<VoidAlloc2, 0>; using U = NotUsesAllocator<VoidAlloc2, 0>; using Pair = std::pair<T, U>; using Outer = CountingAllocator<Pair, 1>; using Inner = CountingAllocator<Pair, 2>; using SA = std::scoped_allocator_adaptor<Outer, Inner>; using SAInner = std::scoped_allocator_adaptor<Inner>; static_assert(!std::uses_allocator<T, Outer>::value, ""); static_assert(std::uses_allocator<T, Inner>::value, ""); Pair * ptr = (Pair*)std::malloc(sizeof(Pair)); Outer O(POuter); Inner I(PInner); SA A(O, I); A.construct(ptr); assert(checkConstruct<>(ptr->first, UA_AllocArg, I)); assert(checkConstruct<>(ptr->second, UA_None)); assert((POuter.checkConstruct<std::piecewise_construct_t const&, std::tuple<std::allocator_arg_t, SAInner&>&&, std::tuple<>&& >(O, ptr))); A.destroy(ptr); std::free(ptr); } } int main() { test_no_inner_alloc(); test_with_inner_alloc(); }
ensemblr/llvm-project-boilerplate
include/llvm/projects/libcxx/test/std/utilities/allocator.adaptor/allocator.adaptor.members/construct_pair.pass.cpp
C++
mit
5,019
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="Jintana & Teerapat the Wedding"> <meta name="author" content="Teerapat Khunpech"> <meta property="og:url" content="http://minnieballinlove.com" /> <meta property="og:type" content="website" /> <meta property="og:title" content="Jintana & Teerapat, We're getting married!" /> <meta property="og:description" content="Let's begin our journey. เรามีความยินดีที่จะเรียนเชิญทุกท่านไปร่วมงานมงคลสมรสของเราที่จังหวัดอุดรธานี ในวันอาทิตย์ที่ 18 ธันวาคม 2559" /> <meta property="og:image" content="http://minnieballinlove.com/img/portfolio/fullsize/1.jpg" /> <title>Minnie 💕 Ball</title> <!-- Bootstrap Core CSS --> <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Alex+Brush' rel='stylesheet' type='text/css'> <!-- Plugin CSS --> <link href="vendor/magnific-popup/magnific-popup.css" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="css/sweetalert.css"> <!-- Theme CSS --> <link href="css/creative.min.css" rel="stylesheet"> <link rel="icon" type="image/png" sizes="96x96" href="/favicon-96x96.png"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body id="page-top"> <nav id="mainNav" class="navbar navbar-default navbar-fixed-top"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> Menu <i class="fa fa-bars"></i> </button> <a class="navbar-brand page-scroll" href="#page-top">Minnie 💕 Ball</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li> <a class="page-scroll" href="#about">Bride & Groom</a> </li> <!-- <li> <a class="page-scroll" href="#services">Bridal Party</a> </li> --> <li> <a class="page-scroll" href="#venue">Venue</a> </li> <li> <a class="page-scroll" href="#RSVPmodal" data-toggle="modal">RSVP</a> </li> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container-fluid --> </nav> <header> <div class="header-content"> <div class="header-content-inner fill"> <!-- <h1 id="homeHeading"></h1> --> <!-- <h1 class="section-heading fill">Jintana & Teerapat</h1> --> <!-- <hr> <p></p> <a href="#RSVPmodal" data-toggle="modal" class="btn btn-xl page-scroll button">RSVP</a> --> <p></p> </div> </div> </header> <section class="bg-primary" id="info"> <div class="container"> <div class="row"> <div class="col-md-12 col-sm-12 text-center"> <h1 class="section-heading">Jintana & Teerapat</h1> <!-- <h1 class="section-heading">Are Getting Married!</h1> --> <hr class="light"> <p class="text-faded"> We're Getting Married! </p> <p class="text-faded"><strong>on December 18th</strong>, - Udonthani, Thailand</p> <!-- <a href="#services" class="page-scroll btn btn-default btn-xl sr-button">Get Started!</a> --> <div id="clockdiv" class="text-faded"> <div> <span class="days"></span> <div class="smalltext">Days</div> </div> <div> <span class="hours"></span> <div class="smalltext">Hours</div> </div> <div> <span class="minutes"></span> <div class="smalltext">Minutes</div> </div> <div> <span class="seconds"></span> <div class="smalltext">Seconds</div> </div> </div> </div> </div> </div> </section> <section id="about"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h1 class="section-heading">Bride & Groom</h1> <hr class="primary"> </div> </div> </div> <div class="container"> <!-- <div class="row"> <div class="col-lg-6 col-md-12 text-center"> <div class="media"> <a class="pull-left" href="#"> <img class="media-object img-circle" src="img/avatar/minnie.png" style="width: 100px;height:100px;"> </a> <div class="media-body"> <h4 class="media-heading">Jintana Choopromwong<small> (Minnie)</small></h4> <hr style="margin:8px auto"> <p class="text-muted pull-left"></p> </div> </div> </div> <div class="col-lg-6 col-md-12 text-center"> <div class="media"> <a class="pull-right" href="#"> <img class="media-object img-circle" src="img/avatar/ball.png" style="width: 100px;height:100px;"> </a> <div class="media-body"> <h4 class="media-heading">Teerapat Khunpech<small> (BALL)</small></h4> <hr style="margin:8px auto"> <p class="text-muted pull-right"></p> </div> </div> </div> </div> --> <div class="row"> <div class="col-lg-6 col-md-6 col-sm-12 text-center"> <div class="media"> <img src="img/avatar/minnie.png" class=" img-circle" /> <div class="description"> <h4>Jintana Choompromwong</h4> <h4> <small> Minnie (Nu+) </small></h4> <a href="https://www.facebook.com/jintanac" class="btn btn-social btn-facebook"><i class="fa sr-icons fa-facebook"></i></a> <a href="https://www.instagram.com/nujinminnie/" class="btn btn-social btn-instagram"><i class="fa sr-icons fa-instagram"></i></a> <p class="text-muted">ถ้าจะให้พูดถึงครั้งแรกที่รู้จักกันกับบอลตอนที่อยู่ TCDC ความรู้สึกแรกคือ แปลก เค้าเป็นคนพูดน้อย ขี้เก็ก ไปกินข้าวเที่ยงคนเดียวตลอด จินตนาถนัดไปเป็นฝูงก็รู้สึกว่าเค้าแปลก ก็พยายามชวนเค้าคุยและชวนเข้าฝูง (ด้วยนิสัยส่วนตัวที่เราเป็นคนอัธยาศัยดีอะนะ) แต่เค้าก็เป็นคนมีความสามารถและมีไหวพริบ และก็มีเสน่ห์ นิสัยเรา 2 คนต่างกันคนละขั้วแต่มันเหมือนส่วนที่หายไปที่เติมเต็มซึ่งกันและกัน บอลเค้าขี้เล่น ทะเล้น ชอบทำอะไรให้หัวเราะตลอด โดยเฉพาะท่าเต้นประหลาด เป็นการยากจริงๆ ที่จะให้เขียนความรู้สึกและความประทับใจที่มีต่อบอล อาจจะพูดสั้นๆได้แค่ว่า ผู้ชายคนนี้แหละที่นู๋เลือกจะใช้ชีวิตด้วยไปตลอด มินนี่รักป่าปี้นะ </p> <hr /> </div> </div> </div> <div class="col-lg-6 col-md-6 col-sm-12 text-center"> <div class="media"> <img src="img/avatar/ball.png" class=" img-circle" /> <div class="description"> <h4>Teerapat Khunpech</h4> <h4> <small> Ball </small></h4> <a href="https://facebook.com/troublemaker.khunpech" class="btn btn-social btn-facebook"><i class="fa sr-icons fa-facebook"></i></a> <a href="https://instagram.com/ballkhunpech" class="btn btn-social btn-instagram"><i class="fa sr-icons fa-instagram"></i></a> <a href="https://twitter.com/engineerball" class="btn btn-social btn-twitter"><i class="fa sr-icons fa-twitter"></i></a> <a href="https://engineerball.com" class="btn btn-social btn-globe"><i class="fa sr-icons fa-globe"></i></a> <p class="text-muted">เมื่อปี 2008 ผมเคยทำงานที่ TCDC ซึ่งเป็นที่เดียวกันกับที่นู๋ทำอยู่ ครั้งแรกที่เจอเค้าเป็นคนที่พูดเก่ง ร่าเริง ยิ้มตลอดเวลา ผมมันขี้อายด้วยก็เลยไม่กล้าเข้าไปคุยได้แต่แอบมอง แต่หลังจากที่ได้ไปกิจกรรม outing ของออฟฟิศ ผมก็เริ่มเข้าไปทำความรู้จักและตีสนิทด้วยมากขึ้น ก็นับว่าเป็นการเริ่มต้นที่ดีที่ได้คุยกัน หลังจากนั้นผมก็ออกไปทำงานที่อื่น เราก็ไม่ค่อยได้คุยกันเท่าไรแต่ก็ยังมีติดต่อบ้าง จนในปี 2012 เราจึงตกลงที่จะเป็นแฟนกัน</p> <p class="text-muted">ในปี 2016 ซึ่งเป็นปีที่คิดว่าเราน่าจะพร้อมสำหรับการใช้ชีวิตคู่ด้วยกันไปตลอดชีวิตแล้ว ผมจึงตัดสินใจที่จะขอนู๋แต่งงาน</p> <hr /> </div> </div> </div> </div> <div class="row"> <div class="col-lg-12 col-md-12 text-center"> <div class="service-box"> <i class="fa fa-4x fa-heart-o text-primary sr-icons"></i> <h3 class="text-primary">Say YES!</h3> <p class="text-muted "> <strong>บอล</strong> : "Jintana, will you marry me?" </p> <p class="text-muted"> <strong>นู๋</strong> : "YES!" </p> <p class="text-muted"> ผมมองหน้านู๋ หน้านู๋เต็มไปด้วยรอยยิ้มและน้ำตาที่ผมคิดว่านู๋ต้องมีความสุขแน่ๆ <strong>"แต่งงานกับบอลนะครับ"</strong> </p> <hr /> <p class="text-muted"> เรามีความยินดีที่จะเรียนเชิญทุกท่านไปร่วมงานมงคลสมรสของเราที่จังหวัดอุดรธานี ในวันอาทิตย์ที่ 18 ธันวาคม 2559 </p> </div> </div> </div> </div> </section> <section class="no-padding" id="portfolio"> <div class="container-fluid"> <div class="row no-gutter popup-gallery"> <div class="col-lg-4 col-sm-6"> <a href="img/portfolio/fullsize/1.jpg" class="portfolio-box"> <img src="img/portfolio/thumbnails/1.jpg" class="img-responsive" alt=""> <div class="portfolio-box-caption"> <!-- <div class="portfolio-box-caption-content"> <div class="project-category text-faded"> Category </div> <div class="project-name"> Project Name </div> </div> --> </div> </a> </div> <div class="col-lg-4 col-sm-6"> <a href="img/portfolio/fullsize/2.jpg" class="portfolio-box"> <img src="img/portfolio/thumbnails/2.jpg" class="img-responsive" alt=""> <div class="portfolio-box-caption"> <!-- <div class="portfolio-box-caption-content"> <div class="project-category text-faded"> Category </div> <div class="project-name"> Project Name </div> </div> --> </div> </a> </div> <div class="col-lg-4 col-sm-6"> <a href="img/portfolio/fullsize/3.jpg" class="portfolio-box"> <img src="img/portfolio/thumbnails/3.jpg" class="img-responsive" alt=""> <div class="portfolio-box-caption"> <!-- <div class="portfolio-box-caption-content"> <div class="project-category text-faded"> Category </div> <div class="project-name"> Project Name </div> </div> --> </div> </a> </div> <div class="col-lg-4 col-sm-6"> <a href="img/portfolio/fullsize/4.jpg" class="portfolio-box"> <img src="img/portfolio/thumbnails/4.jpg" class="img-responsive" alt=""> <div class="portfolio-box-caption"> <!-- <div class="portfolio-box-caption-content"> <div class="project-category text-faded"> Category </div> <div class="project-name"> Project Name </div> </div> --> </div> </a> </div> <div class="col-lg-4 col-sm-6"> <a href="img/portfolio/fullsize/5.jpg" class="portfolio-box"> <img src="img/portfolio/thumbnails/5.jpg" class="img-responsive" alt=""> <div class="portfolio-box-caption"> <!-- <div class="portfolio-box-caption-content"> <div class="project-category text-faded"> Category </div> <div class="project-name"> Project Name </div> </div> --> </div> </a> </div> <div class="col-lg-4 col-sm-6"> <a href="img/portfolio/fullsize/6.jpg" class="portfolio-box"> <img src="img/portfolio/thumbnails/6.jpg" class="img-responsive" alt=""> <div class="portfolio-box-caption"> <!-- <div class="portfolio-box-caption-content"> <div class="project-category text-faded"> Category </div> <div class="project-name"> Project Name </div> </div> --> </div> </a> </div> </div> </div> </section> <section id="venue"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h1 class="section-heading">Bride's House</h1> <hr class="primary"> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 text-center"> <div class="venue-box"> <p class="text-muted">270 Moo 14, Sam Phrao ,Mueang Udon Thani District, Udon Thani <a href="https://goo.gl/maps/aGLYjbc1wtv">( <i class="fa fa-map-marker"></i> Google Maps )</a> </p> </div> </div> </div> <div class="row"> <div class="col-md-12 text-center"> <div class="map-container"> <iframe src="https://www.google.com/maps/d/embed?mid=1tlU4lG0FiOLX0Kq9N8vfa8sb6Os" width="300" height="450" frameborder="0" scrolling="no" marginheight="0" marginwidth="0"></iframe> <!-- <iframe src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d1903.2797133251895!2d102.8239887!3d17.4329185!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0xb97cbaa9617d1fde!2zMTfCsDI1JzU4LjQiTiAxMDLCsDQ5JzI2LjAiRQ!5e0!3m2!1sen!2s!4v1476810924404" width="300" height="450" frameborder="0" scrolling="no" marginheight="0" marginwidth="0"></iframe> --> </div> </div> </div> </div> <div class="container"> <hr class="primary"> <div class="row"> <div class="col-lg-6 col-md-6 text-center"> <div class="service-box"> <i class="fa fa-4x fa-home text-primary sr-icons"></i> <h3>07:00 - Merit Ceremony</h3> <p class="text-muted">พิธีตักบาตร ทำบุญเลี้ยงพระ</p> </div> </div> <div class="col-lg-6 col-md-6 text-center"> <div class="service-box"> <i class="fa fa-4x fa-diamond text-primary sr-icons"></i> <h3>09:09 - Thai Wedding Ceremony</h3> <p class="text-muted">แห่ขันหมาก พิธีบายศรีสู่ขวัญ เชิญร่วมรับประทานอาหาร (อาหารพื้นบ้าน)</p> </div> </div> <div class="col-lg-6 col-md-6 text-center"> <div class="service-box"> <i class="fa fa-4x fa-glass text-primary sr-icons"></i> <h3>18:18 - Wedding Party</h3> <p class="text-muted">งานเลี้ยงฉลองมงคลสมรส เชิญร่วมรับประทานอาหาร (โต๊ะจีน)</p> </div> </div> <div class="col-lg-6 col-md-6 text-center"> <div class="service-box"> <i class="fa fa-4x fa-star-o text-primary sr-icons"></i> <h3>22:00 - After Party</h3> <p class="text-muted">ช่วงเวลาแห่งความสนุกสุดเหวี่ยงทั้ง 2 เวทีกับ DJ Obba และวงดนตรีหมอลำ พร้อมเครื่องดื่มพิเศษจากร้านซาหมวยแอนด์ซัน อุดรธานี</p> </div> </div> </div> <div class="row"> <hr class="primary" /> <div class="col-lg-12 col-md-6 text-center"> <div class="service-box"> <i class="fa fa-4x fa-female text-primary sr-icons"></i> <i class="fa fa-4x fa-male text-primary sr-icons"></i> <h3>Dress Code</h3> <p class="text-muted"><a href="http://pin.it/tzSoSH3">Indigo Craft</a> (สีคราม | ผ้ามัดย้อม | ยีนส์)</p> </div> </div> </div> <hr class="primary" /> </div> </section <section id="RSVP"> <div class="container text-center"> <div class="call-to-action"> <h1 class="section-heading">Will You Attend?</h1> <p>We would greatly appreciate it if you could respond before November 29th.</p> <a class="btn btn-primary" href="#RSVPmodal" data-toggle="modal"><h4>Please sign your RSVP</h4></a> </div> <hr class="primary" /> <!-- Modal --> <div class="modal fade" id="RSVPmodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header modal-header-primary"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h2 class="section-heading">RSVP</h2> </div> <div class="modal-body text-left"> <form class="form-horizontal" id="rsvp"> <fieldset> <div class="form-group"> <label class="col-sm-12" for="detail">Your Detail</label> <div class="col-md-12"> <div class="form-group"> <div class="col-md-6 col-sm-12 detail-box"> <div class="icon-addon addon-md"> <input id="name" name="name" type="text" placeholder="Your Name" class="form-control input-md" required=""> <label for="name" class="fa fa-user" rel="tooltip" title="name"></label> </div> </div> <div class="col-md-6 col-sm-12 detail-box"> <div class="icon-addon addon-md"> <input id="follower" name="follower" type="text" placeholder="Follower name (If you have)" class="form-control input-md"> <label for="follower" class="fa fa-user-plus" rel="tooltip" title="follower"></label> </div> </div> </div> </div> <!-- Text input--> <div class="col-md-12 col-sm-12 detail-box"> <div class="form-group"> <div class="col-md-6 col-sm-12"> <div class="icon-addon addon-md"> <input id="mobile" name="mobile" type="text" placeholder="Your mobile (081-5121231)" class="form-control input-md" required=""> <label for="follower" class="fa fa-mobile" rel="tooltip" title="follower"></label> </div> </div> <div class="col-md-6 col-sm-12 detail-box"> <div class="icon-addon addon-md"> <input id="email" name="email" type="text" placeholder="You Email" class="form-control input-md" required=""> <label for="follower" class="fa fa-envelope" rel="tooltip" title="follower"></label> </div> </div> </div> </div> </div> <hr class="primary"> <!-- Multiple Radios --> <div class="form-group"> <label class="col-sm-12" for="coming">Are You Coming?</label> <div class="col-md-12 col-sm-12"> <div class="col-sm-6"> <div class="radio"> <label for="coming-0"> <input type="radio" name="coming" id="coming" value="yes" checked> Yes, I Will be there </label> </div> </div> <div class="col-sm-6"> <div class="radio"> <label for="coming-1"> <input type="radio" name="coming" id="not-coming" value="no"> Sorry, I can't make it </label> </div> </div> </div> </div> <!-- Wish message --> <div id="wish"> <div class="form-group"> <div class="col-md-12 col-sm-12"> <div class="col-sm-12"> <label for="coming-0">On your wedding day, I wish</label> <textarea class="form-control animated" name="wish" id="wish" placeholder="Write your wish..."></textarea> <!-- <button class="btn btn-info pull-right" style="margin-top:10px" type="button">Share</button> --> <!-- <button id="submit" name="submit" class="btn btn-info pull-right" style="margin-top:10px">Congrats</button> --> </div> </div> </div> </div> <!-- going --> <div id="going"> <!-- Multiple Radios --> <div class="form-group"> <label class="col-sm-12" for="when">When you join us on?</label> <div class="col-md-8"> <select id="join" name="join" class="form-control"> <option value="0">Both event (Ceremoney & Party)</option> <option value="1">Thai Wedding Ceremony (09:09)</option> <option value="2">Wedding Party (18:18)</option> </select> </div> </div> <!-- Text input--> <!-- Select Basic --> <div class="form-group"> <div class="col-sm-12 col-md-12"> <label for"room-preference">Do you want us to book a room?</label> </div> <div class="col-md-8 col-sm-8"> <select id="room" name="room" class="form-control"> <option value="0">Never mind, thanks</option> <option value="1">Yes - Double bed</option> <option value="2">Yes - Twin bed</option> </select> <!-- In and Out time --> <div id="in-out-time" class="in-out-time"> <div class="form-group"> <label class="col-md-12 col-sm-12" for="in-out-time">In & Out</label> <div class="col-md-6 col-sm-12"> <div class="radio radio-primary"> <label for="night1" ><input type="radio" name="room-date" id="night1" value="17-18" checked> 17 Dec - 18 Dec</label> </div> <div class="radio radio-primary"> <label for="night2" ><input type="radio" name="room-date" id="night2" value="17-19"> 17 Dec - 19 Dec</label> </div> </div> <div class="col-md-12 col-sm-12"> <div class="radio inline-radio"> <label> <input type="radio" id="radio-value" name="room-date" value="other" /> </label>Other: <input id="room-date-input" class="form-control" name="room-date-input" type="text" placeholder="Write your date" value="" /> </div> </div> </div> </div> </div> <div class="col-sm-12"> <small class="text-muted">MinnieBall love to reserve your room at <a class="text-primary" href="http://www.leelawadeegrand.com/" target="_blank">Leelawadee Grand <i class="fa fa-building text-primary"></i></a>, You can pay at reception counter hotel for 600 baht/night when you checkout.</small> </div> </div> <!-- Button (Double) --> <!-- <div class="form-group"> <label class="col-md-4 control-label" for="submit"></label> <div class="col-md-6"> <button id="submit" name="submit" class="btn btn-info">Submit</button> </div> </div> --> </fieldset> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Close</button> <button type="button" id="submit" name="submit" class="btn btn-info pull-right">Submit</button> </div> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> <!-- Modal --> </div> </section> <section id="contact"> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 text-center"> <h1 class="section-heading">One Picture Is Worth A Thousand Words</h1> <hr class="primary"> <p> <i class="fa fa fa-instagram"></i> <a href="https://www.instagram.com/explore/tags/minnieballinlove/">#MinnieBallInLove</a></p> <p> <i class="fa fa fa-facebook"></i> <a href="https://facebook.com/minnieballinlove/">facebook.com/minnieballinlove</a></p> </div> </div> </div> </section> <!-- jQuery --> <script src="vendor/jquery/jquery.min.js"></script> <!-- Bootstrap Core JavaScript --> <script src="vendor/bootstrap/js/bootstrap.min.js"></script> <!-- Plugin JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script> <script src="vendor/scrollreveal/scrollreveal.min.js"></script> <script src="vendor/magnific-popup/jquery.magnific-popup.min.js"></script> <!-- Theme JavaScript --> <script src="js/creative.min.js"></script> <script src="js/sweetalert.min.js"></script> <script src="js/form.js"></script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-86722422-1', 'auto'); ga('send', 'pageview'); </script> </body> </html>
engineerball/minnieballinlove
index.html
HTML
mit
29,924
<?php /** * Backq: Background tasks with workers & publishers via queues * * Copyright (c) 2013-2019 Sergei Shilko * * Distributed under the terms of the MIT License. * Redistributions of files must retain the above copyright notice. */ namespace BackQ\Message\Amazon\SNS\Application\PlatformEndpoint; class Register implements RegisterMessageInterface { /** * Associative array of string keys mapping to values, they'll be the attributes * set for an endpoint and could vary depending on the platform application * * @var array */ protected $attributes; /** * Unique identifier created by the notification service for an app on a device * * @var string */ protected $token; /** * Amazon Resource Identifier of the Platform application that an endpoint * will be registered in * * @var string */ protected $applicationArn; /** * Get the specific attributes to create endpoints * @return array */ public function getAttributes() : array { return $this->attributes; } /** * Sets attributes specific to different platforms in order to publish a message * * @param array $attrs */ public function setAttributes(array $attrs) { $this->attributes = $attrs; } /** * Get the resource name for the Application Platform where an endpoint * where an endpoint will be saved * @return string */ public function getApplicationArn() : string { return $this->applicationArn; } /** * Sets up the Resource Number for a Platform Application * @param $appArn */ public function setApplicationArn(string $appArn) { $this->applicationArn = $appArn; } /** * Gets the token or identifier for the device to register * @return string */ public function getToken() : string { return $this->token; } /** * Adds a unique identifier created by the notification service for the app on a device * @param $token */ public function addToken(string $token) { $this->token = $token; } }
sshilko/backq
src/Message/Amazon/SNS/Application/PlatformEndpoint/Register.php
PHP
mit
2,205
/* * Copyright 2014 kevin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #ifndef QWEBRESPONSE_H #define QWEBRESPONSE_H #include "../private/qtwebservicefwd.h" #include <functional> #include <QObject> #include <QSharedPointer> #include <QHash> #include <QStringList> #include <QFile> #include <QJsonDocument> #include <QJsonObject> #include <QDomDocument> #include <QHttpServer/qhttpresponse.h> class QTWEBSERVICE_API QWebResponse : public QObject { Q_OBJECT public: enum ResponseError { SUCCESS = 0, //!< Tried to write response, no data was set NO_DATA_SET, //!< QFile was attempted to be read, and was non-existant FILE_DOES_NOT_EXIST = 10, FILE_COULD_NOT_OPEN, NULLPTR = 100 }; typedef QHttpResponse::StatusCode StatusCode; /** * @brief create Create a new instance of %QWebRequest * @return Shared pointer */ static QSharedPointer<QWebResponse> create(); /** * @brief setHeader Sets a header parameter based on the type passed * @param key * @param value */ void setHeader(const QString key, const QString value); /** * @brief setStatusCode Set the response to use the status code. * @param code */ void setStatusCode(StatusCode code); /** * @brief writeFile Enqueues the %QFile to be written to the output stream as a byte array. This is done by reading * the file to a bytestream, and writing it after. * @param file File that will be read, this will emit the signal to middleware hooks * @return */ bool writeFile( QFile file); bool writeText(const QString text, const QString contentType = "text/plain"); // bool writeText(const QByteArray &text); bool writeJson(const QJsonDocument doc); inline bool writeJson(const QJsonObject &obj) { return writeJson(QJsonDocument(obj)); } // bool writeXML(const QDomDocument &doc); /** * @brief isValidResponse returns true if a response was queued to be written * @return */ bool isValidResponse(); /** * @brief writeToResponse writes the stored data to the QHttpResponse instance * @param httpResponse Response to write data to * @return */ ResponseError writeToResponse(QSharedPointer<QWebRequest> req, QHttpResponse *httpResponse); virtual ~QWebResponse(); signals: /** * @brief modifyOutputData emitted when data is about to be written to a QHttpResponse * @param in * @param out use QSharedPointer::reset to set this shared pointer to a new value for use */ void responseDataPrepared(QSharedPointer<QWebRequest> req, QByteArray in, QSharedPointer<QByteArray> &out); private: QWebResponse(); std::function<QByteArray(ResponseError *)> m_outFunc; QHash<QString, QString> m_headers; StatusCode m_status; }; #endif // QWEBRESPONSE_H
Nava2/QtWebService
include/router/QWebResponse.h
C
mit
3,961
<?php namespace UserBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class CityType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('name', 'text', array('label' => false, 'attr' => array('class' => 'form-control input-md'))) ->add('zip', 'text', array('label' => false, 'attr' => array('class' => 'form-control input-md'))) ; } /** * @param OptionsResolverInterface $resolver */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'UserBundle\Entity\City' )); } /** * @return string */ public function getName() { return 'userbundle_city'; } }
Kelevari/webshop-opdracht
src/UserBundle/Form/CityType.php
PHP
mit
1,032
package AsposeStorageCloud::ApiClient; use strict; use warnings; use utf8; use MIME::Base64; use LWP::UserAgent; use HTTP::Headers; use HTTP::Response; use HTTP::Request::Common qw(DELETE POST GET HEAD PUT); use HTTP::Status; use URI::Query; use JSON; use URI::Escape; use Scalar::Util; use Log::Any qw($log); use Carp; use Module::Runtime qw(use_module); use Digest::HMAC_SHA1; use MIME::Base64; use AsposeStorageCloud::Configuration; sub new { if(not defined $AsposeStorageCloud::Configuration::app_sid or $AsposeStorageCloud::Configuration::app_sid eq ''){ croak("Aspose Cloud App SID key is missing."); } if(not defined $AsposeStorageCloud::Configuration::api_key or $AsposeStorageCloud::Configuration::api_key eq ''){ croak("Aspose Cloud API key is missing."); } my $class = shift; my (%args) = ( 'ua' => LWP::UserAgent->new, 'base_url' => $AsposeStorageCloud::Configuration::api_server, @_ ); return bless \%args, $class; } # Set the user agent of the API client # # @param string $user_agent The user agent of the API client # sub set_user_agent { my ($self, $user_agent) = @_; $self->{http_user_agent}= $user_agent; } # Set timeout # # @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] # sub set_timeout { my ($self, $seconds) = @_; if (!looks_like_number($seconds)) { croak('Timeout variable must be numeric.'); } $self->{http_timeout} = $seconds; } # make the HTTP request # @param string $resourcePath path to method endpoint # @param string $method method to call # @param array $queryParams parameters to be place in query URL # @param array $postData parameters to be placed in POST body # @param array $headerParams parameters to be place in request header # @return mixed sub call_api { my $self = shift; my ($resource_path, $method, $query_params, $post_params, $header_params, $body_data, $auth_settings) = @_; $resource_path =~ s/\Q{appSid}\E/$AsposeStorageCloud::Configuration::app_sid/g; my $_url = $self->{base_url} . $resource_path; # update signature my $signature = $self->sign($_url, $AsposeStorageCloud::Configuration::app_sid, $AsposeStorageCloud::Configuration::api_key); $_url = $_url . '&signature=' . $signature; if($AsposeStorageCloud::Configuration::debug){ print "\nFinal URL: ".$method."::".$_url; } # body data $body_data = to_json($body_data->to_hash) if defined $body_data && $body_data->can('to_hash'); # model to json string my $_body_data = keys %$post_params > 1 ? $post_params : $body_data; #my $_body_data = $body_data; # Make the HTTP request my $_request; if ($method eq 'POST') { # multipart $header_params->{'Content-Type'} = lc $header_params->{'Content-Type'} eq 'multipart/form' ? 'form-data' : $header_params->{'Content-Type'}; $_request = POST($_url, %$header_params, Content => $_body_data); } elsif ($method eq 'PUT') { # multipart $header_params->{'Content-Type'} = lc $header_params->{'Content-Type'} eq 'multipart/form' ? 'form-data' : $header_params->{'Content-Type'}; $_request = PUT($_url, %$header_params, Content => $_body_data); } elsif ($method eq 'GET') { my $headers = HTTP::Headers->new(%$header_params); $_request = GET($_url, %$header_params); } elsif ($method eq 'HEAD') { my $headers = HTTP::Headers->new(%$header_params); $_request = HEAD($_url,%$header_params); } elsif ($method eq 'DELETE') { #TODO support form data my $headers = HTTP::Headers->new(%$header_params); $_request = DELETE($_url, %$headers); } elsif ($method eq 'PATCH') { #TODO } else { } $self->{ua}->timeout($self->{http_timeout} || $AsposeStorageCloud::Configuration::http_timeout); $self->{ua}->agent($self->{http_user_agent} || $AsposeStorageCloud::Configuration::http_user_agent); my $_response = $self->{ua}->request($_request); unless ($_response->is_success) { croak("API Exception(".$_response->code."): ".$_response->message); } return $_response; } # Take value and turn it into a string suitable for inclusion in # the path, by url-encoding. # @param string $value a string which will be part of the path # @return string the serialized object sub to_path_value { my ($self, $value) = @_; return uri_escape($self->to_string($value)); } # Take value and turn it into a string suitable for inclusion in # the query, by imploding comma-separated if it's an object. # If it's a string, pass through unchanged. It will be url-encoded # later. # @param object $object an object to be serialized to a string # @return string the serialized object sub to_query_value { my ($self, $object) = @_; if (is_array($object)) { return implode(',', $object); } else { return $self->to_string($object); } } # Take value and turn it into a string suitable for inclusion in # the header. If it's a string, pass through unchanged # If it's a datetime object, format it in ISO8601 # @param string $value a string which will be part of the header # @return string the header string sub to_header_value { my ($self, $value) = @_; return $self->to_string($value); } # Take value and turn it into a string suitable for inclusion in # the http body (form parameter). If it's a string, pass through unchanged # If it's a datetime object, format it in ISO8601 # @param string $value the value of the form parameter # @return string the form string sub to_form_value { my ($self, $value) = @_; return $self->to_string($value); } # Take value and turn it into a string suitable for inclusion in # the parameter. If it's a string, pass through unchanged # If it's a datetime object, format it in ISO8601 # @param string $value the value of the parameter # @return string the header string sub to_string { my ($self, $value) = @_; if (ref($value) eq "DateTime") { # datetime in ISO8601 format return $value->datetime(); } else { return $value; } } # Deserialize a JSON string into an object # # @param string $class class name is passed as a string # @param string $data data of the body # @return object an instance of $class sub deserialize { my ($self, $class, $data) = @_; $log->debugf("deserializing %s for %s", $data, $class); if (not defined $data) { return undef; } elsif ( (substr($class, 0, 5)) eq 'HASH[') { #hash if ($class =~ /^HASH\[(.*),(.*)\]$/) { my ($key_type, $type) = ($1, $2); my %hash; my $decoded_data = decode_json $data; foreach my $key (keys %$decoded_data) { if (ref $decoded_data->{$key} eq 'HASH') { $hash{$key} = $self->deserialize($type, encode_json $decoded_data->{$key}); } else { $hash{$key} = $self->deserialize($type, $decoded_data->{$key}); } } return \%hash; } else { #TODO log error } } elsif ( (substr($class, 0, 6)) eq 'ARRAY[' ) { # array of data return $data if $data eq '[]'; # return if empty array my $_sub_class = substr($class, 6, -1); my $_json_data = decode_json $data; my @_values = (); foreach my $_value (@$_json_data) { if (ref $_value eq 'ARRAY') { push @_values, $self->deserialize($_sub_class, encode_json $_value); } else { push @_values, $self->deserialize($_sub_class, $_value); } } return \@_values; } elsif ($class eq 'DateTime') { return DateTime->from_epoch(epoch => str2time($data)); } elsif (grep /^$class$/, ('string', 'int', 'float', 'bool', 'object')) { return $data; } else { # model my $_instance = use_module("AsposeStorageCloud::Object::$class")->new; if (ref $data eq "HASH") { return $_instance->from_hash($data); } else { # string, need to json decode first return $_instance->from_hash(decode_json $data); } } } # return 'Accept' based on an array of accept provided # @param [Array] header_accept_array Array fo 'Accept' # @return String Accept (e.g. application/json) sub select_header_accept { my ($self, @header) = @_; if (@header == 0 || (@header == 1 && $header[0] eq '')) { return undef; } elsif (grep(/^application\/json$/i, @header)) { return 'application/json'; } else { return join(',', @header); } } # return the content type based on an array of content-type provided # @param [Array] content_type_array Array fo content-type # @return String Content-Type (e.g. application/json) sub select_header_content_type { my ($self, @header) = @_; if (@header == 0 || (@header == 1 && $header[0] eq '')) { return 'application/json'; # default to application/json } elsif (grep(/^application\/json$/i, @header)) { return 'application/json'; } else { return join(',', @header); } } sub pre_deserialize { my ($self, $data, $class, $content_type) = @_; $log->debugf("pre_deserialize %s for %s and content_type %s", $data, $class, $content_type); if ($class eq "ResponseMessage") { if (defined $content_type and lc $content_type ne 'application/json' ) { my $_instance = use_module("AsposeStorageCloud::Object::$class")->new; $_instance->{'Status'} = 'OK'; $_instance->{'Code'} = 200; $_instance->{'Content'} = $data; return $_instance; } } if ( (defined $content_type) && ($content_type !~ m/json/) ) { croak("API Exception(406.): Invalid contentType".$content_type); } return $self->deserialize($class, $data); } # return signature for aspose cloud api sub sign { my ($self, $url_to_sign, $appSid, $appKey) = @_; #return if (!defined($url_to_sign) || scalar(@$auth_settings) == 0); my $hmac = Digest::HMAC_SHA1->new($appKey); $hmac->add($url_to_sign); my $signature = $hmac->digest; $signature = encode_base64($signature, ''); $signature =~ s/=//; $log->debugf ("signature :: ".$signature); return $signature; } 1;
farooqsheikhpk/Aspose_Total_Cloud
SDKs/Aspose.Storage-Cloud-SDK-for-Perl/lib/AsposeStorageCloud/ApiClient.pm
Perl
mit
10,546
import { Component,ViewEncapsulation } from '@angular/core'; @Component({ selector: 'user', templateUrl: './app/user/user.html', encapsulation: ViewEncapsulation.None // , // styleUrls: ['./app/page/catalogue.component.css'] }) export class User{ name = ' User' }
nsuhanshetty/Las-Console
app/user/user.component.ts
TypeScript
mit
286
export default { "Discovery API v2" : { api: require("_data/orgs/discovery-api/v2/api.json"), meta: require("_data/orgs/discovery-api/v2/methods-metadata.json") }, "Commerce API" : { api: require("_data/orgs/commerce-api/v2-internal/api.json"), meta: require("_data/orgs/commerce-api/v2-internal/methods-metadata.json") } }
ticketmaster-api/ticketmaster-api.github.io
scripts/api-explorer/v2/api.sources-internal.js
JavaScript
mit
336
using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; namespace NetOffice.ExcelApi { /// <summary> /// Interface ISparkHorizontalAxis /// SupportByVersion Excel, 14,15,16 /// </summary> [SupportByVersion("Excel", 14,15,16)] [EntityType(EntityType.IsInterface)] public class ISparkHorizontalAxis : COMObject { #pragma warning disable #region Type Information /// <summary> /// Instance Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type InstanceType { get { return LateBindingApiWrapperType; } } private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(ISparkHorizontalAxis); return _type; } } #endregion #region Ctor /// <param name="factory">current used factory core</param> /// <param name="parentObject">object there has created the proxy</param> /// <param name="proxyShare">proxy share instead if com proxy</param> public ISparkHorizontalAxis(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public ISparkHorizontalAxis(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ISparkHorizontalAxis(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ISparkHorizontalAxis(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ISparkHorizontalAxis(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ISparkHorizontalAxis(ICOMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ISparkHorizontalAxis() : base() { } /// <param name="progId">registered progID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ISparkHorizontalAxis(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion Excel 14, 15, 16 /// Get /// </summary> [SupportByVersion("Excel", 14,15,16)] public NetOffice.ExcelApi.Application Application { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.Application>(this, "Application", NetOffice.ExcelApi.Application.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion Excel 14, 15, 16 /// Get /// </summary> [SupportByVersion("Excel", 14,15,16)] public NetOffice.ExcelApi.Enums.XlCreator Creator { get { return Factory.ExecuteEnumPropertyGet<NetOffice.ExcelApi.Enums.XlCreator>(this, "Creator"); } } /// <summary> /// SupportByVersion Excel 14, 15, 16 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersion("Excel", 14,15,16), ProxyResult] public object Parent { get { return Factory.ExecuteReferencePropertyGet(this, "Parent"); } } /// <summary> /// SupportByVersion Excel 14, 15, 16 /// Get /// </summary> [SupportByVersion("Excel", 14,15,16)] public NetOffice.ExcelApi.SparkColor Axis { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.SparkColor>(this, "Axis", NetOffice.ExcelApi.SparkColor.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion Excel 14, 15, 16 /// Get /// </summary> [SupportByVersion("Excel", 14,15,16)] public bool IsDateAxis { get { return Factory.ExecuteBoolPropertyGet(this, "IsDateAxis"); } } /// <summary> /// SupportByVersion Excel 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 14,15,16)] public bool RightToLeftPlotOrder { get { return Factory.ExecuteBoolPropertyGet(this, "RightToLeftPlotOrder"); } set { Factory.ExecuteValuePropertySet(this, "RightToLeftPlotOrder", value); } } #endregion #region Methods #endregion #pragma warning restore } }
NetOfficeFw/NetOffice
Source/Excel/Interfaces/ISparkHorizontalAxis.cs
C#
mit
5,741
# -*- coding: utf-8 -*- # # monthlyReportNew documentation build configuration file, created by # sphinx-quickstart on Thu Feb 2 15:15:13 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys # sys.path.insert(0, u'/home/shankha/programs/glycoLeap/monthlyReportNew/monthlyReportNew') sys.path.insert(0, os.path.abspath(os.path.pardir)) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General information about the project. project = u'monthlyReportNew' copyright = u'2017, Author' author = u'Author' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = u'' # The full version, including alpha/beta/rc tags. release = u'' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = 'en' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = 'monthlyReportNewdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'monthlyReportNew.tex', u'monthlyReportNew Documentation', u'Author', 'manual'), ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'monthlyreportnew', u'monthlyReportNew Documentation', [author], 1) ] # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'monthlyReportNew', u'monthlyReportNew Documentation', author, 'monthlyReportNew', 'One line description of project.', 'Miscellaneous'), ] # -- Options for Epub output ---------------------------------------------- # Bibliographic Dublin Core info. epub_title = project epub_author = author epub_publisher = author epub_copyright = copyright # The unique identifier of the text. This can be a ISBN number # or the project homepage. # # epub_identifier = '' # A unique identification for the text. # # epub_uid = '' # A list of files that should not be packed into the epub file. epub_exclude_files = ['search.html']
Holmusk/glycoleapMonthlyReportNew
docs/conf.py
Python
mit
5,417
extern crate sdl2; use sdl2::pixels::Color; pub fn main() { let mut sdl_context = sdl2::init().video().unwrap(); let window = sdl_context.window("rust-sdl2 demo: Window", 800, 600) .resizable() .build() .unwrap(); let mut renderer = window.renderer().present_vsync().build().unwrap(); let mut running = true; let mut tick = 0; while running { for event in sdl_context.event_pump().poll_iter() { use sdl2::event::Event; use sdl2::keycode::KeyCode; match event { Event::Quit {..} | Event::KeyDown { keycode: KeyCode::Escape, .. } => { running = false }, _ => {} } } { // Update the window title. // &sdl_context is needed to safely access the Window and to ensure that the event loop // isn't running (which could mutate the Window). // Note: if you don't use renderer: window.properties(&sdl_context); let mut props = renderer.window_properties(&sdl_context).unwrap(); let position = props.get_position(); let size = props.get_size(); let title = format!("Window - pos({}x{}), size({}x{}): {}", position.0, position.1, size.0, size.1, tick); props.set_title(&title); tick += 1; } let mut drawer = renderer.drawer(); drawer.set_draw_color(Color::RGB(0, 0, 0)); drawer.clear(); drawer.present(); } }
nukep/rust-sdl2
examples/window-properties.rs
Rust
mit
1,561
#!/usr/bin/env python3 # Copyright (c) 2015-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test mulitple rpc user config option rpcauth # from test_framework.test_framework import BitcoinTestFramework from test_framework.util import str_to_b64str, assert_equal import os import http.client import urllib.parse class HTTPBasicsTest (BitcoinTestFramework): def __init__(self): super().__init__() self.setup_clean_chain = False self.num_nodes = 1 def setup_chain(self): super().setup_chain() #Append rpcauth to bitcoin.conf before initialization rpcauth = "rpcauth=rt:93648e835a54c573682c2eb19f882535$7681e9c5b74bdd85e78166031d2058e1069b3ed7ed967c93fc63abba06f31144" rpcauth2 = "rpcauth=rt2:f8607b1a88861fac29dfccf9b52ff9f$ff36a0c23c8c62b4846112e50fa888416e94c17bfd4c42f88fd8f55ec6a3137e" with open(os.path.join(self.options.tmpdir+"/node0", "woodcoin.conf"), 'a', encoding='utf8') as f: f.write(rpcauth+"\n") f.write(rpcauth2+"\n") def setup_network(self): self.nodes = self.setup_nodes() def run_test(self): ################################################## # Check correctness of the rpcauth config option # ################################################## url = urllib.parse.urlparse(self.nodes[0].url) #Old authpair authpair = url.username + ':' + url.password #New authpair generated via share/rpcuser tool rpcauth = "rpcauth=rt:93648e835a54c573682c2eb19f882535$7681e9c5b74bdd85e78166031d2058e1069b3ed7ed967c93fc63abba06f31144" password = "cA773lm788buwYe4g4WT+05pKyNruVKjQ25x3n0DQcM=" #Second authpair with different username rpcauth2 = "rpcauth=rt2:f8607b1a88861fac29dfccf9b52ff9f$ff36a0c23c8c62b4846112e50fa888416e94c17bfd4c42f88fd8f55ec6a3137e" password2 = "8/F3uMDw4KSEbw96U3CA1C4X05dkHDN2BPFjTgZW4KI=" authpairnew = "rt:"+password headers = {"Authorization": "Basic " + str_to_b64str(authpair)} conn = http.client.HTTPConnection(url.hostname, url.port) conn.connect() conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) resp = conn.getresponse() assert_equal(resp.status==401, False) conn.close() #Use new authpair to confirm both work headers = {"Authorization": "Basic " + str_to_b64str(authpairnew)} conn = http.client.HTTPConnection(url.hostname, url.port) conn.connect() conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) resp = conn.getresponse() assert_equal(resp.status==401, False) conn.close() #Wrong login name with rt's password authpairnew = "rtwrong:"+password headers = {"Authorization": "Basic " + str_to_b64str(authpairnew)} conn = http.client.HTTPConnection(url.hostname, url.port) conn.connect() conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) resp = conn.getresponse() assert_equal(resp.status==401, True) conn.close() #Wrong password for rt authpairnew = "rt:"+password+"wrong" headers = {"Authorization": "Basic " + str_to_b64str(authpairnew)} conn = http.client.HTTPConnection(url.hostname, url.port) conn.connect() conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) resp = conn.getresponse() assert_equal(resp.status==401, True) conn.close() #Correct for rt2 authpairnew = "rt2:"+password2 headers = {"Authorization": "Basic " + str_to_b64str(authpairnew)} conn = http.client.HTTPConnection(url.hostname, url.port) conn.connect() conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) resp = conn.getresponse() assert_equal(resp.status==401, False) conn.close() #Wrong password for rt2 authpairnew = "rt2:"+password2+"wrong" headers = {"Authorization": "Basic " + str_to_b64str(authpairnew)} conn = http.client.HTTPConnection(url.hostname, url.port) conn.connect() conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) resp = conn.getresponse() assert_equal(resp.status==401, True) conn.close() if __name__ == '__main__': HTTPBasicsTest ().main ()
funkshelper/woodcore
qa/rpc-tests/multi_rpc.py
Python
mit
4,576
// import { moduleForModel, test } from 'ember-qunit'; // moduleForModel('application', 'Unit | Serializer | application', { // // Specify the other units that are required for this test. // needs: [] // }); // Replace this with your real tests. // test('it serializes records', function(assert) { // // @TODO // });
chinthakagodawita/dashfuddle
tests/unit/serializers/application-test.js
JavaScript
mit
325
MistRainDetector ================ DSP Audio rain intensity detector. The embedded implementation is located in src/Detector.c. Include inc/Detector.h to use. The algorithm is implemented in MATLAB in file matlab/Detector.m.
mgraczyk/MistRainDetector
README.md
Markdown
mit
242
import axios from 'axios' import request from 'request' import fs from 'fs' import config from '../../../conf' import models from '../../models' const { Pic } = models export async function getProxy (ctx) { try { const imgPath = config.rootPath + '/upload/test4.jpg' request({ url: 'http://i.meizitu.net/2017/08/27c16.jpg', headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1' } }).pipe(fs.createWriteStream(imgPath)) ctx.body = 'pic is downloading' } catch (e) { ctx.throw(422, e.message) } } export async function test (ctx) { try { ctx.body = 'pic is downloading' } catch (e) { ctx.throw(422, e.message) } }
ZZR-china/YeKi
src/resources/pics/controller.js
JavaScript
mit
760
<?php // src/Blogger/BlogBundle/Form/EnquiryType.php namespace Blogger\BlogBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; class EnquiryType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('name'); $builder->add('email', 'email'); $builder->add('subject'); $builder->add('body', 'textarea'); } public function getName() { return 'contact'; } }
budds12/sf2
src/Blogger/BlogBundle/Form/EnquiryType.php
PHP
mit
525
'use strict'; module.exports = { up: function(queryInterface, Sequelize) { return queryInterface.createTable('rol', { id_rol: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true }, nombre: { type: Sequelize.STRING, allowNull: false }, descripcion: { type: Sequelize.STRING, }, _fecha_creacion: { type: Sequelize.DATE, allowNull: false }, _fecha_modificacion: { type: Sequelize.DATE, allowNull: false } }); }, down: function(queryInterface, Sequelize) { return queryInterface.dropTable('rol'); } };
waquispe/base-backend-express
src/migrations/20170506011000-create-rol.js
JavaScript
mit
698
<div class="row-fluid"> <div class="span6 offset3"> <img src="<?php echo image_path("logo.png");?>" class="text-center"/> </div> </div> <hr> <div class="row-fluid"> <div class="span3 offset1"> <div class="panel panel-default"> <div class="panel-heading">Operación</div> <ul class="nav nav-list"> <li><a href="<?php echo url_for("@productor");?>">Padrón de Productores</a></li> <li><a href="<?php echo url_for("@consulta");?>">Consultas realizadas</a></li> <li><a href="<?php echo url_for("inicio/simulador");?>">Simulador de Cuotas</a></li> </ul> </div> </div> <div class="span3"> <div class="panel panel-default"> <div class="panel-heading">Gestión de datos</div> <ul class="nav nav-list"> <li><a href="<?php echo url_for("@actividad");?>">Actividades Productivas</a></li> <li><a href="<?php echo url_for("@oficina");?>">Oficinas CORFO</a></li> <li><a href="<?php echo url_for("@localidad");?>">Localidades</a></li> </ul> </div> </div> <div class="span3"> <div class="panel panel-default"> <div class="panel-heading">Administración</div> <ul class="nav nav-list"> <li><a href="<?php echo url_for("@sf_guard_change_password");?>">Cambiar mi contraseña</a></li> <?php if($sf_user->puedeGestionarUsuarios()):?> <li><a href="<?php echo url_for("@sf_guard_user");?>">Usuarios del sistema</a></li> <?php endif;?> <li><a href="<?php echo url_for("@sf_guard_signout");?>">Salir</a></li> </ul> </div> </div> </div>
juira/crecer_chubut
apps/frontend/modules/inicio/templates/indexSuccess.php
PHP
mit
1,603
# class A(object): # def __call__(self): # print("invoking __call__ from A!") # if __name__ == "__main__": # a = A() # a()# output: invoking __call__ from A # a.__call__ = lambda: "invoking __call__ from lambda" # print a.__call__() # a() class C(object): '''There is comment ''' pass def __len__(self): return 5 c = C() c.__len__ = lambda: 5 print c.__dict__ print type(c).__dict__ print len(c)
cwlseu/cwlseu.github.io
images/codes/py_call.py
Python
mit
412
const babel = require('babel-core'); const content = ` export type ExportedType = { bar: number, }; class MyComponent extends React.Component { props: { foo: string } & ExportedType; } `; it('intersection inline with exported type', () => { const res = babel.transform(content, { babelrc: false, presets: ['@babel/env', '@babel/react', '@babel/flow'], plugins: [ '@babel/syntax-flow', require('../'), "@babel/plugin-proposal-class-properties" ], }).code; expect(res).toMatchSnapshot(); });
brigand/babel-plugin-flow-react-proptypes
src/__tests__/intersection-inline-with-exported-type.js
JavaScript
mit
543
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>18 --> 19</title> <link href="./../../assets/style.css" rel="stylesheet"> </head> <body> <h2>You have to be fast</h2> <a href="./afbe90500cc7c34796742aec89b8053674b2709fd2499b8adbfc280729e43fa2.html">Teleport</a> <hr> <a href="./../../about.md">About</a> (Spoilers! ) <script src="./../../assets/md5.js"></script> <script> window.currentLevel = 7; </script> <script src="./../../assets/script.js"></script> </body> </html>
simonmysun/praxis
TAIHAO2019/pub/SmallGame/AsFastAsYouCan2/09bd2f3197ec01314cf3094aae8648efee2b44b822fe9e2311213378b8142684.html
HTML
mit
550
// O365 - Migration Banner function addcss(css) { var head = document.getElementsByTagName('head')[0]; var s = document.createElement('style'); s.setAttribute('type', 'text/css'); if (s.styleSheet) { // IE s.styleSheet.cssText = css; } else { // the world s.appendChild(document.createTextNode(css)); } head.appendChild(s); } // CSS Inject addcss('#status_preview_body {display:none}'); // Migration Function MigrationBannerCount = 0; function MigrationBanner() { var sp = document.getElementById('status_preview'); if (MigrationBannerCount > 10) { console.log('MigrationBanner - safety, max attempts, to prevent infinite loop'); //safety, max attempts, to prevent infinite loop return } if (!sp) { console.log('MigrationBanner - wait and check later'); //wait and check later MigrationBannerCount++; window.setTimeout(MigrationBanner, 200); return; } else { console.log('MigrationBanner - found and modify'); //found and modify var h = sp.innerHTML; h = h.replace("This site is read only at the farm administrator's request.", '<table border=0><tr><td><img src="/_layouts/images/kpinormallarge-1.gif" height="15px" width="15px" style="padding-right:20px"/></td><td><b>MIGRATION IN PROGRESS:</b> This site is being moved to Office 365 and will be locked as Read-Only until its migration is complete.<br/>Please check in soon to be automatically redirected to this site’s new location in the cloud. <a href="https://kbarticle">Learn more...</a></td></tr><table>'); sp.innerHTML = h; addcss('#status_preview_body {display:inherit}'); } } function MigrationBannerLoad() { ExecuteOrDelayUntilScriptLoaded(MigrationBanner, "sp.js") } // Delay Load window.setTimeout('MigrationBannerLoad()', 1000);
spjeff/office365
office365-migration-banner/o365-migration-banner.js
JavaScript
mit
1,746
Excess Kurtosis === [![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Coverage Status][codecov-image]][codecov-url] [![Dependencies][dependencies-image]][dependencies-url] > [Chi-squared](https://en.wikipedia.org/wiki/Chi-squared_distribution) distribution [excess kurtosis](https://en.wikipedia.org/wiki/Kurtosis). The [excess kurtosis](https://en.wikipedia.org/wiki/Kurtosis) for a [Chi-squared](https://en.wikipedia.org/wiki/Chi-squared_distribution) random variable is <div class="equation" align="center" data-raw-text="\gamma_2 = \frac{12}{k}" data-equation="eq:ekurtosis"> <img src="https://cdn.rawgit.com/distributions-io/chisquare-ekurtosis/f9045dc0bbde0215c411e73536bb50d3e30c0f03/docs/img/eqn.svg" alt="Excess kurtosis for a Chi-squared distribution."> <br> </div> where `k > 0` is the degrees of freedom. ## Installation ``` bash $ npm install distributions-chisquare-ekurtosis ``` For use in the browser, use [browserify](https://github.com/substack/node-browserify). ## Usage ``` javascript var ekurtosis = require( 'distributions-chisquare-ekurtosis' ); ``` #### ekurtosis( k[, opts] ) Computes the [excess kurtosis](https://en.wikipedia.org/wiki/Kurtosis) for a [Chi-squared](https://en.wikipedia.org/wiki/Chi-squared_distribution) distribution with parameter `k`. `k` may be either a [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number), an [`array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array), a [`typed array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays), or a [`matrix`](https://github.com/dstructs/matrix). ``` javascript var matrix = require( 'dstructs-matrix' ), data, mat, out, i; out = ekurtosis( 2 ); // returns ~6.000 k = [ 2, 4, 8, 16 ]; out = ekurtosis( k ); // returns [ ~6.000, ~3.000, ~1.500, ~0.750 ] k = new Float32Array( k ); out = ekurtosis( k ); // returns Float64Array( [~6.000,~3.000,~1.500,~0.750] ) k = matrix( [ 2, 4, 8, 16 ], [2,2] ); /* [ 2 4, 8 16 ] */ out = ekurtosis( k ); /* [ ~6.000 ~3.000, ~1.500 ~0.750 ] */ ``` The function accepts the following `options`: * __accessor__: accessor `function` for accessing `array` values. * __dtype__: output [`typed array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays) or [`matrix`](https://github.com/dstructs/matrix) data type. Default: `float64`. * __copy__: `boolean` indicating if the `function` should return a new data structure. Default: `true`. * __path__: [deepget](https://github.com/kgryte/utils-deep-get)/[deepset](https://github.com/kgryte/utils-deep-set) key path. * __sep__: [deepget](https://github.com/kgryte/utils-deep-get)/[deepset](https://github.com/kgryte/utils-deep-set) key path separator. Default: `'.'`. For non-numeric `arrays`, provide an accessor `function` for accessing `array` values. ``` javascript var k = [ [0,2], [1,4], [2,8], [3,16] ]; function getValue( d, i ) { return d[ 1 ]; } var out = ekurtosis( k, { 'accessor': getValue }); // returns [ ~6.000, ~3.000, ~1.500, ~0.750 ] ``` To [deepset](https://github.com/kgryte/utils-deep-set) an object `array`, provide a key path and, optionally, a key path separator. ``` javascript var k = [ {'x':[9,2]}, {'x':[9,4]}, {'x':[9,8]}, {'x':[9,16]} ]; var out = ekurtosis( k, 'x|1', '|' ); /* [ {'x':[9,~6.000]}, {'x':[9,~3.000]}, {'x':[9,~1.500]}, {'x':[9,~0.750]}, ] */ var bool = ( data === out ); // returns true ``` By default, when provided a [`typed array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays) or [`matrix`](https://github.com/dstructs/matrix), the output data structure is `float64` in order to preserve precision. To specify a different data type, set the `dtype` option (see [`matrix`](https://github.com/dstructs/matrix) for a list of acceptable data types). ``` javascript var k, out; k = new Float64Array( [ 2,4,8,16 ] ); out = ekurtosis( k, { 'dtype': 'int32' }); // returns Int32Array( [ 6,3,1,0 ] ) // Works for plain arrays, as well... out = ekurtosis( [2,4,8,16], { 'dtype': 'int32' }); // returns Int32Array( [ 6,3,1,0 ] ) ``` By default, the function returns a new data structure. To mutate the input data structure (e.g., when input values can be discarded or when optimizing memory usage), set the `copy` option to `false`. ``` javascript var k, bool, mat, out, i; k = [ 2, 4, 8, 16 ]; out = ekurtosis( k, { 'copy': false }); // returns [ ~6.000, ~3.000, ~1.500, ~0.750 ] bool = ( data === out ); // returns true mat = matrix( [ 2, 4, 8, 16 ], [2,2] ); /* [ 2 4, 8 16 ] */ out = ekurtosis( mat, { 'copy': false }); /* [ ~6.000 ~3.000, ~1.500 ~0.750 ] */ bool = ( mat === out ); // returns true ``` ## Notes * If an element is __not__ a positive number, the [excess kurtosis](https://en.wikipedia.org/wiki/Kurtosis) is `NaN`. ``` javascript var k, out; out = ekurtosis( -1 ); // returns NaN out = ekurtosis( 0 ); // returns NaN out = ekurtosis( null ); // returns NaN out = ekurtosis( true ); // returns NaN out = ekurtosis( {'a':'b'} ); // returns NaN out = ekurtosis( [ true, null, [] ] ); // returns [ NaN, NaN, NaN ] function getValue( d, i ) { return d.x; } k = [ {'x':true}, {'x':[]}, {'x':{}}, {'x':null} ]; out = ekurtosis( k, { 'accessor': getValue }); // returns [ NaN, NaN, NaN, NaN ] out = ekurtosis( k, { 'path': 'x' }); /* [ {'x':NaN}, {'x':NaN}, {'x':NaN, {'x':NaN} ] */ ``` * Be careful when providing a data structure which contains non-numeric elements and specifying an `integer` output data type, as `NaN` values are cast to `0`. ``` javascript var out = ekurtosis( [ true, null, [] ], { 'dtype': 'int8' }); // returns Int8Array( [0,0,0] ); ``` ## Examples ``` javascript var matrix = require( 'dstructs-matrix' ), ekurtosis = require( 'distributions-chisquare-ekurtosis' ); var k, mat, out, tmp, i; // Plain arrays... k = new Array( 10 ); for ( i = 0; i < k.length; i++ ) { k[ i ] = i; } out = ekurtosis( k ); // Object arrays (accessors)... function getValue( d ) { return d.x; } for ( i = 0; i < k.length; i++ ) { k[ i ] = { 'x': k[ i ] }; } out = ekurtosis( k, { 'accessor': getValue }); // Deep set arrays... for ( i = 0; i < k.length; i++ ) { k[ i ] = { 'x': [ i, k[ i ].x ] }; } out = ekurtosis( k, { 'path': 'x/1', 'sep': '/' }); // Typed arrays... k = new Float64Array( 10 ); for ( i = 0; i < k.length; i++ ) { k[ i ] = i; } out = ekurtosis( k ); // Matrices... mat = matrix( k, [5,2], 'float64' ); out = ekurtosis( mat ); // Matrices (custom output data type)... out = ekurtosis( mat, { 'dtype': 'uint8' }); ``` To run the example code from the top-level application directory, ``` bash $ node ./examples/index.js ``` ## Tests ### Unit Unit tests use the [Mocha](http://mochajs.org) test framework with [Chai](http://chaijs.com) assertions. To run the tests, execute the following command in the top-level application directory: ``` bash $ make test ``` All new feature development should have corresponding unit tests to validate correct functionality. ### Test Coverage This repository uses [Istanbul](https://github.com/gotwarlost/istanbul) as its code coverage tool. To generate a test coverage report, execute the following command in the top-level application directory: ``` bash $ make test-cov ``` Istanbul creates a `./reports/coverage` directory. To access an HTML version of the report, ``` bash $ make view-cov ``` --- ## License [MIT license](http://opensource.org/licenses/MIT). ## Copyright Copyright &copy; 2015. The [Compute.io](https://github.com/compute-io) Authors. [npm-image]: http://img.shields.io/npm/v/distributions-chisquare-ekurtosis.svg [npm-url]: https://npmjs.org/package/distributions-chisquare-ekurtosis [travis-image]: http://img.shields.io/travis/distributions-io/chisquare-ekurtosis/master.svg [travis-url]: https://travis-ci.org/distributions-io/chisquare-ekurtosis [codecov-image]: https://img.shields.io/codecov/c/github/distributions-io/chisquare-ekurtosis/master.svg [codecov-url]: https://codecov.io/github/distributions-io/chisquare-ekurtosis?branch=master [dependencies-image]: http://img.shields.io/david/distributions-io/chisquare-ekurtosis.svg [dependencies-url]: https://david-dm.org/distributions-io/chisquare-ekurtosis [dev-dependencies-image]: http://img.shields.io/david/dev/distributions-io/chisquare-ekurtosis.svg [dev-dependencies-url]: https://david-dm.org/dev/distributions-io/chisquare-ekurtosis [github-issues-image]: http://img.shields.io/github/issues/distributions-io/chisquare-ekurtosis.svg [github-issues-url]: https://github.com/distributions-io/chisquare-ekurtosis/issues
distributions-io/chisquare-ekurtosis
README.md
Markdown
mit
8,798
using System.Collections.Generic; using NUnit.Framework; namespace RetailStore.Tests { public class SellMultipleProductsTests { private Screen m_Screen; private RetailStore m_RetailStore; [SetUp] public void SetUp() { var inventory = new Inventory(new Dictionary<string, Product> { { "1", new Product(8.50m) }, { "2", new Product(12.36m) }, { "3", new Product(65.13m) }, }); m_Screen = new Screen(); m_RetailStore = new RetailStore(m_Screen, inventory); } [Test] public void AllProductsFound() { m_RetailStore.OnBarcode("1"); m_RetailStore.OnBarcode("2"); m_RetailStore.OnBarcode("3"); m_RetailStore.OnTotal(); Assert.That(m_Screen.Text, Is.EqualTo("Total: $85.99")); } [Test] public void AllProductsFound_SecondSale() { m_RetailStore.OnBarcode("1"); m_RetailStore.OnTotal(); m_RetailStore.OnBarcode("1"); m_RetailStore.OnBarcode("2"); m_RetailStore.OnTotal(); Assert.That(m_Screen.Text, Is.EqualTo("Total: $20.86")); } [Test] public void SomeProductsNotFound() { m_RetailStore.OnBarcode("1"); m_RetailStore.OnBarcode("2-NotFound"); m_RetailStore.OnBarcode("3"); m_RetailStore.OnTotal(); Assert.That(m_Screen.Text, Is.EqualTo("Total: $73.63")); } [Test] public void NoProductsFound() { m_RetailStore.OnBarcode("1-NotFound"); m_RetailStore.OnBarcode("2-NotFound"); m_RetailStore.OnBarcode("3-NotFound"); m_RetailStore.OnTotal(); Assert.That(m_Screen.Text, Is.EqualTo("Total: $0")); } [Test] public void NoSaleInProgress() { m_RetailStore.OnTotal(); Assert.That(m_Screen.Text, Is.EqualTo("No sale in progress. Please try scanning a product.")); } [Test] public void NoSaleInProgress_SecondSale() { m_RetailStore.OnBarcode("1"); m_RetailStore.OnTotal(); m_RetailStore.OnTotal(); Assert.That(m_Screen.Text, Is.EqualTo("No sale in progress. Please try scanning a product.")); } } }
angellaa/RetailStoreSpike
RetailStore/RetailStore.Tests/SellMultipleProductsTests.cs
C#
mit
2,480
<!DOCTYPE html> <html lang="en"> {% include head.html %} <body> <div class="container content"> <header class="masthead"> <h3 class="masthead-title"> <a href="{{ site.baseurl }}/" title="Home">{{ site.title }}</a><br /> <small>{{ site.tagline }}</small> </h3> </header> <main> {{ content }} </main> <footer class="footer"> <small> &copy; <time datetime="{{ site.time | date_to_xmlschema }}">{{ site.time | date: '%Y' }}</time>. All rights reserved. </small> </footer> </div> </body> </html>
izak/izak.github.io
_layouts/default.html
HTML
mit
617
require "language_pack" require "language_pack/rails2" # Rails 3 Language Pack. This is for all Rails 3.x apps. class LanguagePack::Rails3 < LanguagePack::Rails2 # detects if this is a Rails 3.x app # @return [Boolean] true if it's a Rails 3.x app def self.use? if gemfile_lock? rails_version = LanguagePack::Ruby.gem_version('railties') rails_version >= Gem::Version.new('3.0.0') && rails_version < Gem::Version.new('4.0.0') if rails_version end end def name "Ruby/Rails" end def default_process_types # let's special case thin here web_process = gem_is_bundled?("thin") ? "bundle exec thin start -R config.ru -e $RAILS_ENV -p $PORT" : "bundle exec rails server -p $PORT" super.merge({ "web" => web_process, "console" => "bundle exec rails console" }) end private def plugins super.concat(%w( rails3_serve_static_assets )).uniq end # runs the tasks for the Rails 3.1 asset pipeline def run_assets_precompile_rake_task log("assets_precompile") do setup_database_url_env if rake_task_defined?("assets:precompile") topic("Preparing app for Rails asset pipeline") if File.exists?("public/assets/manifest.yml") puts "Detected manifest.yml, assuming assets were compiled locally" elsif ENV["ASSETS_PRECOMPILED"].present? puts "ASSETS_PRECOMPILED environment variable set, skipping precompilation" else ENV["RAILS_GROUPS"] ||= "assets" ENV["RAILS_ENV"] ||= "production" puts "Running: rake assets:precompile" require 'benchmark' time = Benchmark.realtime { pipe("env PATH=$PATH:bin bundle exec rake assets:precompile 2>&1") } if $?.success? log "assets_precompile", :status => "success" puts "Asset precompilation completed (#{"%.2f" % time}s)" else log "assets_precompile", :status => "failure" puts "Precompiling assets failed, enabling runtime asset compilation" install_plugin("rails31_enable_runtime_asset_compilation") puts "Please see this article for troubleshooting help:" puts "http://devcenter.heroku.com/articles/rails31_heroku_cedar#troubleshooting" end end end end end # setup the database url as an environment variable def setup_database_url_env ENV["DATABASE_URL"] ||= begin # need to use a dummy DATABASE_URL here, so rails can load the environment scheme = if gem_is_bundled?("pg") "postgres" elsif gem_is_bundled?("mysql") "mysql" elsif gem_is_bundled?("mysql2") "mysql2" elsif gem_is_bundled?("sqlite3") || gem_is_bundled?("sqlite3-ruby") "sqlite3" end "#{scheme}://user:[email protected]/dbname" end end end
lemurheavy/heroku-buildpack-ruby
lib/language_pack/rails3.rb
Ruby
mit
2,919
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Archives: 2021 | Hexo</title> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta property="og:type" content="website"> <meta property="og:title" content="Hexo"> <meta property="og:url" content="http://example.com/archives/2021/index.html"> <meta property="og:site_name" content="Hexo"> <meta property="og:locale" content="en_US"> <meta property="article:author" content="John Doe"> <meta name="twitter:card" content="summary"> <link rel="alternate" href="/atom.xml" title="Hexo" type="application/atom+xml"> <link rel="shortcut icon" href="/favicon.png"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/index.min.css"> <link rel="stylesheet" href="/css/style.css"> <link rel="stylesheet" href="/fancybox/jquery.fancybox.min.css"> <meta name="generator" content="Hexo 5.4.0"></head> <body> <div id="container"> <div id="wrap"> <header id="header"> <div id="banner"></div> <div id="header-outer" class="outer"> <div id="header-title" class="inner"> <h1 id="logo-wrap"> <a href="/" id="logo">Hexo</a> </h1> </div> <div id="header-inner" class="inner"> <nav id="main-nav"> <a id="main-nav-toggle" class="nav-icon"></a> <a class="main-nav-link" href="/">Home</a> <a class="main-nav-link" href="/archives">Archives</a> </nav> <nav id="sub-nav"> <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed"></a> <a id="nav-search-btn" class="nav-icon" title="Search"></a> </nav> <div id="search-form-wrap"> <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://example.com"></form> </div> </div> </div> </header> <div class="outer"> <section id="main"> <section class="archives-wrap"> <div class="archive-year-wrap"> <a href="/archives/2021" class="archive-year">2021</a> </div> <div class="archives"> <article class="archive-article archive-type-post"> <div class="archive-article-inner"> <header class="archive-article-header"> <a href="/2021/06/25/hello-world/" class="archive-article-date"> <time class="dt-published" datetime="2021-06-25T02:21:10.213Z" itemprop="datePublished">Jun 25</time> </a> <h1 itemprop="name"> <a class="archive-article-title" href="/2021/06/25/hello-world/">Hello World</a> </h1> </header> </div> </article> </div></section> </section> <aside id="sidebar"> <div class="widget-wrap"> <h3 class="widget-title">Archives</h3> <div class="widget"> <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/06/">June 2021</a></li></ul> </div> </div> <div class="widget-wrap"> <h3 class="widget-title">Recent Posts</h3> <div class="widget"> <ul> <li> <a href="/2021/06/25/hello-world/">Hello World</a> </li> </ul> </div> </div> </aside> </div> <footer id="footer"> <div class="outer"> <div id="footer-info" class="inner"> &copy; 2021 John Doe<br> Powered by <a href="https://hexo.io/" target="_blank">Hexo</a> </div> </div> </footer> </div> <nav id="mobile-nav"> <a href="/" class="mobile-nav-link">Home</a> <a href="/archives" class="mobile-nav-link">Archives</a> </nav> <script src="/js/jquery-3.4.1.min.js"></script> <script src="/fancybox/jquery.fancybox.min.js"></script> <script src="/js/script.js"></script> </div> </body> </html>
andytian1991/andytian1991.github.io
archives/2021/index.html
HTML
mit
4,176
import {BaseIfc} from "./BaseIfc" // http://www.buildingsmart-tech.org/ifc/IFC4/final/html/link/ifctext.htm export type IfcText = string
ikeough/IFC-gen
lang/typescript/src/IfcText.g.ts
TypeScript
mit
139
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="ca"> <head> <!-- Generated by javadoc (1.8.0_101) on Tue Nov 07 12:17:34 CET 2017 --> <title>PathCycleCovers</title> <meta name="date" content="2017-11-07"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> <script type="text/javascript" src="../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="PathCycleCovers"; } } catch(err) { } //--> var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/PathCycleCovers.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li><a href="../index-files/index-1.html">Index</a></li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../digraph/Digraph.html" title="class in digraph"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li>Next&nbsp;Class</li> </ul> <ul class="navList"> <li><a href="../index.html?digraph/PathCycleCovers.html" target="_top">Frames</a></li> <li><a href="PathCycleCovers.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">digraph</div> <h2 title="Class PathCycleCovers" class="title">Class PathCycleCovers</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>digraph.PathCycleCovers</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="typeNameLabel">PathCycleCovers</span> extends java.lang.Object</pre> <div class="block">A class for the array that contains the number of path-cycle covers of a digraph for every given number of paths and cycles. Also used to compute the coefficients of the cover polynomial. Two instances of this class are equal if and only if the cover polynomials of the original graphs are equal. Warning: ints used, may overflow for big digraphs (many edges)</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../digraph/PathCycleCovers.html#PathCycleCovers-int:A:A-">PathCycleCovers</a></span>(int[][]&nbsp;coefs)</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../digraph/PathCycleCovers.html#equals-java.lang.Object-">equals</a></span>(java.lang.Object&nbsp;obj)</code>&nbsp;</td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>int[][]</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../digraph/PathCycleCovers.html#getCoefs--">getCoefs</a></span>()</code>&nbsp;</td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code><a href="../digraph/CoverPolynomial.html" title="class in digraph">CoverPolynomial</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../digraph/PathCycleCovers.html#getCoverPolynomial--">getCoverPolynomial</a></span>()</code>&nbsp;</td> </tr> <tr id="i3" class="rowColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../digraph/PathCycleCovers.html#hashCode--">hashCode</a></span>()</code>&nbsp;</td> </tr> <tr id="i4" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../digraph/PathCycleCovers.html#print--">print</a></span>()</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>getClass, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="PathCycleCovers-int:A:A-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>PathCycleCovers</h4> <pre>public&nbsp;PathCycleCovers(int[][]&nbsp;coefs)</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getCoefs--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getCoefs</h4> <pre>public&nbsp;int[][]&nbsp;getCoefs()</pre> </li> </ul> <a name="print--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>print</h4> <pre>public&nbsp;void&nbsp;print()</pre> </li> </ul> <a name="getCoverPolynomial--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getCoverPolynomial</h4> <pre>public&nbsp;<a href="../digraph/CoverPolynomial.html" title="class in digraph">CoverPolynomial</a>&nbsp;getCoverPolynomial()</pre> </li> </ul> <a name="hashCode--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>hashCode</h4> <pre>public&nbsp;int&nbsp;hashCode()</pre> <dl> <dt><span class="overrideSpecifyLabel">Overrides:</span></dt> <dd><code>hashCode</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> </dl> </li> </ul> <a name="equals-java.lang.Object-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>equals</h4> <pre>public&nbsp;boolean&nbsp;equals(java.lang.Object&nbsp;obj)</pre> <dl> <dt><span class="overrideSpecifyLabel">Overrides:</span></dt> <dd><code>equals</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/PathCycleCovers.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li><a href="../index-files/index-1.html">Index</a></li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../digraph/Digraph.html" title="class in digraph"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li>Next&nbsp;Class</li> </ul> <ul class="navList"> <li><a href="../index.html?digraph/PathCycleCovers.html" target="_top">Frames</a></li> <li><a href="PathCycleCovers.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
salvisolamartinell/cover-polynomial
docs/digraph/PathCycleCovers.html
HTML
mit
11,432
require 'test_helper' class Post include CassandraModel::Resource key :title column :title column :body end class Comment include CassandraModel::Resource column :message column :user_id end class ResourceTest < Test::Unit::TestCase should "have columns" do assert Post.columns.include?('title') assert Post.columns.include?('body') end should "have column_family from class name" do assert_equal :Post, Post.column_family end context "new" do setup do @post = Post.new(:title => "Test title") end should "generate key" do assert_equal "Test title", @post.key end context "without attributes" do setup { @post = Post.new } should "have nil attributes" do assert_nil @post.title assert_nil @post.body end end context "with attributes" do setup { @post = Post.new(:title => "Title", :body => "Body") } should "have set attributes" do assert_equal "Title", @post.title assert_equal "Body", @post.body end end context "with invalid attribute" do should "raise NoMethodError" do assert_raises NoMethodError do Post.new(:bogus => "blah") end end end end context "save" do context "when new record" do context "with valid attributes" do setup do @post = Post.new(:title => "Test title", :body => "Test body") end should "return true" do assert @post.save end end end end end
Lytol/cassandra_model
test/resource_test.rb
Ruby
mit
1,612
# reducer注意事项 * state需要深拷贝 ```js let s = JSON.parse(JSON.stringify(state)); ```
lovesora/gitbook-front-end
javascript/redux/usage/reducer.md
Markdown
mit
97
package com.scienjus.smartqq.listener; import com.scienjus.smartqq.model.DiscussMessage; import com.scienjus.smartqq.model.GroupMessage; import com.scienjus.smartqq.model.Message; /** * Smart QQ的监听器 * * @author ScienJus * @author <a href="mailto:[email protected]">Xianguang Zhou</a> * @since 2015/12/18. */ public interface SmartqqListener { /** * 收到私聊消息后的回调 * * @param message * 好友消息 */ void onMessage(Message message); /** * 收到群消息后的回调 * * @param message * 群消息 */ void onGroupMessage(GroupMessage message); /** * 收到讨论组消息后的回调 * * @param message * 讨论组消息 */ void onDiscussMessage(DiscussMessage message); /** * 轮询线程发生异常的回调 * * @param exception 异常 * @param exceptionThreadType 发生异常的线程 */ void onException(Throwable exception, ExceptionThreadType exceptionThreadType); /** * 登录过期的回调 * * @param apiReturnCode API返回码 */ void onLoginExpired(int apiReturnCode); }
Xianguang-Zhou/smartqq-client
src/main/java/com/scienjus/smartqq/listener/SmartqqListener.java
Java
mit
1,125
/// <reference types="body-parser" /> /// <reference types="express" /> import { OptionsJson } from "body-parser"; import { RequestHandler, Router } from "express"; declare namespace convexpress { interface IResponseDefinition { description?: string; schema?: any; headers?: any; examples?: any; } interface IParameter { name: string; description?: string; in: "body" | "path" | "query" | "header"; required?: boolean; type?: string; schema?: any; } interface IConvRoute { path: string; method: string; handler: RequestHandler; parameters?: IParameter[]; middleware?: RequestHandler[]; description?: string; tags?: string[]; responses?: { [statusCode: string]: IResponseDefinition; }; } interface IConvRouter extends Router { convroute: (route: IConvRoute) => this; serveSwagger: () => this; loadFrom: (pattern: string) => this; } interface IOptions { host: string; basePath?: string; info: { title: string; version: string; }; bodyParserOptions?: { limit?: OptionsJson["limit"]; strict?: OptionsJson["strict"]; verify?: OptionsJson["verify"]; }; } } declare function convexpress( options: convexpress.IOptions ): convexpress.IConvRouter; export = convexpress;
staticdeploy/convexpress
src/index.d.ts
TypeScript
mit
1,507
import { urlEscaper, zip, statusMessage } from '../src/util'; describe('test util', () => { describe('test pure functions in util', () => { it('should return escaped https url', () => { const actualUrl = 'https://abcöd%f&/?get=hi'; const expectedUrl = 'abc_d_f___get_hi'; expect(urlEscaper(actualUrl)).toBe(expectedUrl); }); it('should return escaped http url', () => { const actualUrl = 'http://abcöd%f&/?get=hi'; const expectedUrl = 'abc_d_f___get_hi'; expect(urlEscaper(actualUrl)).toBe(expectedUrl); }); it('should zip together two arrays', () => { const input = [[0, 1, 2, 3], [4, 5, 6, 7]]; const expected = [[0, 4], [1, 5], [2, 6], [3, 7]]; expect(zip(input)).toStrictEqual(expected); }); }); describe('test functions with side-effects in util', () => { let stdoutOutput = ''; const stdoutWrite = process.stdout.write; beforeEach(() => { process.stdout.write = (x) => { stdoutOutput += x; }; stdoutOutput = ''; }); afterEach(() => { process.stdout.write = stdoutWrite; }); it('should write success message if no error', () => { const expectedSuccessMessage = 'success'; statusMessage(expectedSuccessMessage, 'error', undefined); expect(stdoutOutput).toBe(expectedSuccessMessage); }); it('should not write a success metric if error is thrown', () => { const expectedErrorMessage = 'error'; expect(() => { statusMessage('success', expectedErrorMessage, 'error'); }).toThrow(new Error(expectedErrorMessage)); expect(stdoutOutput).toBe(''); }); }); });
emazzotta/lighthouse-badges
__tests__/util.js
JavaScript
mit
1,674
/* 'node_modules/normalize.css/normalize.css' */ /* @import 'normalize.css/normalize.css'; */ /* @import 'bower_components/normalize-css/normalize.css'; */ /* @font-face { font-family: 'Material Icons'; font-style: normal; font-weight: 400; src: url(https://example.com/fonts/MaterialIcons-Regular.eot); // For IE6-8 src: local('Material Icons'), local('MaterialIcons-Regular'), url(//example.com/fonts/MaterialIcons-Regular.woff2) format('woff2'), url(/fonts/MaterialIcons-Regular.woff) format('woff'), url(fonts/MaterialIcons-Regular.ttf) format('truetype'); } */
balmjs/balm
test-workspace/src/styles/global/_vendor.css
CSS
mit
589
/* Modernizr 2.7.0 (Custom Build) | MIT & BSD * Build: http://modernizr.com/download/#-fontface-backgroundsize-borderimage-borderradius-boxshadow-flexbox-hsla-multiplebgs-opacity-rgba-textshadow-cssanimations-csscolumns-generatedcontent-cssgradients-cssreflections-csstransforms-csstransforms3d-csstransitions-applicationcache-canvas-canvastext-draganddrop-hashchange-history-audio-video-indexeddb-input-inputtypes-localstorage-postmessage-sessionstorage-websockets-websqldatabase-webworkers-geolocation-inlinesvg-smil-svg-svgclippaths-touch-webgl-shiv-mq-cssclasses-addtest-prefixed-teststyles-testprop-testallprops-hasevent-prefixes-domprefixes-load */ ; window.Modernizr = function (a, b, c) { function D(a) { j.cssText = a } function E(a, b) { return D(n.join(a + ";") + (b || "")) } function F(a, b) { return typeof a === b } function G(a, b) { return!!~("" + a).indexOf(b) } function H(a, b) { for (var d in a) { var e = a[d]; if (!G(e, "-") && j[e] !== c)return b == "pfx" ? e : !0 } return!1 } function I(a, b, d) { for (var e in a) { var f = b[a[e]]; if (f !== c)return d === !1 ? a[e] : F(f, "function") ? f.bind(d || b) : f } return!1 } function J(a, b, c) { var d = a.charAt(0).toUpperCase() + a.slice(1), e = (a + " " + p.join(d + " ") + d).split(" "); return F(b, "string") || F(b, "undefined") ? H(e, b) : (e = (a + " " + q.join(d + " ") + d).split(" "), I(e, b, c)) } function K() { e.input = function (c) { for (var d = 0, e = c.length; d < e; d++)u[c[d]] = c[d]in k; return u.list && (u.list = !!b.createElement("datalist") && !!a.HTMLDataListElement), u }("autocomplete autofocus list placeholder max min multiple pattern required step".split(" ")), e.inputtypes = function (a) { for (var d = 0, e, f, h, i = a.length; d < i; d++)k.setAttribute("type", f = a[d]), e = k.type !== "text", e && (k.value = l, k.style.cssText = "position:absolute;visibility:hidden;", /^range$/.test(f) && k.style.WebkitAppearance !== c ? (g.appendChild(k), h = b.defaultView, e = h.getComputedStyle && h.getComputedStyle(k, null).WebkitAppearance !== "textfield" && k.offsetHeight !== 0, g.removeChild(k)) : /^(search|tel)$/.test(f) || (/^(url|email)$/.test(f) ? e = k.checkValidity && k.checkValidity() === !1 : e = k.value != l)), t[a[d]] = !!e; return t }("search tel url email datetime date month week time datetime-local number range color".split(" ")) } var d = "2.7.0", e = {}, f = !0, g = b.documentElement, h = "modernizr", i = b.createElement(h), j = i.style, k = b.createElement("input"), l = ":)", m = {}.toString, n = " -webkit- -moz- -o- -ms- ".split(" "), o = "Webkit Moz O ms", p = o.split(" "), q = o.toLowerCase().split(" "), r = {svg: "http://www.w3.org/2000/svg"}, s = {}, t = {}, u = {}, v = [], w = v.slice, x, y = function (a, c, d, e) { var f, i, j, k, l = b.createElement("div"), m = b.body, n = m || b.createElement("body"); if (parseInt(d, 10))while (d--)j = b.createElement("div"), j.id = e ? e[d] : h + (d + 1), l.appendChild(j); return f = ["&#173;", '<style id="s', h, '">', a, "</style>"].join(""), l.id = h, (m ? l : n).innerHTML += f, n.appendChild(l), m || (n.style.background = "", n.style.overflow = "hidden", k = g.style.overflow, g.style.overflow = "hidden", g.appendChild(n)), i = c(l, a), m ? l.parentNode.removeChild(l) : (n.parentNode.removeChild(n), g.style.overflow = k), !!i }, z = function (b) { var c = a.matchMedia || a.msMatchMedia; if (c)return c(b).matches; var d; return y("@media " + b + " { #" + h + " { position: absolute; } }", function (b) { d = (a.getComputedStyle ? getComputedStyle(b, null) : b.currentStyle)["position"] == "absolute" }), d }, A = function () { function d(d, e) { e = e || b.createElement(a[d] || "div"), d = "on" + d; var f = d in e; return f || (e.setAttribute || (e = b.createElement("div")), e.setAttribute && e.removeAttribute && (e.setAttribute(d, ""), f = F(e[d], "function"), F(e[d], "undefined") || (e[d] = c), e.removeAttribute(d))), e = null, f } var a = {select: "input", change: "input", submit: "form", reset: "form", error: "img", load: "img", abort: "img"}; return d }(), B = {}.hasOwnProperty, C; !F(B, "undefined") && !F(B.call, "undefined") ? C = function (a, b) { return B.call(a, b) } : C = function (a, b) { return b in a && F(a.constructor.prototype[b], "undefined") }, Function.prototype.bind || (Function.prototype.bind = function (b) { var c = this; if (typeof c != "function")throw new TypeError; var d = w.call(arguments, 1), e = function () { if (this instanceof e) { var a = function () { }; a.prototype = c.prototype; var f = new a, g = c.apply(f, d.concat(w.call(arguments))); return Object(g) === g ? g : f } return c.apply(b, d.concat(w.call(arguments))) }; return e }), s.flexbox = function () { return J("flexWrap") }, s.canvas = function () { var a = b.createElement("canvas"); return!!a.getContext && !!a.getContext("2d") }, s.canvastext = function () { return!!e.canvas && !!F(b.createElement("canvas").getContext("2d").fillText, "function") }, s.webgl = function () { return!!a.WebGLRenderingContext }, s.touch = function () { var c; return"ontouchstart"in a || a.DocumentTouch && b instanceof DocumentTouch ? c = !0 : y(["@media (", n.join("touch-enabled),("), h, ")", "{#modernizr{top:9px;position:absolute}}"].join(""), function (a) { c = a.offsetTop === 9 }), c }, s.geolocation = function () { return"geolocation"in navigator }, s.postmessage = function () { return!!a.postMessage }, s.websqldatabase = function () { return!!a.openDatabase }, s.indexedDB = function () { return!!J("indexedDB", a) }, s.hashchange = function () { return A("hashchange", a) && (b.documentMode === c || b.documentMode > 7) }, s.history = function () { return!!a.history && !!history.pushState }, s.draganddrop = function () { var a = b.createElement("div"); return"draggable"in a || "ondragstart"in a && "ondrop"in a }, s.websockets = function () { return"WebSocket"in a || "MozWebSocket"in a }, s.rgba = function () { return D("background-color:rgba(150,255,150,.5)"), G(j.backgroundColor, "rgba") }, s.hsla = function () { return D("background-color:hsla(120,40%,100%,.5)"), G(j.backgroundColor, "rgba") || G(j.backgroundColor, "hsla") }, s.multiplebgs = function () { return D("background:url(https://),url(https://),red url(https://)"), /(url\s*\(.*?){3}/.test(j.background) }, s.backgroundsize = function () { return J("backgroundSize") }, s.borderimage = function () { return J("borderImage") }, s.borderradius = function () { return J("borderRadius") }, s.boxshadow = function () { return J("boxShadow") }, s.textshadow = function () { return b.createElement("div").style.textShadow === "" }, s.opacity = function () { return E("opacity:.55"), /^0.55$/.test(j.opacity) }, s.cssanimations = function () { return J("animationName") }, s.csscolumns = function () { return J("columnCount") }, s.cssgradients = function () { var a = "background-image:", b = "gradient(linear,left top,right bottom,from(#9f9),to(white));", c = "linear-gradient(left top,#9f9, white);"; return D((a + "-webkit- ".split(" ").join(b + a) + n.join(c + a)).slice(0, -a.length)), G(j.backgroundImage, "gradient") }, s.cssreflections = function () { return J("boxReflect") }, s.csstransforms = function () { return!!J("transform") }, s.csstransforms3d = function () { var a = !!J("perspective"); return a && "webkitPerspective"in g.style && y("@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}", function (b, c) { a = b.offsetLeft === 9 && b.offsetHeight === 3 }), a }, s.csstransitions = function () { return J("transition") }, s.fontface = function () { var a; return y('@font-face {font-family:"font";src:url("https://")}', function (c, d) { var e = b.getElementById("smodernizr"), f = e.sheet || e.styleSheet, g = f ? f.cssRules && f.cssRules[0] ? f.cssRules[0].cssText : f.cssText || "" : ""; a = /src/i.test(g) && g.indexOf(d.split(" ")[0]) === 0 }), a }, s.generatedcontent = function () { var a; return y(["#", h, "{font:0/0 a}#", h, ':after{content:"', l, '";visibility:hidden;font:3px/1 a}'].join(""), function (b) { a = b.offsetHeight >= 3 }), a }, s.video = function () { var a = b.createElement("video"), c = !1; try { if (c = !!a.canPlayType)c = new Boolean(c), c.ogg = a.canPlayType('video/ogg; codecs="theora"').replace(/^no$/, ""), c.h264 = a.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/, ""), c.webm = a.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/, "") } catch (d) { } return c }, s.audio = function () { var a = b.createElement("audio"), c = !1; try { if (c = !!a.canPlayType)c = new Boolean(c), c.ogg = a.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ""), c.mp3 = a.canPlayType("audio/mpeg;").replace(/^no$/, ""), c.wav = a.canPlayType('audio/wav; codecs="1"').replace(/^no$/, ""), c.m4a = (a.canPlayType("audio/x-m4a;") || a.canPlayType("audio/aac;")).replace(/^no$/, "") } catch (d) { } return c }, s.localstorage = function () { try { return localStorage.setItem(h, h), localStorage.removeItem(h), !0 } catch (a) { return!1 } }, s.sessionstorage = function () { try { return sessionStorage.setItem(h, h), sessionStorage.removeItem(h), !0 } catch (a) { return!1 } }, s.webworkers = function () { return!!a.Worker }, s.applicationcache = function () { return!!a.applicationCache }, s.svg = function () { return!!b.createElementNS && !!b.createElementNS(r.svg, "svg").createSVGRect }, s.inlinesvg = function () { var a = b.createElement("div"); return a.innerHTML = "<svg/>", (a.firstChild && a.firstChild.namespaceURI) == r.svg }, s.smil = function () { return!!b.createElementNS && /SVGAnimate/.test(m.call(b.createElementNS(r.svg, "animate"))) }, s.svgclippaths = function () { return!!b.createElementNS && /SVGClipPath/.test(m.call(b.createElementNS(r.svg, "clipPath"))) }; for (var L in s)C(s, L) && (x = L.toLowerCase(), e[x] = s[L](), v.push((e[x] ? "" : "no-") + x)); return e.input || K(), e.addTest = function (a, b) { if (typeof a == "object")for (var d in a)C(a, d) && e.addTest(d, a[d]); else { a = a.toLowerCase(); if (e[a] !== c)return e; b = typeof b == "function" ? b() : b, typeof f != "undefined" && f && (g.className += " " + (b ? "" : "no-") + a), e[a] = b } return e }, D(""), i = k = null, function (a, b) { function l(a, b) { var c = a.createElement("p"), d = a.getElementsByTagName("head")[0] || a.documentElement; return c.innerHTML = "x<style>" + b + "</style>", d.insertBefore(c.lastChild, d.firstChild) } function m() { var a = s.elements; return typeof a == "string" ? a.split(" ") : a } function n(a) { var b = j[a[h]]; return b || (b = {}, i++, a[h] = i, j[i] = b), b } function o(a, c, d) { c || (c = b); if (k)return c.createElement(a); d || (d = n(c)); var g; return d.cache[a] ? g = d.cache[a].cloneNode() : f.test(a) ? g = (d.cache[a] = d.createElem(a)).cloneNode() : g = d.createElem(a), g.canHaveChildren && !e.test(a) && !g.tagUrn ? d.frag.appendChild(g) : g } function p(a, c) { a || (a = b); if (k)return a.createDocumentFragment(); c = c || n(a); var d = c.frag.cloneNode(), e = 0, f = m(), g = f.length; for (; e < g; e++)d.createElement(f[e]); return d } function q(a, b) { b.cache || (b.cache = {}, b.createElem = a.createElement, b.createFrag = a.createDocumentFragment, b.frag = b.createFrag()), a.createElement = function (c) { return s.shivMethods ? o(c, a, b) : b.createElem(c) }, a.createDocumentFragment = Function("h,f", "return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&(" + m().join().replace(/[\w\-]+/g, function (a) { return b.createElem(a), b.frag.createElement(a), 'c("' + a + '")' }) + ");return n}")(s, b.frag) } function r(a) { a || (a = b); var c = n(a); return s.shivCSS && !g && !c.hasCSS && (c.hasCSS = !!l(a, "article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")), k || q(a, c), a } var c = "3.7.0", d = a.html5 || {}, e = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i, f = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i, g, h = "_html5shiv", i = 0, j = {}, k; (function () { try { var a = b.createElement("a"); a.innerHTML = "<xyz></xyz>", g = "hidden"in a, k = a.childNodes.length == 1 || function () { b.createElement("a"); var a = b.createDocumentFragment(); return typeof a.cloneNode == "undefined" || typeof a.createDocumentFragment == "undefined" || typeof a.createElement == "undefined" }() } catch (c) { g = !0, k = !0 } })(); var s = {elements: d.elements || "abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output progress section summary template time video", version: c, shivCSS: d.shivCSS !== !1, supportsUnknownElements: k, shivMethods: d.shivMethods !== !1, type: "default", shivDocument: r, createElement: o, createDocumentFragment: p}; a.html5 = s, r(b) }(this, b), e._version = d, e._prefixes = n, e._domPrefixes = q, e._cssomPrefixes = p, e.mq = z, e.hasEvent = A, e.testProp = function (a) { return H([a]) }, e.testAllProps = J, e.testStyles = y, e.prefixed = function (a, b, c) { return b ? J(a, b, c) : J(a, "pfx") }, g.className = g.className.replace(/(^|\s)no-js(\s|$)/, "$1$2") + (f ? " js " + v.join(" ") : ""), e }(this, this.document), function (a, b, c) { function d(a) { return"[object Function]" == o.call(a) } function e(a) { return"string" == typeof a } function f() { } function g(a) { return!a || "loaded" == a || "complete" == a || "uninitialized" == a } function h() { var a = p.shift(); q = 1, a ? a.t ? m(function () { ("c" == a.t ? B.injectCss : B.injectJs)(a.s, 0, a.a, a.x, a.e, 1) }, 0) : (a(), h()) : q = 0 } function i(a, c, d, e, f, i, j) { function k(b) { if (!o && g(l.readyState) && (u.r = o = 1, !q && h(), l.onload = l.onreadystatechange = null, b)) { "img" != a && m(function () { t.removeChild(l) }, 50); for (var d in y[c])y[c].hasOwnProperty(d) && y[c][d].onload() } } var j = j || B.errorTimeout, l = b.createElement(a), o = 0, r = 0, u = {t: d, s: c, e: f, a: i, x: j}; 1 === y[c] && (r = 1, y[c] = []), "object" == a ? l.data = c : (l.src = c, l.type = a), l.width = l.height = "0", l.onerror = l.onload = l.onreadystatechange = function () { k.call(this, r) }, p.splice(e, 0, u), "img" != a && (r || 2 === y[c] ? (t.insertBefore(l, s ? null : n), m(k, j)) : y[c].push(l)) } function j(a, b, c, d, f) { return q = 0, b = b || "j", e(a) ? i("c" == b ? v : u, a, b, this.i++, c, d, f) : (p.splice(this.i++, 0, a), 1 == p.length && h()), this } function k() { var a = B; return a.loader = {load: j, i: 0}, a } var l = b.documentElement, m = a.setTimeout, n = b.getElementsByTagName("script")[0], o = {}.toString, p = [], q = 0, r = "MozAppearance"in l.style, s = r && !!b.createRange().compareNode, t = s ? l : n.parentNode, l = a.opera && "[object Opera]" == o.call(a.opera), l = !!b.attachEvent && !l, u = r ? "object" : l ? "script" : "img", v = l ? "script" : u, w = Array.isArray || function (a) { return"[object Array]" == o.call(a) }, x = [], y = {}, z = {timeout: function (a, b) { return b.length && (a.timeout = b[0]), a }}, A, B; B = function (a) { function b(a) { var a = a.split("!"), b = x.length, c = a.pop(), d = a.length, c = {url: c, origUrl: c, prefixes: a}, e, f, g; for (f = 0; f < d; f++)g = a[f].split("="), (e = z[g.shift()]) && (c = e(c, g)); for (f = 0; f < b; f++)c = x[f](c); return c } function g(a, e, f, g, h) { var i = b(a), j = i.autoCallback; i.url.split(".").pop().split("?").shift(), i.bypass || (e && (e = d(e) ? e : e[a] || e[g] || e[a.split("/").pop().split("?")[0]]), i.instead ? i.instead(a, e, f, g, h) : (y[i.url] ? i.noexec = !0 : y[i.url] = 1, f.load(i.url, i.forceCSS || !i.forceJS && "css" == i.url.split(".").pop().split("?").shift() ? "c" : c, i.noexec, i.attrs, i.timeout), (d(e) || d(j)) && f.load(function () { k(), e && e(i.origUrl, h, g), j && j(i.origUrl, h, g), y[i.url] = 2 }))) } function h(a, b) { function c(a, c) { if (a) { if (e(a))c || (j = function () { var a = [].slice.call(arguments); k.apply(this, a), l() }), g(a, j, b, 0, h); else if (Object(a) === a)for (n in m = function () { var b = 0, c; for (c in a)a.hasOwnProperty(c) && b++; return b }(), a)a.hasOwnProperty(n) && (!c && !--m && (d(j) ? j = function () { var a = [].slice.call(arguments); k.apply(this, a), l() } : j[n] = function (a) { return function () { var b = [].slice.call(arguments); a && a.apply(this, b), l() } }(k[n])), g(a[n], j, b, n, h)) } else!c && l() } var h = !!a.test, i = a.load || a.both, j = a.callback || f, k = j, l = a.complete || f, m, n; c(h ? a.yep : a.nope, !!i), i && c(i) } var i, j, l = this.yepnope.loader; if (e(a))g(a, 0, l, 0); else if (w(a))for (i = 0; i < a.length; i++)j = a[i], e(j) ? g(j, 0, l, 0) : w(j) ? B(j) : Object(j) === j && h(j, l); else Object(a) === a && h(a, l) }, B.addPrefix = function (a, b) { z[a] = b }, B.addFilter = function (a) { x.push(a) }, B.errorTimeout = 1e4, null == b.readyState && b.addEventListener && (b.readyState = "loading", b.addEventListener("DOMContentLoaded", A = function () { b.removeEventListener("DOMContentLoaded", A, 0), b.readyState = "complete" }, 0)), a.yepnope = k(), a.yepnope.executeStack = h, a.yepnope.injectJs = function (a, c, d, e, i, j) { var k = b.createElement("script"), l, o, e = e || B.errorTimeout; k.src = a; for (o in d)k.setAttribute(o, d[o]); c = j ? h : c || f, k.onreadystatechange = k.onload = function () { !l && g(k.readyState) && (l = 1, c(), k.onload = k.onreadystatechange = null) }, m(function () { l || (l = 1, c(1)) }, e), i ? k.onload() : n.parentNode.insertBefore(k, n) }, a.yepnope.injectCss = function (a, c, d, e, g, i) { var e = b.createElement("link"), j, c = i ? h : c || f; e.href = a, e.rel = "stylesheet", e.type = "text/css"; for (j in d)e.setAttribute(j, d[j]); g || (n.parentNode.insertBefore(e, n), m(c, 0)) } }(this, document), Modernizr.load = function () { yepnope.apply(window, [].slice.call(arguments, 0)) };
willhaley/angularPresentation-wcavl
assets/js/vendor/modernizr-2.7.0.min.js
JavaScript
mit
19,638
# This file was automagically generated by mbed.org. For more information, # see http://mbed.org/handbook/Exporting-to-GCC-ARM-Embedded GCC_BIN = OUTPUT_BIN ?= mbed_1768_grove_driver_framework BASE_DIR = ../.. SULI_DIR = $(BASE_DIR)/suli GROVES_DIR = $(BASE_DIR)/grove_drivers RPC_SERVER_DIR = $(BASE_DIR)/grove_rpc_server BUILD_DIR = . OUTPUT = $(BUILD_DIR)/$(OUTPUT_BIN) GROVES ?= grove_example OBJECTS = main.o user_main.o suli2.o rpc_server.o rpc_stream.o rpc_server_registration.o SYS_PATHS = $(BASE_DIR)/mbed/TARGET_LPC1768/TOOLCHAIN_GCC_ARM SYS_OBJECTS = cmsis_nvic.o system_LPC17xx.o board.o retarget.o startup_LPC17xx.o INCLUDE_PATHS = -I. -I$(BASE_DIR) -I$(BASE_DIR)/mbed -I$(BASE_DIR)/mbed/TARGET_LPC1768 -I$(BASE_DIR)/mbed/TARGET_LPC1768/TOOLCHAIN_GCC_ARM -I$(BASE_DIR)/mbed/TARGET_LPC1768/TARGET_NXP -I$(BASE_DIR)/mbed/TARGET_LPC1768/TARGET_NXP/TARGET_LPC176X -I$(BASE_DIR)/mbed/TARGET_LPC1768/TARGET_NXP/TARGET_LPC176X/TARGET_MBED_LPC1768 INCLUDE_PATHS += -I$(SULI_DIR) -I$(RPC_SERVER_DIR) ############################################################################### ### DO NOT CHANGE THE FOLLOWING CONTENT ############################################################################### OBJECTS += $(foreach g,$(GROVES),$(g).o $(g)_class.o $(g)_gen.o) INCLUDE_PATHS += $(foreach g,$(GROVES),-I$(GROVES_DIR)/$(g)) GROVES_DIR_LIST = $(foreach g,$(GROVES),$(GROVES_DIR)/$(g)) LIBRARY_PATHS = -L$(BASE_DIR)/mbed/TARGET_LPC1768/TOOLCHAIN_GCC_ARM LIBRARIES = -lmbed LINKER_SCRIPT = $(BASE_DIR)/mbed/TARGET_LPC1768/TOOLCHAIN_GCC_ARM/LPC1768.ld AS = $(GCC_BIN)arm-none-eabi-as CC = $(GCC_BIN)arm-none-eabi-gcc CPP = $(GCC_BIN)arm-none-eabi-g++ LD = $(GCC_BIN)arm-none-eabi-gcc OBJCOPY = $(GCC_BIN)arm-none-eabi-objcopy OBJDUMP = $(GCC_BIN)arm-none-eabi-objdump SIZE = $(GCC_BIN)arm-none-eabi-size CPU = -mcpu=cortex-m3 -mthumb CC_FLAGS = $(CPU) -c -g -fno-common -fmessage-length=0 -Wall -fno-exceptions -ffunction-sections -fdata-sections -fomit-frame-pointer CC_FLAGS += -MMD -MP CC_SYMBOLS = -DTARGET_LPC1768 -DTARGET_M3 -DTARGET_CORTEX_M -DTARGET_NXP -DTARGET_LPC176X -DTARGET_MBED_LPC1768 -DTOOLCHAIN_GCC_ARM -DTOOLCHAIN_GCC -D__CORTEX_M3 -DARM_MATH_CM3 -DMBED_BUILD_TIMESTAMP=1429796006.34 -D__MBED__=1 LD_FLAGS = $(CPU) -Wl,--gc-sections --specs=nano.specs -u _printf_float -u _scanf_float -Wl,--wrap,main LD_FLAGS += -Wl,-Map=$(OUTPUT).map,--cref LD_SYS_LIBS = -lstdc++ -lsupc++ -lm -lc -lgcc -lnosys ifeq ($(DEBUG), 1) CC_FLAGS += -DDEBUG -O0 else CC_FLAGS += -DNDEBUG -Os endif $(info $(OBJECTS)) $(info $(GROVES_DIR_LIST)) VPATH = $(BASE_DIR):$(SULI_DIR):$(RPC_SERVER_DIR):$(BUILD_DIR):$(GROVES_DIR_LIST):$(SYS_PATHS) .PHONY: all clean all: $(OUTPUT).bin $(OUTPUT).hex clean: rm -f $(OUTPUT).bin $(OUTPUT).elf $(OUTPUT).hex $(OUTPUT).map $(OUTPUT).lst $(OBJECTS) $(SYS_OBJECTS) $(DEPS) %.o: %.s $(AS) $(CPU) -o $@ $< %.o: %.c $(CC) $(CC_FLAGS) $(CC_SYMBOLS) -std=gnu99 $(INCLUDE_PATHS) -o $@ $< %.o: %.cpp $(CPP) $(CC_FLAGS) $(CC_SYMBOLS) -std=gnu++98 -fno-rtti $(INCLUDE_PATHS) -o $@ $< $(OUTPUT).elf: $(OBJECTS) $(SYS_OBJECTS) $(LD) $(LD_FLAGS) -T$(LINKER_SCRIPT) $(LIBRARY_PATHS) -o $@ $^ $(LIBRARIES) $(LD_SYS_LIBS) $(LIBRARIES) $(LD_SYS_LIBS) @echo "" @echo "*****" @echo "***** You must modify vector checksum value in *.bin and *.hex files." @echo "*****" @echo "" $(SIZE) $@ $(OUTPUT).bin: $(OUTPUT).elf @$(OBJCOPY) -O binary $< $@ $(OUTPUT).hex: $(OUTPUT).elf @$(OBJCOPY) -O ihex $< $@ $(OUTPUT).lst: $(OUTPUT).elf @$(OBJDUMP) -Sdh $< > $@ lst: $(OUTPUT).lst size: $(SIZE) $(OUTPUT).elf DEPS = $(OBJECTS:.o=.d) $(SYS_OBJECTS:.o=.d) -include $(DEPS)
KillingJacky/grove_driver_framework
users_build_dir/local_user/Makefile
Makefile
mit
3,661
<?php namespace liderDeportivo\ExtranetBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormEvents; use Symfony\Component\Form\FormError; class GruposFilterType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('id', 'filter_number_range') ->add('numeroEquipos', 'filter_number_range') ->add('totalClasificadosAuto', 'filter_number_range') ->add('totalClasificadosManual', 'filter_number_range') ; $listener = function(FormEvent $event) { // Is data empty? foreach ($event->getData() as $data) { if(is_array($data)) { foreach ($data as $subData) { if(!empty($subData)) return; } } else { if(!empty($data)) return; } } $event->getForm()->addError(new FormError('Filter empty')); }; $builder->addEventListener(FormEvents::POST_BIND, $listener); } public function getName() { return 'liderdeportivo_extranetbundle_gruposfiltertype'; } }
ovelasquez/lider
src/liderDeportivo/ExtranetBundle/Form/GruposFilterType.php
PHP
mit
1,410
#!/bin/sh . .lg.rc # nohup xterm -e "npm run start:watch" & nohup xterm -e "npm run test:watch" & code .
abarbanell/limitless-garden
dev.sh
Shell
mit
110
(function(window, document, $, undefined) { "use strict"; $(function() { if ($('#chartjs_line').length) { var ctx = document.getElementById('chartjs_line').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], datasets: [{ label: 'Almonds', data: [12, 19, 3, 17, 6, 3, 7], backgroundColor: "rgba(89, 105, 255,0.5)", borderColor: "rgba(89, 105, 255,0.7)", borderWidth: 2 }, { label: 'Cashew', data: [2, 29, 5, 5, 2, 3, 10], backgroundColor: "rgba(255, 64, 123,0.5)", borderColor: "rgba(255, 64, 123,0.7)", borderWidth: 2 }] }, options: { legend: { display: true, position: 'bottom', labels: { fontColor: '#71748d', fontFamily: 'Circular Std Book', fontSize: 14, } }, scales: { xAxes: [{ ticks: { fontSize: 14, fontFamily: 'Circular Std Book', fontColor: '#71748d', } }], yAxes: [{ ticks: { fontSize: 14, fontFamily: 'Circular Std Book', fontColor: '#71748d', } }] } } }); } if ($('#chartjs_bar').length) { var ctx = document.getElementById("chartjs_bar").getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ["M", "T", "W", "R", "F", "S", "S"], datasets: [{ label: 'Almonds', data: [12, 19, 3, 17, 28, 24, 7], backgroundColor: "rgba(89, 105, 255,0.5)", borderColor: "rgba(89, 105, 255,0.7)", borderWidth: 2 }, { label: 'Cashew', data: [30, 29, 5, 5, 20, 3, 10], backgroundColor: "rgba(255, 64, 123,0.5)", borderColor: "rgba(255, 64, 123,0.7)", borderWidth: 2 }] }, options: { scales: { yAxes: [{ }] }, legend: { display: true, position: 'bottom', labels: { fontColor: '#71748d', fontFamily: 'Circular Std Book', fontSize: 14, } }, scales: { xAxes: [{ ticks: { fontSize: 14, fontFamily: 'Circular Std Book', fontColor: '#71748d', } }], yAxes: [{ ticks: { fontSize: 14, fontFamily: 'Circular Std Book', fontColor: '#71748d', } }] } } }); } if ($('#chartjs_radar').length) { var ctx = document.getElementById("chartjs_radar"); var myChart = new Chart(ctx, { type: 'radar', data: { labels: ["M", "T", "W", "T", "F", "S", "S"], datasets: [{ label: 'Almonds', backgroundColor: "rgba(89, 105, 255,0.5)", borderColor: "rgba(89, 105, 255,0.7)", data: [12, 19, 3, 17, 28, 24, 7], borderWidth: 2 }, { label: 'Cashew', backgroundColor: "rgba(255, 64, 123,0.5)", borderColor: "rgba(255, 64, 123,0.7)", data: [30, 29, 5, 5, 20, 3, 10], borderWidth: 2 }] }, options: { legend: { display: true, position: 'bottom', labels: { fontColor: '#71748d', fontFamily: 'Circular Std Book', fontSize: 14, } }, } }); } if ($('#chartjs_polar').length) { var ctx = document.getElementById("chartjs_polar").getContext('2d'); var myChart = new Chart(ctx, { type: 'polarArea', data: { labels: ["M", "T", "W", "T", "F", "S", "S"], datasets: [{ backgroundColor: [ "#5969ff", "#ff407b", "#25d5f2", "#ffc750", "#2ec551", "#7040fa", "#ff004e" ], data: [12, 19, 3, 17, 28, 24, 7] }] }, options: { legend: { display: true, position: 'bottom', labels: { fontColor: '#71748d', fontFamily: 'Circular Std Book', fontSize: 14, } }, } }); } if ($('#chartjs_pie').length) { var ctx = document.getElementById("chartjs_pie").getContext('2d'); var myChart = new Chart(ctx, { type: 'pie', data: { labels: ["M", "T", "W", "T", "F", "S", "S"], datasets: [{ backgroundColor: [ "#5969ff", "#ff407b", "#25d5f2", "#ffc750", "#2ec551", "#7040fa", "#ff004e" ], data: [12, 19, 3, 17, 28, 24, 7] }] }, options: { legend: { display: true, position: 'bottom', labels: { fontColor: '#71748d', fontFamily: 'Circular Std Book', fontSize: 14, } }, } }); } if ($('#chartjs_doughnut').length) { var ctx = document.getElementById("chartjs_doughnut").getContext('2d'); var myChart = new Chart(ctx, { type: 'doughnut', data: { labels: ["M", "T", "W", "T", "F", "S", "S"], datasets: [{ backgroundColor: [ "#5969ff", "#ff407b", "#25d5f2", "#ffc750", "#2ec551", "#7040fa", "#ff004e" ], data: [12, 19, 3, 17, 28, 24, 7] }] }, options: { legend: { display: true, position: 'bottom', labels: { fontColor: '#71748d', fontFamily: 'Circular Std Book', fontSize: 14, } }, } }); } }); })(window, document, window.jQuery);
freehackquest/backend
web-admin/assets/vendor/charts/charts-bundle/chartjs.js
JavaScript
mit
10,402
from random import randint def testMillerRabin(n, k): """Return False if n is a composite. Return True if n is probably a prime.""" assert n > 3 assert k > 0 d = n - 1 s = 0 while (d % 2 == 0): s += 1 d //= 2 print("n =", n, " => ", n-1,"= 2 **", s, "*", d) for repeat in range(k): print("repeat =", repeat, "/", k) a = randint(2, n-2) x = (a ** d) % n print("a =", a, " x =", x) if x == 1 or x == n - 1: continue nextLoop = False for r in range(1, s): x = (x*x) % n print("r =", r, " x=", x) if x == 1: return False if x == n - 1: nextLoop = True break if nextLoop: continue return False return True testMillerRabin(999999991, 3)
feliposz/project-euler-solutions
python/miller-rabin.py
Python
mit
883
$('#export-entries').click(function() { disableAll(); $.post('/export/start', function(data) { $('#export-progress').html(data.message); var id = data.id; function getStatus() { $.getJSON('/export/status/' + id, function(result) { $('#export-progress').html(result.message); if (result.status == 'finished'){ $('#export-progress').html('Export finished. <a href="/export/download/' + result.filename + '">Download ' + result.filename + '</a>'); $('#delete-message').show(); enableAll(); } else if (result.status == 'failed') { $('#export-progress').css('color', 'red').html(result.message); enableAll(); } else { setTimeout(getStatus, 1000); } }); } getStatus(); }); }); function disableAll() { $('input, button, select').attr('disabled', 'disabled'); } function enableAll() { $('input, button, select').removeAttr('disabled'); $('#import-form').get(0).reset(); $('#upload').attr('disabled', 'disabled'); } function uploadFile(e) { e.preventDefault(); var name = $('#zip').val(); disableAll(); var xhr = new XMLHttpRequest(); var data = new FormData(); data.append("zip", document.getElementById('zip').files[0]); /* event listners */ xhr.upload.addEventListener("progress", uploadProgress, false); xhr.addEventListener("load", uploadComplete, false); xhr.addEventListener("error", uploadFailed, false); xhr.addEventListener("abort", uploadCanceled, false); url = $('#upload').data('upload-url'); xhr.open("POST", url); xhr.send(data); } function uploadProgress(e) { if (e.lengthComputable) { var percentComplete = Math.round(e.loaded * 100 / e.total); $('#import-progress').html('Uploaded ' + percentComplete.toString() + '% of zip file'); } else { $('#import-progress').html('Unable to calculate progress'); } } function uploadComplete(e) { var result = $.parseJSON(e.target.responseText); $('#import-progress').html(result.message); var taskId = result.id; var interval = 1000; function getStatus() { $.getJSON('/import/status/' + taskId, function(data) { if (data.status == 'failed') { $('#import-progress').css('color', 'red').html(data.message); enableAll(); } else if (data.status == 'inprogress') { $('#import-progress').html(data.message); setTimeout(getStatus, interval); } else if (data.status == 'finished') { $('#import-progress').html(data.message); enableAll(); } else if (data.status == 'new') { $('#import-progress').html('Waiting for import to start...'); setTimeout(getStatus, interval); } }); } getStatus(); } function uploadFailed(e) { $('#import-progress').css('color', 'red').html('Upload failed!') } function uploadCanceled(e) { $('#import-progress').css('color', 'red').html('Upload cancelled!') } $('#upload').click(uploadFile); $('#zip').change(function() { var name = $(this).val(); if (name && name.match(/\.zip$/i)) { $('#upload').removeAttr('disabled'); $('#import-progress').css('color', 'black').html('Ready to start import'); } else { $('#upload').attr('disabled', 'disabled'); $('#import-progress').css('color', 'red').html('You can only upload .zip files'); } }); // Migration of images to Google Cloud Storage function migrateToGcs() { disableAll(); $.post('/migrate/start', function(data) { $('#migrate-progress').html(data.message); var id = data.id; function getStatus() { $.getJSON('/migrate/status/' + id, function(result) { if (result.status == 'finished'){ $('#migrate-progress').html(result.message); enableAll(); $('#migrate-to-gcs').attr('disabled', 'disabled'); } else if (result.status == 'failed') { $('#migrate-progress').css('color', 'red').html(result.message); enableAll(); } else { if (result.message) { $('#migrate-progress').html(result.message); } setTimeout(getStatus, 1000); } }); } getStatus(); }); } $('#migrate-to-gcs').click(migrateToGcs);
einaregilsson/MyLife
js/settings.js
JavaScript
mit
4,063
angular.module('app.controllers', ['ngCordova', 'ionic']) .controller('alertCtrl', ['$scope', '$cordovaDialogs', function ($scope, $cordovaDialogs) { $cordovaDialogs.alert('Mensaje del alerta', 'Alerta', 'Aceptar') .then(function() { console.log('Alert ok'); }); }]) .controller('confirmCtrl', ['$scope', '$cordovaDialogs', function ($scope, $cordovaDialogs) { $cordovaDialogs.confirm('Mensaje del confirm', 'Confirm', ['Cancelar','Aceptar']) .then(function(buttonIndex) { // no button = 0, 'OK' = 1, 'Cancel' = 2 var btnIndex = buttonIndex; console.log(btnIndex); }); }]) .controller('promptCtrl', ['$scope', '$cordovaDialogs', function ($scope, $cordovaDialogs) { $cordovaDialogs.prompt('Mensaje para el prompt', 'Prompt', ['Uso 1','Uso 2'], 'Escriba aquí') .then(function(result) { var input = result.input1; // no button = 0, 'OK' = 1, 'Cancel' = 2 var btnIndex = result.buttonIndex; console.log(input, btnIndex); }); }]);
alejo8591/unipiloto-apm-4
modules/module_8/lab4/www/js/controllers.js
JavaScript
mit
1,010
require 'spec_helper' include EventHelper include LocalTimeHelper describe 'events/show', type: :view do before(:each) do @event = FactoryGirl.build_stubbed(Event, name: 'EuroAsia Scrum', category: 'Scrum', description: 'EuroAsia Scrum and Pair hookup http://lin.ky/', time_zone: 'Eastern Time (US & Canada)', project_id: 1) allow(Time).to receive(:now).and_return(Time.parse('2014-03-07 23:30:00 UTC')) @event_schedule = @event.next_occurrences(end_time: Time.now + 40.days) render end it 'should display event information' do expect(rendered).to have_text('EuroAsia Scrum') expect(rendered).to have_text('EuroAsia Scrum and Pair hookup') end it 'should render the event name' do expect(rendered).to have_text(@event.name) end it 'should render the event description, with links hyperlinked' do expect(rendered).to have_link('http://lin.ky') expect(rendered).to have_content('EuroAsia Scrum and Pair hookup http://lin.ky') end describe 'Hangouts' do before(:each) do @recent_hangout = FactoryGirl.build_stubbed(:event_instance, uid: '123456', event_id: 375, category: 'Scrum', hangout_url: 'http://hangout.test', updated: Time.parse('10:25:00 UTC')) allow(@recent_hangout).to receive(:started?).and_return false allow(@recent_hangout).to receive(:live?).and_return false allow(view).to receive(:generate_event_instance_id).and_return('123456') @event.url = @recent_hangout.hangout_url end context 'hangout is live' do before :each do allow(@recent_hangout).to receive(:started?).and_return(true) allow(@recent_hangout).to receive(:live?).and_return(true) end it 'renders Join link if hangout is live' do render expect(rendered).to have_link('Join now', href: 'http://hangout.test') end end context 'for signed in users' do before do allow(view).to receive(:user_signed_in?).and_return(true) allow(Time).to receive(:now).and_return(Time.parse('2014-03-09 23:30:00 UTC')) end it_behaves_like 'it has a hangout button' do let(:title) { 'EuroAsia Scrum' } let(:project_id) { @event.project_id } let(:event_id) { @event.id } let(:category) { @event.category } let(:event_instance_id) { @recent_hangout.uid } end end end end
SergiosLen/WebsiteOne
spec/views/events/show.html.erb_spec.rb
Ruby
mit
2,784
<!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8"> <!-- Bot & SEO --> <meta name="Generator" content="OpenLibrerian"> <meta name="robots" content="<?php echo $robotsInstruction ?>"> <meta name="author" content="<?php echo PREFIX_ABSOLUTE_LINK; ?>humans.txt"> <meta name="designer" content="Ajabep"> <meta name="owner" content="Ajabep"> <?php if($this->name=='index'){ echo '<meta name="identifier-URL" content="'.PREFIX_ABSOLUTE_LINK.'">';} ?> <meta name="coverage" content="Worldwide"> <meta name="distribution" content="Global"> <meta name="rating" content="General"> <title><?php if( $this->name == 'index' ) { echo 'Objects list - '; } elseif( $this->name == 'tags' ) { echo 'Tag list - '; } elseif( $this->name == 'object' ) { echo $object->name() . ' - '; switch($this->get['edit']){ case 'edit': case 'delete': echo $this->get['edit']; break; default : echo 'details'; } echo ' - '; } elseif( $this->name == 'tag' ) { echo $tag->name() . ' - '; switch($this->get['edit']) { case 'delete': echo $this->get['edit']; break; default : echo 'details'; } echo ' - '; } elseif( $this->name == 'about' ) { echo 'About - '; } elseif( $this->name == 'admin' ) { echo 'Admin space - '; } ?>OpenLibrerian</title> <!-- /Bot & SEO --> <!-- mobile --> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="HandheldFriendly" content="true"> <meta name="MobileOptimized" content="width"> <!-- /mobile --> <!-- IE Compatibility --> <!--[if IE]> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <![endif]--> <!--[if IE]> <meta http-equiv="X-UA-Compatible" content="IE=10"> <![endif]--> <!--[if lt IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <!-- /IE Compatibility --> <!-- IE Apps --> <meta name="msapplication-config" content="/IEconfig.xml" /> <meta name="msapplication-navbutton-color" content="#fff"> <meta name="msapplication-TileColor" content="#fff"> <meta name="msapplication-TileImage" content="<?php echo PREFIX_ABSOLUTE_CDN; ?>img/mstile-144x144.1.png"> <meta name="msapplication-square70x70logo" content="<?php echo PREFIX_ABSOLUTE_CDN; ?>img/mstile-70x70.1.png"> <meta name="msapplication-square150x150logo" content="<?php echo PREFIX_ABSOLUTE_CDN; ?>img/mstile-150x150.1.png"> <meta name="msapplication-square310x310logo" content="<?php echo PREFIX_ABSOLUTE_CDN; ?>img/mstile-310x310.1.png"> <meta name="msapplication-square310x150logo" content="<?php echo PREFIX_ABSOLUTE_CDN; ?>img/mstile-310x150.1.png"> <!-- taches --> <meta name="msapplication-task" content="name=Object list; action-uri=<?php echo PREFIX_LINK_LANG; ?>; icon-uri=<?php echo PREFIX_ABSOLUTE_LINK; ?>favicon.ico"> <?php if( $this->name == 'object' ) { echo '<meta name="msapplication-task" content="name=' . $object->name() . '; action-uri=' . PREFIX_LINK_LANG . '/object/' . $object->ID() . '/' . stringToUrl($object->name()) . '; icon-uri=' . PREFIX_ABSOLUTE_LINK . 'favicon.ico">'; } ?> <meta name="msapplication-task" content="name=Tag list; action-uri=<?php echo PREFIX_LINK_LANG; ?>tags/; icon-uri=<?php echo PREFIX_ABSOLUTE_LINK; ?>favicon.ico"> <?php if( $this->name == 'tag' ) { echo '<meta name="msapplication-task" content="name=' . $tag->name() . '; action-uri=' . PREFIX_LINK_LANG . '/tag/' . $tag->ID() . '/' . stringToUrl($tag->name()) . '; icon-uri=' . PREFIX_ABSOLUTE_LINK . 'favicon.ico">'; } ?> <meta name="msapplication-task" content="name=About; action-uri=<?php echo PREFIX_ABSOLUTE_LINK; ?>about/; icon-uri=<?php echo PREFIX_ABSOLUTE_LINK; ?>favicon.ico"> <meta name="msapplication-task" content="name=Admin space; action-uri=<?php echo PREFIX_ABSOLUTE_LINK; ?>admin/; icon-uri=<?php echo PREFIX_ABSOLUTE_LINK; ?>favicon.ico"> <!-- /taches --> <!-- / IE Apps --> <!-- Apple Apps --> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="white-translucent"> <meta name="format-detection" content="telephone=no"> <meta name="apple-mobile-web-app-title" content="<?php echo NAME_OF_THE_SYSTEM; ?>"> <meta name="apple-touch-fullscreen" content="yes"> <!-- / Apple Apps --> <!-- dns-prefetch --> <link rel="dns-prefetch" href="http//code.jquery.com"> <link rel="dns-prefetch" href="http//maxcdn.bootstrapcdn.com"> <link rel="dns-prefetch" href="<?php echo PREFIX_ABSOLUTE_CDN; ?>"> <!-- / dns-prefetch --> <!--[if IE]><link rel="shortcut icon" type="image/x-icon" href="<?php echo PREFIX_LINK; ?>favicon.ico" /><![endif]--> <!-- cf. http://ie.microsoft.com/testdrive/Browser/IconEditor/Default.html --> <link rel="icon" type="image/x-icon" href="<?php echo PREFIX_LINK; ?>favicon.ico"> <link rel="icon" type="image/png" href="<?php echo PREFIX_ABSOLUTE_CDN; ?>img/favicon-16x16.1.png" sizes="16x16"> <link rel="icon" type="image/png" href="<?php echo PREFIX_ABSOLUTE_CDN; ?>img/favicon-32x32.1.png" sizes="32x32"> <link rel="icon" type="image/png" href="<?php echo PREFIX_ABSOLUTE_CDN; ?>img/favicon-96x96.1.png" sizes="96x96"> <link rel="icon" type="image/png" href="<?php echo PREFIX_ABSOLUTE_CDN; ?>img/favicon-160x160.1.png" sizes="160x160"> <link rel="icon" type="image/png" href="<?php echo PREFIX_ABSOLUTE_CDN; ?>img/favicon-196x196.1.png" sizes="196x196"> <link rel="author" type="text/plain" href="<?php echo PREFIX_ABSOLUTE_LINK; ?>humans.txt"> <!-- Apple Apps --> <link rel="apple-touch-icon" sizes="57x57" href="<?php echo PREFIX_ABSOLUTE_CDN; ?>img/apple-touch-icon-57x57.1.png"> <link rel="apple-touch-icon" sizes="114x114" href="<?php echo PREFIX_ABSOLUTE_CDN; ?>img/apple-touch-icon-114x114.1.png"> <link rel="apple-touch-icon" sizes="72x72" href="<?php echo PREFIX_ABSOLUTE_CDN; ?>img/apple-touch-icon-72x72.1.png"> <link rel="apple-touch-icon" sizes="144x144" href="<?php echo PREFIX_ABSOLUTE_CDN; ?>img/apple-touch-icon-144x144.1.png"> <link rel="apple-touch-icon" sizes="60x60" href="<?php echo PREFIX_ABSOLUTE_CDN; ?>img/apple-touch-icon-60x60.1.png"> <link rel="apple-touch-icon" sizes="120x120" href="<?php echo PREFIX_ABSOLUTE_CDN; ?>img/apple-touch-icon-120x120.1.png"> <link rel="apple-touch-icon" sizes="76x76" href="<?php echo PREFIX_ABSOLUTE_CDN; ?>img/apple-touch-icon-76x76.1.png"> <link rel="apple-touch-icon" sizes="152x152" href="<?php echo PREFIX_ABSOLUTE_CDN; ?>img/apple-touch-icon-152x152.1.png"> <!-- / Apple Apps --> <?php if( $this->name == 'index' ) { echo '<link rel="stylesheet" type="text/css" href="' . PREFIX_ABSOLUTE_CDN . 'css/index.2.min.css">'; } elseif( $this->name == 'tags' ) { echo '<link rel="stylesheet" type="text/css" href="' . PREFIX_ABSOLUTE_CDN . 'css/tags.2.min.css">'; } elseif( $this->name == 'object' ) { echo '<link rel="stylesheet" type="text/css" href="' . PREFIX_ABSOLUTE_CDN . 'css/object.2.min.css">'; } elseif( $this->name == 'tag' ) { echo '<link rel="stylesheet" type="text/css" href="' . PREFIX_ABSOLUTE_CDN . 'css/tag.2.min.css">'; } elseif( $this->name == 'about' ) { echo '<link rel="stylesheet" type="text/css" href="' . PREFIX_ABSOLUTE_CDN . 'css/about.2.min.css">'; } elseif( $this->name == 'admin' && !$isAdmin && !empty($_GET['resetPassword']) ) { echo '<link rel="stylesheet" type="text/css" href="' . PREFIX_ABSOLUTE_CDN . 'css/admin.2.min.css">'; } else { echo '<link rel="stylesheet" type="text/css" href="' . PREFIX_ABSOLUTE_CDN . 'css/style.2.min.css">'; } ?> </head> <body role="document" itemscope="itemscope" itemtype="http://schema.org/WebPage">
ajabep/OpenLibrerian
vue/doctype.php
PHP
mit
7,862
--- layout: post title: "Volunteer work" date: 2016-08-17 image: images/nattskiftet.jpg tag: --- Social equality and gender equality is something I'm passionate about, and love to spend some of my free time each month doing something active about. I'm an active volunteer in <a href="https://www.nattskiftet.org/" target="_blank">Nattskiftet</a> (swedish for Nightshift) which is an NGO working for safety and raising awareness about sexual harassment happening in public areas, like nightclubs and music festivals. The method is walking in and in the vicinity of nightclubs and music festivals acting as a sober friend for people who need us. The second NGO is <a href="https://fatta.nu/fatta-man/" target="_blank">Fatta Man</a>,an organization working towards raising awareness about men's sexual violence towards women and non-men. The method is through workshops at schools, information targeting men through social media, a podcast and an online teaching tool in the making.
cc-lemon/cc-lemon.github.io
_posts/2016-08-17-volunteer-work.md
Markdown
mit
990
export { SlidesModule } from './src/slides.module'; export { SlidesListComponent } from './src/containers/slides-list/slides-list.component';
weareopensource/storytelling
Angular/libs/slides/index.ts
TypeScript
mit
142
from django.http import HttpResponseRedirect, HttpResponse from django.template import RequestContext from django.shortcuts import get_object_or_404, render_to_response from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse from django.conf import settings from django.core.paginator import Paginator, InvalidPage, EmptyPage from PIL import Image as PImage from os.path import join as pjoin from .models import Forum, Thread, Post, UserProfile from .forms import ProfileForm from django.utils.encoding import smart_str def main(request): """Main listing.""" context = RequestContext(request) forums = Forum.objects.all() return render_to_response("forum/list.html", dict(forums=forums, user=request.user), context) def mk_paginator(request, items, num_items): """Create and return a paginator.""" paginator = Paginator(items, num_items) try: page = int(request.GET.get("page", '1')) except ValueError: page = 1 try: items = paginator.page(page) except (InvalidPage, EmptyPage): items = paginator.page(paginator.num_pages) return items def forum(request, pk): context = RequestContext(request) """Listing of threads in a forum.""" threads = Thread.objects.filter(forum=pk).order_by("-created") threads = mk_paginator(request, threads, 20) title = Forum.objects.get(pk=pk) context_dict = {'pk':pk, 'threads': threads, 'title': title} return render_to_response("forum/forum.html",context_dict, context) def thread(request, pk): """Listing of posts in a thread.""" context = RequestContext(request) posts = Post.objects.filter(thread=pk).order_by("created") posts = mk_paginator(request, posts, 15) t = Thread.objects.get(pk=pk) title = t.title forum_pk = t.forum.pk context_dict = {'pk':pk, 'posts': posts, 'title': title, 'forum_pk': forum_pk} return render_to_response("forum/thread.html", context_dict, context) def post(request, ptype, pk): """we also need to add a way to post replies and new threads. I'll use the same template for both and call it post.html and the method names will be: post() to show the form and new_thread() and reply() to submit; urls will be: /forum/post/(new_thread|reply)/{id}/ and /forum/new_thread/{id}/ and /forum/reply/{id}/.""" """Display a post form.""" context = RequestContext(request) action = reverse("forum:%s" % ptype, args=[pk]) if ptype == "new_thread": title = "Start New Topic" subject = '' elif ptype == "reply": title = "Reply" subject = "Re: " + Thread.objects.get(pk=pk).title context_dict = {'subject':subject, 'action': action, 'title':title} return render_to_response("forum/post.html", context_dict, context) def reply(request, pk): """Reply to a thread.""" context = RequestContext(request) p = request.POST if p["body"]: thread = Thread.objects.get(pk=pk) Post.objects.create(thread=thread, title=p["subject"], body=p["body"], creator=request.user) increment_post_counter(request) return HttpResponseRedirect(reverse("forum:thread", args=[pk]) + "?page=last") def new_thread(request, pk): """Start a new thread.""" p = request.POST if p["subject"] and p["body"]: forum = Forum.objects.get(pk=pk) thread = Thread.objects.create(forum=forum, title=p["subject"], creator=request.user) Post.objects.create(thread=thread, title=p["subject"], body=p["body"], creator=request.user) increment_post_counter(request) return HttpResponseRedirect(reverse("forum:forum", args=[pk])) @login_required def profile(request, pk): """Edit user profile.""" context = RequestContext(request) profile = UserProfile.objects.get(user=pk) print('profile=', profile) img = None if request.method == "POST": print("request method is post") pf = ProfileForm(request.POST, request.FILES, instance=profile) if pf.is_valid(): print("form is valid") print ("image name=", profile.avatar.name) pf.save() # resize and save image under same filename im_path = pjoin(settings.MEDIA_ROOT, profile.avatar.name) #im_url = profile.avatar.url print('url=', im_path) im = PImage.open(im_path) im.thumbnail((160,160), PImage.ANTIALIAS) #im.save(im_path, "JPEG") im.save(im_path, "JPEG") else: print ("Errors: ", pf.errors) else: pf = ProfileForm(instance=profile) if profile.avatar: print ('profile.avatar=', smart_str(profile.avatar), smart_str(profile.avatar.url)) #img = "/media/" + profile.avatar.name img = profile.avatar.url context_dict = {'pf': pf, 'img': img, 'profile': profile} return render_to_response("forum/profile.html", context_dict, context) def increment_post_counter(request): """We also have to make sure we increment the posts counter every time a user replies or creates a thread:""" profile = request.user.userprofile_set.all()[0] profile.posts += 1 profile.save()
vadosl/forum
forum/apps/forum/views.py
Python
mit
5,258
var Module; if (typeof Module === 'undefined') Module = eval('(function() { try { return Module || {} } catch(e) { return {} } })()'); if (!Module.expectedDataFileDownloads) { Module.expectedDataFileDownloads = 0; Module.finishedDataFileDownloads = 0; } Module.expectedDataFileDownloads++; (function() { var loadPackage = function(metadata) { var PACKAGE_PATH; if (typeof window === 'object') { PACKAGE_PATH = window['encodeURIComponent'](window.location.pathname.toString().substring(0, window.location.pathname.toString().lastIndexOf('/')) + '/'); } else if (typeof location !== 'undefined') { // worker PACKAGE_PATH = encodeURIComponent(location.pathname.toString().substring(0, location.pathname.toString().lastIndexOf('/')) + '/'); } else { throw 'using preloaded data can only be done on a web page or in a web worker'; } var PACKAGE_NAME = 'GitHub.data'; var REMOTE_PACKAGE_BASE = 'GitHub.data'; if (typeof Module['locateFilePackage'] === 'function' && !Module['locateFile']) { Module['locateFile'] = Module['locateFilePackage']; Module.printErr('warning: you defined Module.locateFilePackage, that has been renamed to Module.locateFile (using your locateFilePackage for now)'); } var REMOTE_PACKAGE_NAME = typeof Module['locateFile'] === 'function' ? Module['locateFile'](REMOTE_PACKAGE_BASE) : ((Module['filePackagePrefixURL'] || '') + REMOTE_PACKAGE_BASE); var REMOTE_PACKAGE_SIZE = 18052341; var PACKAGE_UUID = '1075c55d-f753-4160-ac90-c3ff0924688d'; function fetchRemotePackage(packageName, packageSize, callback, errback) { var xhr = new XMLHttpRequest(); xhr.open('GET', packageName, true); xhr.responseType = 'arraybuffer'; xhr.onprogress = function(event) { var url = packageName; var size = packageSize; if (event.total) size = event.total; if (event.loaded) { if (!xhr.addedTotal) { xhr.addedTotal = true; if (!Module.dataFileDownloads) Module.dataFileDownloads = {}; Module.dataFileDownloads[url] = { loaded: event.loaded, total: size }; } else { Module.dataFileDownloads[url].loaded = event.loaded; } var total = 0; var loaded = 0; var num = 0; for (var download in Module.dataFileDownloads) { var data = Module.dataFileDownloads[download]; total += data.total; loaded += data.loaded; num++; } total = Math.ceil(total * Module.expectedDataFileDownloads/num); if (Module['setStatus']) Module['setStatus']('Downloading data... (' + loaded + '/' + total + ')'); } else if (!Module.dataFileDownloads) { if (Module['setStatus']) Module['setStatus']('Downloading data...'); } }; xhr.onload = function(event) { var packageData = xhr.response; callback(packageData); }; xhr.send(null); }; function handleError(error) { console.error('package error:', error); }; var fetched = null, fetchedCallback = null; fetchRemotePackage(REMOTE_PACKAGE_NAME, REMOTE_PACKAGE_SIZE, function(data) { if (fetchedCallback) { fetchedCallback(data); fetchedCallback = null; } else { fetched = data; } }, handleError); function runWithFS() { function assert(check, msg) { if (!check) throw msg + new Error().stack; } Module['FS_createPath']('/', 'Il2CppData', true, true); Module['FS_createPath']('/Il2CppData', 'Metadata', true, true); Module['FS_createPath']('/', 'Resources', true, true); function DataRequest(start, end, crunched, audio) { this.start = start; this.end = end; this.crunched = crunched; this.audio = audio; } DataRequest.prototype = { requests: {}, open: function(mode, name) { this.name = name; this.requests[name] = this; Module['addRunDependency']('fp ' + this.name); }, send: function() {}, onload: function() { var byteArray = this.byteArray.subarray(this.start, this.end); this.finish(byteArray); }, finish: function(byteArray) { var that = this; Module['FS_createPreloadedFile'](this.name, null, byteArray, true, true, function() { Module['removeRunDependency']('fp ' + that.name); }, function() { if (that.audio) { Module['removeRunDependency']('fp ' + that.name); // workaround for chromium bug 124926 (still no audio with this, but at least we don't hang) } else { Module.printErr('Preloading file ' + that.name + ' failed'); } }, false, true); // canOwn this data in the filesystem, it is a slide into the heap that will never change this.requests[this.name] = null; }, }; new DataRequest(0, 36372, 0, 0).open('GET', '/mainData'); new DataRequest(36372, 36393, 0, 0).open('GET', '/methods_pointedto_by_uievents.xml'); new DataRequest(36393, 14059697, 0, 0).open('GET', '/sharedassets0.assets'); new DataRequest(14059697, 15661177, 0, 0).open('GET', '/Il2CppData/Metadata/global-metadata.dat'); new DataRequest(15661177, 17548609, 0, 0).open('GET', '/Resources/unity_default_resources'); new DataRequest(17548609, 18052341, 0, 0).open('GET', '/Resources/unity_builtin_extra'); function processPackageData(arrayBuffer) { Module.finishedDataFileDownloads++; assert(arrayBuffer, 'Loading data file failed.'); var byteArray = new Uint8Array(arrayBuffer); var curr; // Reuse the bytearray from the XHR as the source for file reads. DataRequest.prototype.byteArray = byteArray; DataRequest.prototype.requests["/mainData"].onload(); DataRequest.prototype.requests["/methods_pointedto_by_uievents.xml"].onload(); DataRequest.prototype.requests["/sharedassets0.assets"].onload(); DataRequest.prototype.requests["/Il2CppData/Metadata/global-metadata.dat"].onload(); DataRequest.prototype.requests["/Resources/unity_default_resources"].onload(); DataRequest.prototype.requests["/Resources/unity_builtin_extra"].onload(); Module['removeRunDependency']('datafile_GitHub.data'); }; Module['addRunDependency']('datafile_GitHub.data'); if (!Module.preloadResults) Module.preloadResults = {}; Module.preloadResults[PACKAGE_NAME] = {fromCache: false}; if (fetched) { processPackageData(fetched); fetched = null; } else { fetchedCallback = processPackageData; } } if (Module['calledRun']) { runWithFS(); } else { if (!Module['preRun']) Module['preRun'] = []; Module["preRun"].push(runWithFS); // FS is not initialized yet, wait for it } } loadPackage(); })();
jeannforbes/Slamdroid
Release/fileloader.js
JavaScript
mit
7,080
(function () { 'use strict'; angular.module('component.seed', []); })();
klajd/angular-component-seed
src/module.js
JavaScript
mit
83
'use strict'; // Leagues controller angular.module('leagues').controller('LeaguesController', ['$http', '$resource' , '$scope', '$stateParams', '$location', 'Authentication', 'Leagues', function($http,$resource, $scope, $stateParams, $location, Authentication, Leagues) { $scope.invite = ''; $scope.authentication = Authentication; $scope.listRequests = ''; $scope.spec = function () { var Resource = $resource('/leagues/requests'); Resource.query(function (leagues) { $scope.listRequests = leagues; }); }; $scope.spec(); var placeSearch, autocomplete; if (document.getElementById('address')) { autocomplete = new google.maps.places.Autocomplete( /** @type {HTMLInputElement} */(document.getElementById('address'))); // When the user selects an address from the dropdown, // populate the address fields in the form. google.maps.event.addListener(autocomplete, 'place_changed', function () { $scope.updateAddress(); }); } ; $scope.updateAddress = function () { var place = autocomplete.getPlace(); document.getElementById('address').value = place.formatted_address; if ($scope.league) { $scope.league.ort = place.formatted_address; $scope.league.lat = place.geometry.location.A; $scope.league.lng = place.geometry.location.F; } else { this.address = place.formatted_address; this.lat = place.geometry.location.A; this.lng = place.geometry.location.F; } }; // Create new League $scope.create = function () { // Create new League object var league = new Leagues($scope.league); // Redirect after save league.$save(function (response) { $location.path('leagues/' + response._id); // Clear form fields $scope.name = ''; $scope.sport = ''; }, function (errorResponse) { $scope.error = errorResponse.data.message; }); }; // Remove existing League $scope.remove = function (league) { if (league) { league.$remove(); for (var i in $scope.leagues) { if ($scope.leagues [i] === league) { $scope.leagues.splice(i, 1); } } } else { $scope.league.$remove(function () { $location.path('leagues'); }); } }; $scope.joinLeague = function (league) { $http.get('/leagues/' + league._id + '/join'); location.reload(); }; $scope.leaveLeague = function (league) { var league = $scope.league; $http.get("/leagues/" + league._id + "/leave"); location.reload(); }; $scope.joinStatus = function (leagueid) { var existing = false; if (leagueid.users) { leagueid.users.forEach(function (user) { if ($scope.authentication.user._id == user.user._id) { existing = true; } }); } return existing; }; $scope.declineRequest = function(league){ $http.get("/leagues/" + league._id + "/decline"); location.reload(); } // Update existing League $scope.update = function () { var league = $scope.league; league.$update(function () { $location.path('leagues/' + league._id); }, function (errorResponse) { $scope.error = errorResponse.data.message; }); }; // Find a list of Leagues $scope.find = function () { $scope.leagues = Leagues.query(); }; // Find existing League $scope.findOne = function () { $scope.league = Leagues.get({ leagueId: $stateParams.leagueId }); }; $scope.requestSheduleFormated = function () { if ($scope.league.requestShedule) { if ($scope.league.requestShedule == 'weeklyAll') { return 'Eine zufällige Herausforderung pro Woche'; } else if ($scope.league.requestShedule == 'biweeklyAll') { return 'Eine zufällige Herausforderung jede zweite Woche'; } } else if ($scope.league.requestShedule == 'weeklyTowTop') { return 'Eine Herausforderung gegen einen Mitspieler maximal 2 Plätze besser/schlechter pro Woche'; } else if ($scope.league.requestShedule == 'biweeklyTowTop') { return ' Eine Herausforderung gegen einen Mitspieler maximal 2 Plätze besser/schlechter jede zweite Woche'; } else{ return 'keine' } }; $scope.sendInvite = function(){ var league = $scope.league; $http.post('/leagues/' + league._id + '/invite', {user: $scope.invite}); } } ]);
raphirm/RacketSports
public/modules/leagues/controllers/leagues.client.controller.js
JavaScript
mit
4,242