repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
kindjar/static-data
lib/static-data/version.rb
42
module StaticData VERSION = "0.3.0" end
mit
ignaciocases/hermeneumatics
node_modules/scala-node/main/target/streams/compile/externalDependencyClasspath/$global/package-js/extracted-jars/scalajs-library_2.10-0.4.0.jar--29fb2f8b/scala/xml/dtd/DFAContentModel.js
3141
/** @constructor */ ScalaJS.c.scala_xml_dtd_DFAContentModel = (function() { ScalaJS.c.scala_xml_dtd_ContentModel.call(this); this.dfa$2 = null; this.bitmap$0$2 = false }); ScalaJS.c.scala_xml_dtd_DFAContentModel.prototype = new ScalaJS.inheritable.scala_xml_dtd_ContentModel(); ScalaJS.c.scala_xml_dtd_DFAContentModel.prototype.constructor = ScalaJS.c.scala_xml_dtd_DFAContentModel; ScalaJS.c.scala_xml_dtd_DFAContentModel.prototype.dfa$lzycompute__p2__Lscala_util_automata_DetWordAutom = (function() { if ((!this.bitmap$0$2)) { var nfa = ScalaJS.modules.scala_xml_dtd_ContentModel$Translator().automatonFrom__Lscala_util_regexp_Base$RegExp__I__Lscala_util_automata_NondetWordAutom(this.r__Lscala_util_regexp_Base$RegExp(), 1); var jsx$1 = new ScalaJS.c.scala_util_automata_SubsetConstruction().init___Lscala_util_automata_NondetWordAutom(nfa).determinize__Lscala_util_automata_DetWordAutom(); this.dfa$2 = jsx$1; this.bitmap$0$2 = true }; ScalaJS.modules.scala_runtime_BoxedUnit().UNIT__Lscala_runtime_BoxedUnit(); return this.dfa$2 }); ScalaJS.c.scala_xml_dtd_DFAContentModel.prototype.dfa__Lscala_util_automata_DetWordAutom = (function() { if ((!this.bitmap$0$2)) { return this.dfa$lzycompute__p2__Lscala_util_automata_DetWordAutom() } else { return this.dfa$2 } }); ScalaJS.c.scala_xml_dtd_DFAContentModel.prototype.dfa__ = (function() { return this.dfa__Lscala_util_automata_DetWordAutom() }); ScalaJS.c.scala_xml_dtd_DFAContentModel.prototype.r__ = (function() { return this.r__Lscala_util_regexp_Base$RegExp() }); /** @constructor */ ScalaJS.inheritable.scala_xml_dtd_DFAContentModel = (function() { /*<skip>*/ }); ScalaJS.inheritable.scala_xml_dtd_DFAContentModel.prototype = ScalaJS.c.scala_xml_dtd_DFAContentModel.prototype; ScalaJS.is.scala_xml_dtd_DFAContentModel = (function(obj) { return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_xml_dtd_DFAContentModel))) }); ScalaJS.as.scala_xml_dtd_DFAContentModel = (function(obj) { if ((ScalaJS.is.scala_xml_dtd_DFAContentModel(obj) || (obj === null))) { return obj } else { ScalaJS.throwClassCastException(obj, "scala.xml.dtd.DFAContentModel") } }); ScalaJS.isArrayOf.scala_xml_dtd_DFAContentModel = (function(obj, depth) { return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_xml_dtd_DFAContentModel))) }); ScalaJS.asArrayOf.scala_xml_dtd_DFAContentModel = (function(obj, depth) { if ((ScalaJS.isArrayOf.scala_xml_dtd_DFAContentModel(obj, depth) || (obj === null))) { return obj } else { ScalaJS.throwArrayCastException(obj, "Lscala.xml.dtd.DFAContentModel;", depth) } }); ScalaJS.data.scala_xml_dtd_DFAContentModel = new ScalaJS.ClassTypeData({ scala_xml_dtd_DFAContentModel: 0 }, false, "scala.xml.dtd.DFAContentModel", ScalaJS.data.scala_xml_dtd_ContentModel, { scala_xml_dtd_DFAContentModel: 1, scala_xml_dtd_ContentModel: 1, java_lang_Object: 1 }); ScalaJS.c.scala_xml_dtd_DFAContentModel.prototype.$classData = ScalaJS.data.scala_xml_dtd_DFAContentModel; //@ sourceMappingURL=DFAContentModel.js.map
mit
coingecko/cryptoexchange
lib/cryptoexchange/exchanges/bitconnect/market.rb
191
module Cryptoexchange::Exchanges module Bitconnect class Market < Cryptoexchange::Models::Market NAME = 'bitconnect' API_URL = 'https://bitconnect.co/api' end end end
mit
dvx/jssembly
core/src/com/polyfx/jssembly/Block.java
2442
package com.polyfx.jssembly; import java.nio.ByteBuffer; import org.antlr.runtime.ANTLRStringStream; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.Lexer; import org.antlr.runtime.RecognitionException; import static com.polyfx.jssembly.platforms.Architecture.*; import com.polyfx.jssembly.platforms.Architecture; import com.polyfx.jssembly.platforms.Assembler; import com.polyfx.jssembly.platforms.x64.x64Assembler; import com.polyfx.jssembly.platforms.x64.x64Lexer; public class Block { private Architecture architecture; private byte[] instructions; private String program = ""; public Block(byte[] instr) { this.instructions = instr; this.architecture = raw; } public Block(Architecture arch) { this.architecture = arch; Lexer lex = null; Assembler assembler = null; switch (architecture) { // no parsing necessary if we're writing bytes to memory case raw: return; // arm architectures trickle down case armv7: case armv9: // lex = new armLexer(new ANTLRStringStream(program)); // assembler = new armAssembler(new CommonTokenStream(lex)); break; case x64: lex = new x64Lexer(new ANTLRStringStream(program)); assembler = new x64Assembler(new CommonTokenStream(lex)); break; case x86: break; default: break; } try { if (assembler != null) { assembler.start(); this.instructions = assembler.getMachineCode(); } else { throw new JssemblyException("Assembler not found for architecture: " + this.architecture.name()); } } catch (RecognitionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* * Direct bytes go directly in the buffer (and to memory via the JNI bridge) * * NOTE: we use ints here otherwise we need to do annoying casting in the caller */ public void __asm(int ... bytes) { ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length); for (int i : bytes) { byteBuffer.put((byte) i); } this.instructions = byteBuffer.array(); } /* * One line at a time */ public void __asm(String line) { this.program += (line + '\n'); } /* * Multiple lines */ public void __asm(String... lines) { for (String line : lines) { this.__asm(line); } } /* * */ public String getProgram() { return this.program; } /* * */ public void invoke(Object... args) { Jssembly.invoke(this.instructions, args); } }
mit
mbret/miage-biblio-nodejs
api/controllers/api/ReservationController.js
2376
/** * ReservationController * * @description :: Server-side logic for managing reservations * @help :: See http://links.sailsjs.org/docs/controllers */ module.exports = { findMultiple: function (req, res) { Reservation.find().populate('user').populate('customer').populate('work').exec(function callback(err, reservations){ if(err) return res.serverError(err); return res.ok({ reservations: reservations }); }); }, create: function (req, res) { var data = {}; if( req.param('reference') ) data.work = req.param('reference'); // set literary work as reference if( req.param('customer') ) data.customer = req.param('customer'); // set customer data.user = req.session.userID; // set user Reservation.create( data ).exec(function(err, resa){ if(err){ if(err.ValidationError) return res.badRequest(err); else return res.serverError(err); } return res.created({ reservation: resa }); }); }, delete: function (req, res) { Reservation.findOne({'ID':req.param('id')}).then(function(reservation){ if(!reservation) return res.notFound(); // We destroy return Reservation.destroy({ID:req.param('id')}).then(function(){ return res.ok(); }); }).fail(function(err){ return res.serverError(err); }); }, update: function (req, res) { // Check required params if( !req.param('id') ) return res.badRequest(); // user data var data = {}; if( req.param('reference') ) data.work = req.param('reference'); if( req.param('customer') ) data.customer = req.param('customer'); // Query to update var query = { 'ID': req.param('id') } // Update process Reservation.update(query, data, function(err, resa) { if (err) { if(err.ValidationError) return res.badRequest( err ); else return res.serverError(err); } if(!resa || resa.length < 1) return res.notFound(); return res.ok({ reservation: resa[0] }); }); } };
mit
Phalanxia/Rad
Gruntfile.js
5673
"use strict"; var grunt = require("grunt"), os = require("os"), platforms = ["osx", "win", "linux32", "linux64"]; module.exports = function (grunt) { var pkg = grunt.file.readJSON("package.json"); var version = pkg.version; grunt.initConfig({ // Clean files to prep for a new build. clean: { before_build: { src: ["build/src", "build/Rad"] }, after_build: { src: ["build/src"] }, all: { src: ["node_modules", "build"] } }, compress: { win32: { options: { archive: "./dist/" + pkg.name + "_" + pkg.version + "_win32.zip"}, files: [{expand: true, cwd: "./build/Rad/win32/", src: ["**"]}] }, win64: { options: { archive: "./dist/" + pkg.name + "_" + pkg.version + "_win64.zip"}, files: [{expand: true, cwd: "./build/Rad/win64/", src: ["**"]}] }, osx32: { options: { archive: "./dist/" + pkg.name + "_" + pkg.version + "_osx32.zip"}, files: [{expand: true, cwd: "./build/Rad/osx32/", src: ["**"]}] }, osx64: { options: { archive: "./dist/" + pkg.name + "_" + pkg.version + "_osx64.zip"}, files: [{expand: true, cwd: "./build/Rad/osx64/", src: ["**"]}] }, linux32: { options: { archive: "./dist/" + pkg.name + "_" + pkg.version + "_linux32.zip"}, files: [{expand: true, cwd: "./build/Rad/linux32/", src: ["**"]}] }, linux64: { options: { archive: "./dist/" + pkg.name + "_" + pkg.version + "_linux64.zip"}, files: [{expand: true, cwd: "./build/Rad/linux64/", src: ["**"]}] } }, // Copy all files over and create a build directory so we don't mess up any of the source code. copy: { build: { files: [ { cwd: "app", src: ["**"], dest: "build/src/app", expand: true }, { src: "package.json", dest: "build/src/package.json" }, { src: "index.html", dest: "build/src/index.html" } ] } }, jshint: { options: {}, all: ["Gruntfile.js", "app/**/*.js"] }, less: { development: { options: { paths: [] }, files: { "app/assets/css/index.css": "app/assets/less/index.less" } }, build: { options: { paths: [], plugins: [], compress: true, optimization: 0 }, files: { "build/src/app/assets/css/index.css": "app/assets/less/index.less" } } }, nwjs: { win: { options: { appName: pkg.name, appVersion: pkg.version, buildDir: "./build", cacheDir: "./build/cache", platforms: platforms, winIco: "./build/src/app/assets/icons/icon.ico" }, src: ["./build/src/**/*"] }, all: { options: { appName: pkg.name, appVersion: pkg.version, buildDir: "./build", cacheDir: "./build/cache", platforms: platforms }, src: ["./build/src/**/*"] } }, shell: { run: { options: { stdout: false, stderr: false, stdin: false }, command: "nw ." }, install: { options: { stdout: false, stderr: false, stdin: false }, command: "npm install" }, build: { options: { stdout: false, stderr: false, stdin: false }, command: "cd ./build/src && npm install --production" } } }); // Load grunt contribution tasks. grunt.loadNpmTasks("grunt-contrib-clean"); grunt.loadNpmTasks("grunt-contrib-copy"); grunt.loadNpmTasks("grunt-contrib-jshint"); grunt.loadNpmTasks("grunt-contrib-less"); grunt.loadNpmTasks("grunt-contrib-compress"); // Load third-party tasks. grunt.loadNpmTasks("grunt-shell"); grunt.loadNpmTasks("grunt-nw-builder"); // Override default tasks or some magic. grunt.registerTask("default", []); // Register tasks. grunt.registerTask("build", function (platforms) { grunt.log.writeln("Building " + version); var platform = os.platform(), nwjsThing = "nwjs:all"; /* if (platform === "win32" || platform === "win64") { nwjsThing = "nwjs:win" } Getting errors x.x */ grunt.task.run([ "clean:before_build", "copy:build", "less:build", "shell:build", nwjsThing, "clean:after_build" ]); }); grunt.registerTask("test", function () { grunt.task.run([]); }); grunt.registerTask("lesscss", function () { grunt.log.writeln("Compiling .less files"); grunt.task.run(["less:development"]); }); grunt.registerTask("package", function () { var plats = []; if (platforms.indexOf("osx") > -1) { plats.push("compress:osx32", "compress:osx64"); } if (platforms.indexOf("win") > -1) { plats.push("compress:win32", "compress:win64"); } if (platforms.indexOf("linux32") > -1) { plats.push("compress:linux32"); } if (platforms.indexOf("linux64") > -1) { plats.push("compress:linux64"); } grunt.task.run(plats); }); grunt.registerTask("install", function () { grunt.log.writeln("Installing Dependencies"); grunt.task.run(["shell:install"]); }); grunt.registerTask("run", function () { grunt.log.writeln("Running Game " + version); grunt.task.run(["shell:run"]); }); }
mit
islas27/proyecto1-draw
almacenesHwrace/src/main/java/mx/uach/fing/almaceneshwrace/models/Product.java
4755
package mx.uach.fing.almaceneshwrace.models; import java.io.Serializable; import java.util.List; import java.util.Objects; import javax.persistence.*; /** * * @author jesus */ @Entity @Table (name ="products") public class Product extends ActiveRecord implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private Long id; @Column(name = "name") private String name; @Column(name = "description") private String description; @Column(name = "number_of_stock") private Long numberOfStock; @Column(name = "price") private Float price; @Column(name = "category") private String category; public Product() { } public Product(String name, String description, Long numberOfStock, Float price) { this.name = name; this.description = description; this.numberOfStock = numberOfStock; this.price = price; } /** * @return the id */ @Override public Long getId() { return id; } /** * @param id the id to set */ @Override public void setId(Long id) { this.id = id; } /** * @return the nombre */ public String getName() { return name; } /** * @param name the nombre to set */ public void setName(String name) { this.name = name; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } /** * @return the numberOfStock */ public Long getNumberOfStock() { return numberOfStock; } /** * @param numberOfStock the numberOfStock to set */ public void setNumberOfStock(Long numberOfStock) { this.numberOfStock = numberOfStock; } /** * @return the price */ public Float getPrice() { return price; } /** * @param price the precio to set */ public void setPrice(Float price) { this.price = price; } /** * @return the category */ public String getCategory() { return category; } /** * @param category the category to set */ public void setCategory(String category) { this.category = category; } /** * la funcion findAll mapea todos los productos de la base de datos * @return List de product */ public static List<Product> findAll(){ EntityManagerFactory emf = Persistence.createEntityManagerFactory(PU); EntityManager em = emf.createEntityManager(); List<Product> lista; em.getTransaction().begin(); Query q = em.createQuery("SELECT p FROM Product p"); lista = q.getResultList(); em.getTransaction().commit(); em.close(); emf.close(); return lista; } /** * La funcion findById devuelve una lista con todos los productos que * concuerden con el id dado * @param id * @return */ public static Product findById(Long id){ EntityManagerFactory emf = Persistence.createEntityManagerFactory(PU); EntityManager em = emf.createEntityManager(); Product p; em.getTransaction().begin(); Query q = em.createQuery("SELECT p FROM Product p WHERE p.id = ?"); q.setParameter(1, id); p = (Product)q.getResultList().get(0); em.getTransaction().commit(); em.close(); emf.close(); return p; } @Override public int hashCode() { int hash = 7; hash = 97 * hash + Objects.hashCode(this.id); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Product other = (Product) obj; if (!Objects.equals(this.id, other.id)) { return false; } if (!Objects.equals(this.name, other.name)) { return false; } if (!Objects.equals(this.description, other.description)) { return false; } if (!Objects.equals(this.numberOfStock, other.numberOfStock)) { return false; } if (!Objects.equals(this.price, other.price)) { return false; } if (!Objects.equals(this.category, other.category)) { return false; } return true; } }
mit
glomium/elmnt.de
useraccounts/conf.py
2296
#!/usr/bin/python # ex:set fileencoding=utf-8: from __future__ import unicode_literals from django.conf import settings as djsettings class Settings(object): PREFIX = "USERACCOUNTS" DEFAULTS = { # Enable login via... "LOGIN_EMAIL": True, "LOGIN_USERNAME": True, # Login security "CACHE_PREFIX": "useraccounts", "INTERNAL_IPS": djsettings.INTERNAL_IPS, "THROTTLE_IP": True, "THROTTLE_IP_COUNT": 25, "THROTTLE_IP_INTERVAL": 5, "THROTTLE_USER": True, "THROTTLE_USER_COUNT": 5, "THROTTLE_USER_INTERVAL": 3, "THROTTLE_SIGNAL_TIMEOUT": 180, # Email validation "VALIDATION_SALT": "useraccounts.email", "VALIDATION_TIMEOUT": 72, "VALIDATION_SEND_MAIL": True, "VALIDATION_TEMPLATE_HTML": None, "VALIDATION_TEMPLATE_PLAIN": "useraccounts/email_validation.txt", "VALIDATION_TEMPLATE_SUBJECT": "useraccounts/email_validation.subject", # Password restore "RESTORE_SALT": "useraccounts.restore", "RESTORE_TIMEOUT": 24, "RESTORE_SEND_MAIL": True, "RESTORE_TEMPLATE_HTML": None, "RESTORE_TEMPLATE_PLAIN": "useraccounts/email_restore.txt", "RESTORE_TEMPLATE_SUBJECT": "useraccounts/email_restore.subject", # resolve views "RESTORE_AUTOLOGIN": True, "RESOLVE_EMAIL_VALIDATE": None, "RESOLVE_PASSWORD_RESTORE": None, "REDIRECT_EMAIL_CREATE": None, "REDIRECT_EMAIL_VALIDATE": None, "REDIRECT_EMAIL_UPDATE": None, "REDIRECT_EMAIL_DELETE": None, "REDIRECT_EMAIL_RESEND": None, "REDIRECT_RESTORE_CREATE": None, "REDIRECT_RESTORE_SUCCESS": djsettings.LOGIN_REDIRECT_URL, "REDIRECT_CHANGE_SUCCESS": djsettings.LOGIN_REDIRECT_URL, # username "USERNAME_VALIDATORS": [ {'NAME': 'useraccounts.validators.UsernameValidator'} ], } def __init__(self): for key, value in self.DEFAULTS.items(): variable = "%s_%s" % (self.PREFIX, key) if not hasattr(djsettings, variable): setattr(djsettings, variable, value) setattr(self, key, getattr(djsettings, variable)) settings = Settings()
mit
shinznatkid/django-config
dconfig/files/settings.py
166
from .common_settings import * # pylint: disable=W0401 INSTALLED_APPS += [] try: from configs import * # pylint: disable=W0401 except ImportError: pass
mit
varunamachi/quartz
archives/plugin_orek_client/source/Plugin.cpp
968
#include <base/QzAppContext.h> #include <core/ext/IExtensionAdapter.h> #include "ContentProvider.h" #include "NodeProvider.h" #include "Plugin.h" namespace Quartz { namespace Ext { namespace Orek { const QString Plugin::PLUGIN_ID{ "qzplugin.orek_client" }; const QString Plugin::PLUGIN_NAME{ "Orek Client" }; struct Plugin::Data { AdapterList m_adapters; ExtensionList m_plugins; DependencyList m_dependencies; }; Plugin::Plugin() : Quartz::Ext::Plugin{ PLUGIN_ID, PLUGIN_NAME } , m_data{ new Data{} } { m_data->m_plugins.push_back( std::make_shared< ContentProvider >() ); m_data->m_plugins.push_back( std::make_shared< NodeProvider >() ); } Plugin::~Plugin() { } const ExtensionList & Plugin::extensions() const { return m_data->m_plugins; } const DependencyList & Plugin::dependencies() const { return m_data->m_dependencies; } const AdapterList &Plugin::adapters() const { return m_data->m_adapters; } } } }
mit
wmira/react-icons-kit
src/md/ic_restaurant_menu_twotone.js
464
export const ic_restaurant_menu_twotone = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M8.1 13.34l2.83-2.83L3.91 3.5c-1.56 1.56-1.56 4.09 0 5.66l4.19 4.18zm12.05-3.19c1.91-1.91 2.28-4.65.81-6.12-1.46-1.46-4.2-1.1-6.12.81-1.59 1.59-2.09 3.74-1.38 5.27L3.7 19.87l1.41 1.41L12 14.41l6.88 6.88 1.41-1.41L13.41 13l1.47-1.47c1.53.71 3.68.21 5.27-1.38z"},"children":[]}]};
mit
foundersandcoders/sail-back
test/upload/upload.member.test.js
1164
'use strict' var test = require('tape') var request = require('request') var fs = require('fs') var through = require('through2') var req = require('hyperquest') var mockMembers = require('./mocks.js').members var members = [] // make request to upload test('create members array', function (t) { var mockstream = mockMembers() mockstream.pipe(through.obj(function (buf, enc, next) { members.push(buf) return next() }, function (cb) { t.equals(members.length, 14, '14 members in array') t.end() return cb() })) }) test('POST to /upload?type=members', function (t) { var opts = { method: 'POST', uri: 'http://0.0.0.0:1337/upload?type=members', body: members, json: true } request(opts, function (e, h, r) { console.log('response', r) t.equals(r.problem_count, 0, 'no problems') t.ok(r.done, 'upload finished') t.end() }) }) test('records should exists', function (t) { var opts = { method: 'GET', uri: 'http://0.0.0.0:1337/api/members' } request(opts, function (e, h, r) { var payments = JSON.parse(r) t.ok(payments.length > 4, 'records created') t.end() }) })
mit
herowzz/dayIdGen
dayIdGen-embed/src/main/java/com/github/herowzz/dayIdGen/embed/DayIdGen.java
1379
package com.github.herowzz.dayIdGen.embed; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import com.github.herowzz.dayIdGen.embed.dao.IdDao; public class DayIdGen { private IdDao idDao; /** * name to generate db table name */ private String name; /** * prefix string to begin with the id<br> * if the id is 3 and prefix is FK, than the final id is FK3 */ private String prefix = ""; /** * id with the min digit, will begin with 0<br> * if the id is 3 and minDigit is 3, than the final id is 003 */ private int minDigit = 3; public String getNextId() throws Exception { long id = idDao.getNextDayId(name); return prefix + String.format("%0" + minDigit + "d", id); } public String getNextDateId() throws Exception { LocalDate now = LocalDate.now(); long id = idDao.getNextDayId(name, now); return prefix + now.format(DateTimeFormatter.ofPattern("yyMMdd")) + String.format("%0" + minDigit + "d", id); } public int clearTables() throws Exception { return idDao.clearIdTables(); } public void setPrefix(String prefix) { this.prefix = prefix; } public void setMinDigit(int minDigit) { this.minDigit = minDigit; } public void setName(String name) { this.name = name; } public void setIdDao(IdDao idDao) { this.idDao = idDao; } }
mit
ombt/ombt
old/libsrc/ternarytree/test/localization_test.cpp
1049
#include "tests_common.hpp" #include "../examples/locale_less.hpp" int localization_test() { long result = errors_counter(); typedef containers::ternary_tree<std::string, int, utility::locale_less<char> > LocTst; LocTst names(utility::locale_less<char>::locale_less(utility::swedish_locale_name)); names["aåa"] = 2; names["aäå"] = 3; names["aaå"] = 1; names["aöå"] = 4; names["ååå"] = 11; names["åäö"] = 12; names["öäå"] = 17; names["äåö"] = 14; names["äöå"] = 16; names["ääö"] = 15; names["åöå"] = 13; bool display = false; BOOST_CHECK(names.size() == 11); LocTst::iterator it = names.begin(); int x = 0, prev = 0; while (it != names.end()) { x = *it++; BOOST_CHECK(x > prev); if (x <= prev) { display = true; break; } prev = x; } if (display) { for (it = names.begin(); it != names.end(); ++it) { std::string key = it.key(); CharToOem(key.c_str(), (char*)key.c_str()); std::cout << key << ", "; } } return errors_counter() - result; }
mit
carlcortright/Playground
Ruby/Basics/arguments.rb
63
first, second, third = ARGV puts "#{first} #{second} #{third}"
mit
twilio/twilio-csharp
src/Twilio/Rest/Conversations/V1/CredentialOptions.cs
8866
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Converters; namespace Twilio.Rest.Conversations.V1 { /// <summary> /// Add a new push notification credential to your account /// </summary> public class CreateCredentialOptions : IOptions<CredentialResource> { /// <summary> /// The type of push-notification service the credential is for. /// </summary> public CredentialResource.PushTypeEnum Type { get; } /// <summary> /// A string to describe the resource /// </summary> public string FriendlyName { get; set; } /// <summary> /// [APN only] The URL encoded representation of the certificate. /// </summary> public string Certificate { get; set; } /// <summary> /// [APN only] The URL encoded representation of the private key. /// </summary> public string PrivateKey { get; set; } /// <summary> /// [APN only] Whether to send the credential to sandbox APNs. /// </summary> public bool? Sandbox { get; set; } /// <summary> /// [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. /// </summary> public string ApiKey { get; set; } /// <summary> /// [FCM only] The Server key of your project from Firebase console. /// </summary> public string Secret { get; set; } /// <summary> /// Construct a new CreateCredentialOptions /// </summary> /// <param name="type"> The type of push-notification service the credential is for. </param> public CreateCredentialOptions(CredentialResource.PushTypeEnum type) { Type = type; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (Type != null) { p.Add(new KeyValuePair<string, string>("Type", Type.ToString())); } if (FriendlyName != null) { p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName)); } if (Certificate != null) { p.Add(new KeyValuePair<string, string>("Certificate", Certificate)); } if (PrivateKey != null) { p.Add(new KeyValuePair<string, string>("PrivateKey", PrivateKey)); } if (Sandbox != null) { p.Add(new KeyValuePair<string, string>("Sandbox", Sandbox.Value.ToString().ToLower())); } if (ApiKey != null) { p.Add(new KeyValuePair<string, string>("ApiKey", ApiKey)); } if (Secret != null) { p.Add(new KeyValuePair<string, string>("Secret", Secret)); } return p; } } /// <summary> /// Update an existing push notification credential on your account /// </summary> public class UpdateCredentialOptions : IOptions<CredentialResource> { /// <summary> /// A 34 character string that uniquely identifies this resource. /// </summary> public string PathSid { get; } /// <summary> /// The type of push-notification service the credential is for. /// </summary> public CredentialResource.PushTypeEnum Type { get; set; } /// <summary> /// A string to describe the resource /// </summary> public string FriendlyName { get; set; } /// <summary> /// [APN only] The URL encoded representation of the certificate. /// </summary> public string Certificate { get; set; } /// <summary> /// [APN only] The URL encoded representation of the private key. /// </summary> public string PrivateKey { get; set; } /// <summary> /// [APN only] Whether to send the credential to sandbox APNs. /// </summary> public bool? Sandbox { get; set; } /// <summary> /// [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. /// </summary> public string ApiKey { get; set; } /// <summary> /// [FCM only] The Server key of your project from Firebase console. /// </summary> public string Secret { get; set; } /// <summary> /// Construct a new UpdateCredentialOptions /// </summary> /// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param> public UpdateCredentialOptions(string pathSid) { PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (Type != null) { p.Add(new KeyValuePair<string, string>("Type", Type.ToString())); } if (FriendlyName != null) { p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName)); } if (Certificate != null) { p.Add(new KeyValuePair<string, string>("Certificate", Certificate)); } if (PrivateKey != null) { p.Add(new KeyValuePair<string, string>("PrivateKey", PrivateKey)); } if (Sandbox != null) { p.Add(new KeyValuePair<string, string>("Sandbox", Sandbox.Value.ToString().ToLower())); } if (ApiKey != null) { p.Add(new KeyValuePair<string, string>("ApiKey", ApiKey)); } if (Secret != null) { p.Add(new KeyValuePair<string, string>("Secret", Secret)); } return p; } } /// <summary> /// Remove a push notification credential from your account /// </summary> public class DeleteCredentialOptions : IOptions<CredentialResource> { /// <summary> /// A 34 character string that uniquely identifies this resource. /// </summary> public string PathSid { get; } /// <summary> /// Construct a new DeleteCredentialOptions /// </summary> /// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param> public DeleteCredentialOptions(string pathSid) { PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// Fetch a push notification credential from your account /// </summary> public class FetchCredentialOptions : IOptions<CredentialResource> { /// <summary> /// A 34 character string that uniquely identifies this resource. /// </summary> public string PathSid { get; } /// <summary> /// Construct a new FetchCredentialOptions /// </summary> /// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param> public FetchCredentialOptions(string pathSid) { PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// Retrieve a list of all push notification credentials on your account /// </summary> public class ReadCredentialOptions : ReadOptions<CredentialResource> { /// <summary> /// Generate the necessary parameters /// </summary> public override List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (PageSize != null) { p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString())); } return p; } } }
mit
dolimoni/ensa-Project
application/views/profil.php
13509
<!DOCTYPE html> <html> <head> <title>ENSA - Authentification</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="icon" type="image/png" href="images/favicon-32x32.png" /> <link rel="stylesheet" type="text/css" href="<?php echo css_url('style')?>"> <!-- Bootstrap files --> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/bootstrap/css/bootstrap.min.css" /> <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,800,700,600,300' rel='stylesheet' type='text/css'> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/icons/flaticon.css" /> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/signup.css" /> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/login.css" /> </head> <body> <!-- Inscription --> <div id="e_signup"> <div class="container"> <div class="e_title col-sm-4 col-sm-offset-2"> <h3>Mon profile</h3> </div> <br/><br/><br/> <div class="text-center"> <?php if($who == "ensa"){ ?> <a href="<?php echo site_url('My_controllerpdf/pdfensasprepa')?>" class="btn btn-warning"><span class="glyphicon glyphicon-download-alt"></span> Générer PDF</a> <?php }elseif($who == "cnc"){ ?> <a href="<?php echo site_url('My_controllerpdf/pdfelevescnc')?>" class="btn btn-warning"><span class="glyphicon glyphicon-download-alt"></span> Générer PDF</a> <?php }else{ ?> <a href="<?php echo site_url('My_controllerpdf/pdfconcours')?>" class="btn btn-warning"><span class="glyphicon glyphicon-download-alt"></span> Générer PDF</a> <?php } ?> <a href="<?php echo site_url("etudiant_controller/deconnexion"); ?>" class="btn btn-success"><span class="glyphicon glyphicon-edit"></span> Modifier</a> <a href="<?php echo site_url("etudiant_controller/deconnexion"); ?>" class="btn btn-danger"><span class="glyphicon glyphicon-remove"></span> Deconnexion</a> <br/> <br/> <img class="img-thumbnail" src="<?php echo img_url($cin.".jpg"); ?>" style="width:200px; height: 200px;" /> </div> <div class="row"> <div class="col-sm-5 col-sm-offset-1"> <div class="e_input col-md-12"> <span class="glyphicon glyphicon-bookmark"></span> <span> nom </span><div class="pull-right"><?php echo $nom; ?></div> </div> <div class="e_input col-md-12"> <span class="glyphicon glyphicon-bookmark"><span> prénom </span></span><div class="pull-right"><?php echo $prenom; ?></div> </div> <div class="e_input col-md-12"> <span class="glyphicon glyphicon-lock"></span> <span> CIN</span><div class="pull-right"><?php echo $cin; ?></div> </div> <div class="e_input col-md-12"> <span class="glyphicon glyphicon-lock"></span><span> CNE</span><div class="pull-right"><?php echo $cne; ?></div> </div> <div class="e_input col-md-12"> <span class="glyphicon glyphicon-bookmark"></span> <span> Civilité</span><div class="pull-right"><?php echo $civilite; ?></div> </div> <div class="e_input col-md-12"> <span class="glyphicon glyphicon-flag"> <span> Nationalité</span></span><div class="pull-right"><?php echo $nationalite; ?></div> </div> <?php if($who == "ensa"){ ?> <div class="e_input e_date col-md-12"> <span class="glyphicon glyphicon-list-alt"></span> <span>Type de bac</span><div class="pull-right"><?php echo $type_bac; ?></div> </div> <div class="e_input col-md-12"> <span class="glyphicon glyphicon-lock"></span> <span>Note de bac</span><div class="pull-right"><?php echo $note_bac; ?></div> </div> <div class="e_input col-md-12"> <span class="glyphicon glyphicon-lock"></span><span>Note de la 1er année</span> <div class="pull-right"><?php echo $note_1er_annee; ?></div> </div> <div class="e_input col-md-12"> <span class="glyphicon glyphicon-lock"></span> <div class="pull-right">// à faire le classement</div> </div> Choix de filière : <br/> <div class="table-responsive"> <table class="table table-hover"> <thead> <tr> <th>1er choix</th> <th>2éme choix</th> <th>3éme choix</th> </tr> </thead> <tbody> <tr> <td><?php echo $choix1; ?></td> <td><?php echo $choix2; ?></td> <td><?php echo $choix3; ?></td> </tr> </tbody> </table> </div> <input type="hidden" value="ensa" name="who" /> <?php } else if($who == "cnc"){ ?> <div class="e_input e_date col-md-12"> <span class="glyphicon glyphicon-list-alt"></span> <span>Type de bac</span><div class="pull-right"><?php echo $type_bac; ?></div> </div> <div class="e_input col-md-12"> <span class="glyphicon glyphicon-lock"></span> <span>Note de bac</span><div class="pull-right"><?php echo $note_bac; ?></div> </div> <div class="e_input col-md-12"> <span class="glyphicon glyphicon-lock"></span> <span>filiere cp</span><div class="pull-right"><?php echo $filiere_cp; ?></div> </div> <div class="e_input col-md-12"> <span class="glyphicon glyphicon-lock"></span> <span>etablissement cp</span><div class="pull-right"><?php echo $etablissement_cp; ?></div> </div> <div class="e_input col-md-12"> <span class="glyphicon glyphicon-lock"></span> <span>ville_cp</span><div class="pull-right"><?php echo $ville_cp; ?></div> </div> <div class="e_input col-md-12"> <span class="glyphicon glyphicon-lock"></span> <span>range cp</span><div class="pull-right"><?php echo $range_cnc; ?></div> </div> <div class="e_input col-md-12"> <span class="glyphicon glyphicon-lock"></span> <span>filière ENSA</span><div class="pull-right"><?php echo $choix1; ?></div> </div> <input type="hidden" value="ensa" name="cnc" /> <?php } else { ?> <div class="e_input e_date col-md-12"> <span class="glyphicon glyphicon-list-alt"></span> <span>Type de bac</span><div class="pull-right"><?php echo $type_bac; ?></div> </div> <div class="e_input col-md-12"> <span class="glyphicon glyphicon-lock"></span> <span>Note de bac</span><div class="pull-right"><?php echo $note_bac; ?></div> </div> <div class="e_input col-md-12"> <span class="glyphicon glyphicon-lock"></span> <span>type de diplome</span><div class="pull-right"><?php echo $type_diplome; ?></div> </div> <div class="e_input col-md-12"> <span class="glyphicon glyphicon-lock"></span> <span>etablissement du diplome</span><div class="pull-right"><?php echo $etablissement_diplome; ?></div> </div> <div class="e_input col-md-12"> <span class="glyphicon glyphicon-lock"></span> <span>filière ENSA</span><div class="pull-right"><?php echo $choix1; ?></div> </div> <input type="hidden" value="ensa" name="3and4Year" /> <?php } ?> </div> <div class="col-sm-5"> <div class="e_input e_date col-md-12"> <span class="glyphicon glyphicon-calendar"></span> <span> Date de naissance</span><div class="pull-right"><?php echo $date_naissance; ?></div> </div> <div class="e_input col-md-12"> <span class="glyphicon glyphicon-map-marker"> <span> Lieu de naissance</span></span><div class="pull-right"><?php echo $lieu_naissance; ?></div> </div> <div class="e_input col-md-12"> <span class="glyphicon glyphicon-earphone"> <span> Téléphone</span></span><div class="pull-right"><?php echo $tel; ?></div> </div> <div class="e_input col-md-12"> <span class="glyphicon glyphicon-phone"></span> <span> GSM</span><div class="pull-right"><?php echo $gsm; ?></div> </div> <div class="e_input col-md-12"> <span class="glyphicon glyphicon-envelope"> <span> Email</span></span><div class="pull-right"><?php echo $email; ?></div> </div> <div class="e_input col-md-12"> <span class="glyphicon glyphicon-map-marker"></span> <span> Adresse</span><div class="pull-right"><?php echo $adresse; ?></div> </div> <div class="e_input col-md-12"> <span class="glyphicon glyphicon-map-marker"></span> <span> Ville</span> <div class="pull-right"><?php echo $ville; ?></div> </div> <div class="e_input col-md-12"> <span class="glyphicon glyphicon-info-sign"></span> <span>Profession du père</span><div class="pull-right"><?php echo $profession_pere; ?></div> </div> <div class="e_input col-md-12"> <span class="glyphicon glyphicon-info-sign"></span> <span> Porfession de la mère</span><div class="pull-right"><?php echo $profession_mere; ?></div> </div> <br/> </div> </div> </div> </div> <script src="<?php echo base_url(); ?>assets/js/jquery.js"></script> <script src="<?php echo base_url(); ?>assets/bootstrap/js/bootstrap.min.js"></script> <script src="<?php echo base_url(); ?>assets/js/scripts.js"></script> </body> </html>
mit
robocon/easy1-template
lang/th/research/readresearch.php
124
<?php $T = array( 'Research' => 'ผลงานวิชาการ', 'By' => 'โดย', 'on' => 'เมื่อ' );
mit
CaptChadd/Extremecoin
src/version.cpp
2717
// Copyright (c) 2012 The Bitcoin developers // Copyright (c) 2012 Litecoin Developers // Copyright (c) 2012 Extremecoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("CaptChadd"); // Client version number #define CLIENT_VERSION_SUFFIX "-EXC" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$ #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "$Format:%h$" # define GIT_COMMIT_DATE "$Format:%cD" #endif #define STRINGIFY(s) #s #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" STRINGIFY(maj) "." STRINGIFY(min) "." STRINGIFY(rev) "." STRINGIFY(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" STRINGIFY(maj) "." STRINGIFY(min) "." STRINGIFY(rev) "." STRINGIFY(build) "-UK" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE);
mit
whipcash/whipcash
src/rpcdump.cpp
3004
// Copyright (c) 2009-2014 Bitcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "init.h" // for pwalletMain #include "bitcoinrpc.h" #include "ui_interface.h" #include "base58.h" #include <boost/lexical_cast.hpp> #define printf OutputDebugStringF using namespace json_spirit; using namespace std; class CTxDump { public: CBlockIndex *pindex; int64 nValue; bool fSpent; CWalletTx* ptx; int nOut; CTxDump(CWalletTx* ptx = NULL, int nOut = -1) { pindex = NULL; nValue = 0; fSpent = false; this->ptx = ptx; this->nOut = nOut; } }; Value importprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "importprivkey <whipcashprivkey> [label] [rescan=true]\n" "Adds a private key (as returned by dumpprivkey) to your wallet."); EnsureWalletIsUnlocked(); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding"); CKey key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); CKeyID vchAddress = pubkey.GetID(); if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range"); { LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->MarkDirty(); pwalletMain->SetAddressBookName(vchAddress, strLabel); if (!pwalletMain->AddKeyPubKey(key, pubkey)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); if (fRescan) { pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true); pwalletMain->ReacceptWalletTransactions(); } } return Value::null; } Value dumpprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey <whipcashaddress>\n" "Reveals the private key corresponding to <whipcashaddress>."); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Whipcash address"); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CKey vchSecret; if (!pwalletMain->GetKey(keyID, vchSecret)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); return CBitcoinSecret(vchSecret).ToString(); }
mit
ebemunk/blog
projects/van-eventviz/scraper/src/scrape.test.js
994
import { readFile } from 'fs' import { fromCallback } from 'bluebird' import axios from 'axios' import scrape, { parsePage } from './scrape' import * as db from './db' let data, empty beforeAll(async () => { data = await fromCallback(cb => readFile('./test/test2.html', 'utf-8', cb)) empty = await fromCallback(cb => readFile('./test/empty.html', 'utf-8', cb)) db.getPool = jest.fn(() => ({ query: jest.fn(() => Promise.resolve()), end: jest.fn(() => Promise.resolve()), })) }) describe('scrape', () => { it('gets', async () => { axios.get = jest .fn() .mockReturnValueOnce(Promise.resolve({ data })) .mockReturnValueOnce(Promise.resolve({ data: empty })) const events = await scrape() expect(axios.get).toHaveBeenCalledTimes(2) }) }) describe('parsePage', () => { it('parses list html', async () => { axios.get = jest.fn(() => Promise.resolve({ data })) const evs = await parsePage(3) expect(evs).toMatchSnapshot() }) })
mit
ShankarSumanth/lean-react
webpack-config/named-module-plugin.js
90
const webpack = require( 'webpack' ); module.exports = new webpack.NamedModulesPlugin();
mit
Arseniik/mean-gallery
app/routes/files.server.routes.js
1948
'use strict'; module.exports = function(app) { var files = require('../../app/controllers/files.server.controller'); var users = require('../../app/controllers/users.server.controller'); var multer = require('multer'); var upload = multer({dest: __dirname + '/../../public/data/'}); var multipleUpload = upload.array('files'); var fs = require('fs'); // Routing logic app.route('/files').get(users.requiresLogin, files.list); app.get('/files/dirs', users.requiresLogin, files.getFolders); app.get('/files/upload', users.requiresLogin, function (req, res) { }) .post('/files/upload', users.requiresLogin, multipleUpload, function (req, res) { var folder = (req.body.folderName !== '') ? req.body.folderName : (req.body.selectedFolder === 'root') ? '' : req.body.selectedFolder; var path = __dirname + '/../../public/data/' + folder + '/'; console.log('Path :', path); if (req.body.folderName !== '') { createFolder(path); } req.files.forEach(function (file) { var tmp_path = file.path; var target_path = path + file.originalname; console.log('tmp : ', tmp_path) console.log('target :', target_path); fs.rename(tmp_path, target_path, function(err) { if (err) throw err; fs.unlink(tmp_path, function() { if (err) { throw err; } }); }); }); res.redirect(200, '/files'); }); function createFolder(name) { fs.mkdir(name, '777', function(err) { if (err) { if (err.code === 'EEXISTS') { return; } else { console.log(err); throw err; } } }); console.log('folder created'); } };
mit
vyper/c4p
lib/config/mapping.rb
1216
collection :users do entity User repository UserRepository attribute :id, String attribute :name, String attribute :email, String attribute :password, EncryptedPassword attribute :created_at, DateTime attribute :updated_at, DateTime end collection :authentications do entity Authentication repository AuthenticationRepository attribute :id, String attribute :user_id, String attribute :uid, String attribute :provider, String attribute :created_at, DateTime attribute :updated_at, DateTime end collection :events do entity Event repository EventRepository attribute :id, String attribute :owner_id, String attribute :name, String attribute :description, String attribute :tags, PGCITextArray attribute :created_at, DateTime attribute :updated_at, DateTime end collection :talks do entity Talk repository TalkRepository attribute :id, String attribute :event_id, String attribute :author_id, String attribute :name, String attribute :description, String attribute :created_at, DateTime attribute :updated_at, DateTime end
mit
zhangzhe/ama-china
app/helpers/comments_helper.rb
326
module CommentsHelper def comments_tree_for(comments) comments.map do |comment, nested_comments| render(partial: "/comments/comment", locals: {comment: comment}) + (nested_comments.size > 0 ? content_tag(:div, comments_tree_for(nested_comments), class: "replies") : nil) end.join.html_safe end end
mit
black-security/cyber-security-framework
remote/dns/dnask.py
4801
import dns.resolver, dns.message, argparse, random from network.modules import socket from core.modules.base import Program from core.modules.console import print class DNAsk(Program): """Utility to build and execute DNS queries ...""" requirements = {"dnspython3"} def __init__(self): super().__init__() self.parser.add_argument("query", type=str, help="Query string.") self.parser.add_argument("-t", "--rdtype", type=str, default=1, help="Query type.") self.parser.add_argument("-c", "--rdclass", type=str, default=1, help="Query class.") self.parser.add_argument("-m", "--metaquery", action="store_true", help="Execute as MetaQuery.") self.parser.add_argument("-s", "--source", type=str, default=socket.gethostbyname(socket.gethostname()), help="Source address.") self.parser.add_argument("-sP", "--source-port", type=int, default=random.randint(1, 65535), help="Source port.") self.parser.add_argument("--tcp", action="store_true", help="Use TCP to make the query.") self.parser.add_argument("-ns", "--nameservers", nargs="+", type=str, help="A list of nameservers to query. Each nameserver is a string which contains the IP address of a nameserver.") self.parser.add_argument("-p", "--port", type=int, default=53, help="The port to which to send queries (Defaults to 53).") self.parser.add_argument("-T", "--timeout", type=int, default=8, help="The number of seconds to wait for a response from a server, before timing out.") self.parser.add_argument("-l", "--lifetime", type=int, default=8, help="The total number of seconds to spend trying to get an answer to the question. If the lifetime expires, a Timeout exception will occur.") self.parser.add_argument("-e", "--edns", type=int, default=-1, help="The EDNS level to use (Defaults to -1, no Edns).") self.parser.add_argument("-eF", "--edns-flags", type=int, help="The EDNS flags.") self.parser.add_argument("-eP", "--edns-payload", type=int, default=0, help="The EDNS payload size (Defaults to 0).") self.parser.add_argument("-S", "--want-dnssec", action="store_true", help="Indicate that DNSSEC is desired.") self.parser.add_argument("-f", "--flags", type=int, default=None, help="The message flags to use (Defaults to None (i.e. not overwritten)).") self.parser.add_argument("-r", "--retry-servfail", action="store_true", help="Retry a nameserver if it says SERVFAIL.") self.parser.add_argument("-R", "--one-rr-per-rrset", action="store_true", help="Put each RR into its own RRset (Only useful when executing MetaQueries).") self.parser.add_argument("--filename", type=argparse.FileType("r"), help="The filename of a configuration file in standard /etc/resolv.conf format. This parameter is meaningful only when I{configure} is true and the platform is POSIX.") self.parser.add_argument("--configure-resolver", action="store_false", help="If True (the default), the resolver instance is configured in the normal fashion for the operating system the resolver is running on. (I.e. a /etc/resolv.conf file on POSIX systems and from the registry on Windows systems.") def run(self): arguments = self.arguments.__dict__ nameservers = arguments.get("nameservers") resolver = dns.resolver.Resolver(arguments.get("filename"), arguments.get("configure_resolver")) resolver.set_flags(arguments.get("flags")) resolver.use_edns(arguments.get("edns"), arguments.get("edns_flags"), arguments.get("edns_payload")) if nameservers: resolver.nameservers = nameservers resolver.port = arguments.get("port") resolver.timeout = arguments.get("timeout") resolver.lifetime = arguments.get("lifetime") resolver.retry_servfail = arguments.get("retry_servfail") if arguments.pop("metaquery"): kwargs = {v: arguments.get(k) for k, v in {"rdclass": "rdclass", "edns": "use_edns", "want_dnssec": "want_dnssec", "edns_flags": "ednsflags", "edns_payload": "request_payload"}.items()} message = dns.message.make_query(arguments.get("query"), arguments.get("rdtype"), **kwargs) kwargs = {k: arguments.get(k) for k in ["timeout", "port", "source", "source_port", "one_rr_per_rrset"]} if arguments.get("tcp"): resp = dns.query.tcp(message, resolver.nameservers[0], **kwargs) else: resp = dns.query.udp(message, resolver.nameservers[0], **kwargs) print(resp) else: kwargs = {k: arguments.get(k) for k in ["rdtype", "rdclass", "tcp", "source", "source_port"]} answer = resolver.query(arguments.pop("query"), **kwargs) print(answer.response)
mit
Molajo/Cache
Source/Driver.php
1983
<?php /** * Cache Driver * * @package Molajo * @copyright 2014-2015 Amy Stephen. All rights reserved. * @license http://www.opensource.org/licenses/mit-license.html MIT License */ namespace Molajo\Cache; use CommonApi\Cache\CacheInterface; /** * Cache Driver * * @package Molajo * @copyright 2014-2015 Amy Stephen. All rights reserved. * @license http://www.opensource.org/licenses/mit-license.html MIT License * @since 1.0.0 */ final class Driver implements CacheInterface { /** * Cache Adapter * * @var object * @since 1.0.0 */ protected $adapter; /** * Constructor * * @param CacheInterface $cache * * @since 1.0.0 */ public function __construct(CacheInterface $cache) { $this->adapter = $cache; } /** * Return cached or parameter value * * @param string $key serialize name uniquely identifying content * * @return bool|CacheItem cache for this key that has not been serialized * @since 1.0.0 */ public function get($key) { return $this->adapter->get($key); } /** * Persist data in cache * * @param string $key * @param mixed $value * @param integer $ttl (number of seconds) * * @return bool * @since 1.0.0 */ public function set($key, $value, $ttl = 0) { return $this->adapter->set($key, $value, $ttl); } /** * Remove cache for specified $key value * * @param string $key serialize name uniquely identifying content * * @return object CacheInterface * @since 1.0.0 */ public function remove($key = null) { return $this->adapter->remove($key); } /** * Clear all cache * * @return object CacheInterface * @since 1.0.0 */ public function clear() { return $this->adapter->clear(); } }
mit
SimonWallner/archive-rails
app/helpers/application_helper.rb
3253
module ApplicationHelper require 'redcarpet' PREDEFINED_FIELDS = ["External Links", "Aggregate Scores", "Review Scores"] @@GAME_VERSIONER = GameVersioner.instance # amount displayed featured entries def getAmountFeatured() return 8 end def markdown(text) rndr = CustomLinkRenderer.new(:filter_html => true, :no_images => true, :hard_wrap => true) markdown = Redcarpet::Markdown.new(rndr, :space_after_headers => true, :autolink => true) markdown.render(text).html_safe end class CustomLinkRenderer < Redcarpet::Render::HTML def link(link, title, alt_text) "<a href=\"#{link}\">#{alt_text}</a>" end # parse links and email addresses even if they are not enclosed # in () # cut down long links to make them prettier def autolink(link, link_type) if (link_type == :url) if link[-1] =='/' link = link[0..-1] end link_title = link.split("/") link_end = "" if link_title.length > 5 link_title=link_title[0..4] link_end = "/..." end link_t = link_title[2] for i in 3..link_title.length-1 if link_title[i].length>20 link_end = "/..." break end link_t += "/" + link_title[i] end link_t +=link_end return "<a href=\"#{link}\">#{link_t}</a>" elsif (link_type == :email) return "<a href=mailto:\"#{link}\">#{link}</a>" else return nil end end end def just_links_markdown(text) logger.debug "render just links" logger.debug text renderer = JustLinksRenderer.new :filter_html => true logger.debug "renderer initialised" markdown = Redcarpet::Markdown.new renderer, :autolink => true markdown.render(text).html_safe end # Returns an array of MixedField objects which fit the given type # # == Parameters: # object:: [game, company, developer] object for which the mixed fields # should be retrieved. # type:: [can be each MixedFieldType name (as symbols), :all] Type of the # mixed field that is queried, provide as symbol # # == Returns: # Array fo Mixed Fields objects # def get_mixed_fields(object, type) if type == nil || object == nil return Array.new end mf = object.mixed_fields if type == :all #return mf return @@GAME_VERSIONER.current_version_mixed_fields mf end mfs = mf.find_all {|i| i.mixed_field_type.name == type.to_s } return mfs end def get_field(object, name) if object == nil || name == nil return Array.new end f = object.fields return f.find_all { |i| i.name == name } end def get_user_fields(object) if object == nil return Array.new end f = object.fields return f.find_all { |i| not PREDEFINED_FIELDS.include?(i.name) } end # returns a formatted date with additional info def format_date(date) if date == nil return "" end formatted_date = "" if date.day != nil formatted_date = formatted_date + date.day.to_s + "." end if date.month != nil formatted_date = formatted_date + date.month.to_s + "." end if date.year != nil formatted_date = formatted_date + date.year.to_s end begin if date.additional_info != nil formatted_date = formatted_date + " - " + date.additional_info end rescue # do nothing here end return formatted_date end end
mit
marcinfkns/yet-another-retryer
src/main/java/retryer/stopstrategy/CompositeStopStrategy.java
534
package retryer.stopstrategy; import java.util.List; import retryer.RetryContext; /** concrete instances provided by StopStrategy.or/and methods */ public abstract class CompositeStopStrategy<T> implements StopStrategy<T> { List<StopStrategy<T>> strategies; public CompositeStopStrategy(List<StopStrategy<T>> strategies) { this.strategies = strategies; } @Override public void switchOn() { strategies.forEach(s -> s.switchOn()); } @Override public void switchOff() { strategies.forEach(s -> s.switchOff()); } }
mit
binary42/OCI
orbsvcs/Log/NotifyLog_i.cpp
6879
// $Id: NotifyLog_i.cpp 1861 2011-08-31 16:18:08Z mesnierp $ #include "orbsvcs/Log/NotifyLog_i.h" #include "orbsvcs/Log/LogMgr_i.h" #include "orbsvcs/Log/LogNotification.h" TAO_BEGIN_VERSIONED_NAMESPACE_DECL TAO_NotifyLog_i::TAO_NotifyLog_i (CORBA::ORB_ptr orb, PortableServer::POA_ptr poa, TAO_LogMgr_i &logmgr_i, DsLogAdmin::LogMgr_ptr factory, CosNotifyChannelAdmin::EventChannelFactory_ptr ecf, TAO_LogNotification *log_notifier, DsLogAdmin::LogId id) : TAO_Log_i (orb, logmgr_i, factory, id, log_notifier), notify_factory_ (CosNotifyChannelAdmin::EventChannelFactory::_duplicate (ecf)), poa_ (PortableServer::POA::_duplicate (poa)) { CosNotifyChannelAdmin::ChannelID channel_id; CosNotification::QoSProperties initial_qos; CosNotification::AdminProperties initial_admin; ACE_ASSERT (!CORBA::is_nil (this->notify_factory_.in ())); this->event_channel_ = this->notify_factory_->create_channel (initial_qos, initial_admin, channel_id); } TAO_NotifyLog_i::~TAO_NotifyLog_i () { this->event_channel_->destroy (); } DsLogAdmin::Log_ptr TAO_NotifyLog_i::copy (DsLogAdmin::LogId &id) { DsNotifyLogAdmin::NotifyLogFactory_var notifyLogFactory = DsNotifyLogAdmin::NotifyLogFactory::_narrow (factory_.in ()); CosNotification::QoSProperties* qos = get_qos (); CosNotification::AdminProperties* admin = get_admin (); DsNotifyLogAdmin::NotifyLog_var log = notifyLogFactory->create (DsLogAdmin::halt, 0, thresholds_, static_cast<const CosNotification::QoSProperties> (*qos), static_cast<const CosNotification::AdminProperties> (*admin), id); this->copy_attributes (log.in ()); return log._retn (); } DsLogAdmin::Log_ptr TAO_NotifyLog_i::copy_with_id (DsLogAdmin::LogId id) { DsNotifyLogAdmin::NotifyLogFactory_var notifyLogFactory = DsNotifyLogAdmin::NotifyLogFactory::_narrow (factory_.in ()); CosNotification::QoSProperties* qos = get_qos (); CosNotification::AdminProperties* admin = get_admin (); DsNotifyLogAdmin::NotifyLog_var log = notifyLogFactory->create_with_id (id, DsLogAdmin::halt, 0, thresholds_, static_cast<const CosNotification::QoSProperties> (*qos), static_cast<const CosNotification::AdminProperties> (*admin)); this->copy_attributes (log.in ()); return log._retn (); } void TAO_NotifyLog_i::destroy (void) { notifier_->object_deletion (logid_); // Remove ourselves from the list of logs. this->logmgr_i_.remove (this->logid_); // Deregister with POA. PortableServer::ObjectId_var id = this->poa_->servant_to_id (this); this->poa_->deactivate_object (id.in ()); } void TAO_NotifyLog_i::activate (void) { CosNotifyChannelAdmin::AdminID adminid = 0; CosNotifyChannelAdmin::InterFilterGroupOperator ifgop = CosNotifyChannelAdmin::OR_OP; this->consumer_admin_ = this->event_channel_->new_for_consumers (ifgop, adminid); ACE_ASSERT (!CORBA::is_nil (consumer_admin_.in ())); // Setup the CA to receive all type of events CosNotification::EventTypeSeq added(1); CosNotification::EventTypeSeq removed (0); added.length (1); removed.length (0); added[0].domain_name = CORBA::string_dup ("*"); added[0].type_name = CORBA::string_dup ("*"); this->consumer_admin_->subscription_change (added, removed); ACE_NEW_THROW_EX (this->my_log_consumer_, TAO_Notify_LogConsumer (this), CORBA::NO_MEMORY ()); this->my_log_consumer_->connect (this->consumer_admin_.in ()); } //IDL to C++ CosNotifyFilter::Filter_ptr TAO_NotifyLog_i::get_filter (void) { //TODO: need to add impl throw CORBA::NO_IMPLEMENT (); } void TAO_NotifyLog_i::set_filter (CosNotifyFilter::Filter_ptr /* filter */) { throw CORBA::NO_IMPLEMENT (); //TODO: need to add impl } CosNotifyChannelAdmin::EventChannelFactory_ptr TAO_NotifyLog_i::MyFactory (void) { //TODO: need to add impl throw CORBA::NO_IMPLEMENT (); } CosNotifyChannelAdmin::ConsumerAdmin_ptr TAO_NotifyLog_i::default_consumer_admin (void) { return this->event_channel_->default_consumer_admin (); } CosNotifyChannelAdmin::SupplierAdmin_ptr TAO_NotifyLog_i::default_supplier_admin (void) { return this->event_channel_->default_supplier_admin (); } CosNotifyFilter::FilterFactory_ptr TAO_NotifyLog_i::default_filter_factory (void) { return this->event_channel_->default_filter_factory (); } CosNotifyChannelAdmin::ConsumerAdmin_ptr TAO_NotifyLog_i::new_for_consumers (CosNotifyChannelAdmin::InterFilterGroupOperator op, CosNotifyChannelAdmin::AdminID& id) { return this->event_channel_->new_for_consumers (op,id); } CosNotifyChannelAdmin::SupplierAdmin_ptr TAO_NotifyLog_i::new_for_suppliers (CosNotifyChannelAdmin::InterFilterGroupOperator op, CosNotifyChannelAdmin::AdminID& id) { return this->event_channel_->new_for_suppliers (op,id); } CosNotifyChannelAdmin::ConsumerAdmin_ptr TAO_NotifyLog_i::get_consumeradmin (CosNotifyChannelAdmin::AdminID id) { return this->event_channel_->get_consumeradmin (id); } CosNotifyChannelAdmin::SupplierAdmin_ptr TAO_NotifyLog_i::get_supplieradmin (CosNotifyChannelAdmin::AdminID id) { return this->event_channel_->get_supplieradmin (id); } CosNotifyChannelAdmin::AdminIDSeq* TAO_NotifyLog_i::get_all_consumeradmins (void) { return this->event_channel_->get_all_consumeradmins (); } CosNotifyChannelAdmin::AdminIDSeq* TAO_NotifyLog_i::get_all_supplieradmins (void) { return this->event_channel_->get_all_supplieradmins (); } CosNotification::AdminProperties* TAO_NotifyLog_i::get_admin (void) { return this->event_channel_->get_admin (); } void TAO_NotifyLog_i::set_admin (const CosNotification::AdminProperties& admin) { this->event_channel_->set_admin (admin); } CosNotification::QoSProperties* TAO_NotifyLog_i::get_qos (void) { //need to add merging of QoS from Log_i and EventChannel_i throw CORBA::NO_IMPLEMENT (); } void TAO_NotifyLog_i::set_qos (const CosNotification::QoSProperties& /* qos */) { throw CORBA::NO_IMPLEMENT (); //TODO: need to add later } void TAO_NotifyLog_i::validate_qos ( const CosNotification::QoSProperties& /* required_qos */, CosNotification::NamedPropertyRangeSeq_out /* available_qos */) { throw CORBA::NO_IMPLEMENT (); //TODO: need to add later } CosEventChannelAdmin::ConsumerAdmin_ptr TAO_NotifyLog_i::for_consumers (void) { return this->event_channel_->for_consumers(); } CosEventChannelAdmin::SupplierAdmin_ptr TAO_NotifyLog_i::for_suppliers ( ) { return this->event_channel_->for_suppliers(); } TAO_END_VERSIONED_NAMESPACE_DECL
mit
billogram/billogram-v2-api-python-lib
billogram_api.py
28667
# encoding=utf-8 # Copyright (c) 2013 Billogram AB # # 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. "Library for accessing the Billogram v2 HTTP API" from __future__ import unicode_literals, print_function, division import requests import json API_URL_BASE = "https://billogram.com/api/v2" USER_AGENT = "Billogram API Python Library/1.00" # python 2/3 intercompatibility try: unicode # not defined in py3k def _printable_repr(s): # python 2.7 can't handle unicode objects from __repr__ # so need this wrapper return s.encode('utf-8') except NameError: basestring = str # py3k has no basestring type so fake one def _printable_repr(s): return s class BillogramAPIError(Exception): "Base class for errors from the Billogram API" def __init__(self, message, **kwargs): super(BillogramAPIError, self).__init__(message) self.field = kwargs.get('field', None) self.field_path = kwargs.get('field_path', None) self.extra_data = kwargs if 'field' in self.extra_data: del self.extra_data['field'] if 'field_path' in self.extra_data: del self.extra_data['field_path'] if not self.extra_data: self.extra_data = None class ServiceMalfunctioningError(BillogramAPIError): "The Billogram API service seems to be malfunctioning" pass class RequestFormError(BillogramAPIError): "Errors caused by malformed requests" pass class PermissionDeniedError(BillogramAPIError): "No permission to perform the requested operation" pass class InvalidAuthenticationError(PermissionDeniedError): "The user/key combination could not be authenticated" pass class NotAuthorizedError(PermissionDeniedError): "The user does not have authorization to perform the requested operation" pass class RequestDataError(BillogramAPIError): "Errors caused by bad data passed to request" pass class UnknownFieldError(RequestDataError): "An unknown field was passed in the request data" pass class MissingFieldError(RequestDataError): "A required field was missing from the request data" pass class InvalidFieldCombinationError(RequestDataError): "Mutually exclusive fields were specified together" pass class InvalidFieldValueError(RequestDataError): "A field was given an out-of-range value or a value of incorrect type" pass class ReadOnlyFieldError(RequestDataError): "Attempt to modify a read-only field" pass class InvalidObjectStateError(RequestDataError): "The request can not be performed on an object in this state" pass class ObjectNotFoundError(RequestDataError): "No object by the requested ID exists" pass class ObjectNotAvailableYetError(ObjectNotFoundError): "No object by the requested ID exists, but is expected to be created soon" pass class BillogramAPI(object): """Pseudo-connection to the Billogram v2 API Objects of this class provide a call interface to the Billogram v2 HTTP API. """ def __init__(self, auth_user, auth_key, user_agent=None, api_base=None): """Create a Billogram API connection object Pass the API authentication in the auth_user and auth_key parameters. API accounts can only be created from the Billogram web interface. """ self._auth = (auth_user, auth_key) self._items = None self._customers = None self._billogram = None self._settings = None self._logotype = None self._reports = None self._user_agent = user_agent or USER_AGENT self._api_base = api_base or API_URL_BASE @property def items(self): "Provide access to the items database" if self._items is None: self._items = SimpleClass(self, 'item', 'item_no') return self._items @property def customers(self): "Provide access to the customer database" if self._customers is None: self._customers = SimpleClass(self, 'customer', 'customer_no') return self._customers @property def billogram(self): "Provide access to billogram objects and attached invoices" if self._billogram is None: self._billogram = BillogramClass(self) return self._billogram @property def settings(self): "Provide access to settings for the Billogram account" if self._settings is None: self._settings = SingletonObject(self, 'settings') return self._settings @property def logotype(self): "Provide access to the logotype for the Billogram account" if self._logotype is None: self._logotype = SingletonObject(self, 'logotype') return self._logotype @property def reports(self): "Provide access to the reports database" if self._reports is None: self._reports = SimpleClass(self, 'report', 'filename') return self._reports @classmethod def _check_api_response(cls, resp, expect_content_type=None): if not resp.ok or expect_content_type is None: # if the request failed the response should always be json expect_content_type = 'application/json' if resp.status_code in range(500, 600): # internal error if resp.headers['content-type'] == expect_content_type and \ expect_content_type == 'application/json': data = resp.json() raise ServiceMalfunctioningError( 'Billogram API reported a server error: {} - {}'.format( data.get('status'), data.get('data').get('message') ) ) raise ServiceMalfunctioningError( 'Billogram API reported a server error' ) if resp.headers['content-type'] != expect_content_type: # the service returned a different content-type from the expected, # probably some malfunction on the remote end if resp.headers['content-type'] == 'application/json': data = resp.json() if data.get('status') == 'NOT_AVAILABLE_YET': raise ObjectNotAvailableYetError( 'Object not available yet' ) raise ServiceMalfunctioningError( 'Billogram API returned unexpected content type' ) if expect_content_type == 'application/json': data = resp.json() status = data.get('status') if not status: raise ServiceMalfunctioningError( 'Response data missing status field' ) if not 'data' in data: raise ServiceMalfunctioningError( 'Response data missing data field' ) else: # per above, non-json responses are always ok, so just return them return resp.content if resp.status_code == 403: # bad auth if status == 'PERMISSION_DENIED': raise NotAuthorizedError( 'Not allowed to perform the requested operation' ) elif status == 'INVALID_AUTH': raise InvalidAuthenticationError( 'The user/key combination is wrong, check the credentials \ used and possibly generate a new set' ) elif status == 'MISSING_AUTH': raise RequestFormError('No authentication data was given') else: raise PermissionDeniedError( 'Permission denied, status={}'.format( status ) ) if resp.status_code == 404: # not found if data.get('status') == 'NOT_AVAILABLE_YET': raise ObjectNotFoundError('Object not available yet') raise ObjectNotFoundError('Object not found') if resp.status_code == 405: # bad http method raise RequestFormError('Invalid HTTP method') if status == 'OK': return data errordata = data.get('data', {}) raise { 'MISSING_QUERY_PARAMETER': RequestFormError, 'INVALID_QUERY_PARAMETER': RequestFormError, 'INVALID_PARAMETER': InvalidFieldValueError, 'INVALID_PARAMETER_COMBINATION': InvalidFieldCombinationError, 'READ_ONLY_PARAMETER': ReadOnlyFieldError, 'UNKNOWN_PARAMETER': UnknownFieldError, 'INVALID_OBJECT_STATE': InvalidObjectStateError, }.get(status, RequestDataError)(**errordata) def get(self, obj, params=None, expect_content_type=None): "Perform a HTTP GET request to the Billogram API" url = '{}/{}'.format(self._api_base, obj) return self._check_api_response( requests.get( url, auth=self._auth, params=params, headers={'user-agent': self._user_agent} ), expect_content_type=expect_content_type ) def post(self, obj, data): "Perform a HTTP POST request to the Billogram API" url = '{}/{}'.format(self._api_base, obj) return self._check_api_response( requests.post( url, auth=self._auth, data=json.dumps(data), headers={ 'content-type': 'application/json', 'user-agent': self._user_agent } ) ) def put(self, obj, data): "Perform a HTTP PUT request to the Billogram API" url = '{}/{}'.format(self._api_base, obj) return self._check_api_response( requests.put( url, auth=self._auth, data=json.dumps(data), headers={ 'content-type': 'application/json', 'user-agent': self._user_agent } ) ) def delete(self, obj): "Perform a HTTP DELETE request to the Billogram API" url = '{}/{}'.format(self._api_base, obj) return self._check_api_response( requests.delete( url, auth=self._auth, headers={'user-agent': self._user_agent} ) ) class SingletonObject(object): """Represents a remote singleton object on Billogram Implements __getattr__ for dict-like access to the data of the remote object, or use the 'data' property to access the backing dict object. The data in this dict and all sub-objects should be treated as read-only, the only way to change the remote object is through the 'update' method. The represented object is initially "lazy" and will only be fetched on the first access. If the remote data are changed, the local copy can be updated bythe 'refresh' method. See the online documentation for the actual structure of remote objects. """ def __init__(self, api, url_name): self._api = api self._object_class = url_name self._data = None __slots__ = ('_api', '_object_class', '_data') def __getitem__(self, key): "Dict-like access to object data" return self.data[key] def __repr__(self): return _printable_repr( "<Billogram object '{}'{}>".format( self._url, (self._data is None) and ' (lazy)' or '' ) ) @property def _url(self): return self._object_class @property def data(self): "Access the data of the actual object" if self._data is None: self.refresh() return self._data def refresh(self): "Refresh the local copy of the object data from remote" resp = self._api.get(self._url) self._data = resp['data'] return self def update(self, data): "Modify the remote object with a partial or complete structure" resp = self._api.put(self._url, data) self._data = resp['data'] return self class SimpleObject(SingletonObject): """Represents a remote object on the Billogram service Implements __getattr__ for dict-like access to the data of the remote object, or use the 'data' property to access the backing dict object. The data in this dict and all sub-objects should be treated as read-only, the only way to change the remote object is through the 'update' method. If the remote data are changed, the local copy can be updated by the 'refresh' method. The 'delete' method can be used to remove the backing object. See the online documentation for the actual structure of remote objects. """ def __init__(self, api, object_class, data): self._api = api self._object_class = object_class self._data = data __slots__ = () @property def _url(self): return self._object_class._url_of(self) def __getattr__(self, key): return self._data[key] def delete(self): "Remove the remote object from the database" self._api.delete(self._url) return None class Query(object): """Builds queries and fetches pages of remote objects Due to internal limitations in Billogram it is currently only possible to filter on a single field or special query at a time. This may change in the future. When it does the API will continue supporting the old filtering mechanism, however this client library will be updated to use the new one, and at that point we will strongly recommend all applications be updated. The exact fields and special queries available for each object type varies, see the online documentation for details. """ def __init__(self, type_class): self._type_class = type_class self._filter = {} self._count_cached = None self._page_size = 100 self._order = {} def _make_query(self, page_number=1, page_size=None): query_args = { 'page_size': page_size or self._page_size, 'page': page_number, } query_args.update(self._get_queryargs()) resp = self._type_class.api.get(self._type_class._url_name, query_args) self._count_cached = resp['meta']['total_count'] return resp def _get_queryargs(self): args = {} args.update(self.filter) args.update(self.order) return args @property def count(self): """Total amount of objects matched by the current query, reading this may cause a remote request""" if self._count_cached is None: # make a query for a single result, # this will update the cached count self._make_query(1, 1) return self._count_cached @property def total_pages(self): """Total number of pages required for all objects based on current pagesize, reading this may cause a remote request""" return (self.count + self.page_size - 1) // self.page_size @property def page_size(self): "Number of objects to return per page" return self._page_size @page_size.setter def page_size(self, value): value = int(value) assert value >= 1 self._page_size = value return self @property def filter(self): "Filter to apply to query" return self._filter @filter.setter def filter(self, value): if value == self._filter: return if value: assert 'filter_type' in value and \ 'filter_field' in value and \ 'filter_value' in value assert value['filter_type'] in ( 'field', 'field-prefix', 'field-search', 'special' ) self._filter = dict(value) else: self._filter = {} self._count_cached = None return self @property def order(self): return self._order @order.setter def order(self, value): if value: assert 'order_field' in value and 'order_direction' in value assert value['order_direction'] in ('asc', 'desc') self._order = dict(value) else: self._order = {} return self def make_filter(self, filter_type=None, filter_field=None, filter_value=None): if None in (filter_type, filter_field, filter_value): self.filter = {} else: self.filter = { 'filter_type': filter_type, 'filter_field': filter_field, 'filter_value': filter_value } return self def remove_filter(self): "Remove any filter currently set" self.filter = {} return self def filter_field(self, filter_field, filter_value): "Filter on a basic field, look for exact matches" return self.make_filter('field', filter_field, filter_value) def filter_prefix(self, filter_field, filter_value): "Filter on a basic field, look for prefix matches" return self.make_filter('field-prefix', filter_field, filter_value) def filter_search(self, filter_field, filter_value): "Filter on a basic field, look for substring matches" return self.make_filter('field-search', filter_field, filter_value) def filter_special(self, filter_field, filter_value): "Filter on a special query" return self.make_filter('special', filter_field, filter_value) def search(self, search_terms): "Filter by a full data search (exact meaning depends on object type)" return self.make_filter('special', 'search', search_terms) def get_page(self, page_number): "Fetch objects for the one-based page number" resp = self._make_query(int(page_number)) return [ self._type_class._object_class( self._type_class.api, self._type_class, o ) for o in resp['data'] ] def iter_all(self): "Iterate over all matched objects" # make a copy of ourselves so parameters can't be changed behind # our back import copy qry = copy.copy(self) # iterate over every object on every page for page_number in range(1, qry.total_pages+1): page = qry.get_page(page_number) for obj in page: yield obj class SimpleClass(object): """Represents a collection of remote objects on the Billogram service Provides methods to search, fetch and create instances of the object type. See the online documentation for the actual structure of remote objects. """ _object_class = SimpleObject def __init__(self, api, url_name, object_id_field): self._api = api self._url_name = url_name self._object_id_field = object_id_field def _url_of(self, obj=None, obj_id=None): if obj_id is None: obj_id = obj[self._object_id_field] return '{}/{}'.format(self.url_name, obj_id) @property def url_name(self): return self._url_name @property def api(self): return self._api def query(self): "Create a query for objects of this type" return Query(self) def get(self, object_id): "Fetch a single object by its identification" resp = self.api.get(self._url_of(obj_id=object_id)) return self._object_class(self.api, self, resp['data']) def create(self, data): "Create a new object with the given data" resp = self.api.post(self.url_name, data) return self._object_class(self.api, self, resp['data']) class BillogramObject(SimpleObject): """Represents a billogram object on the Billogram service In addition to the basic methods of the SimpleObject remote object class, also provides specialized methods to perform events on billogram objects. See the online documentation for the actual structure of billogram objects. """ __slots__ = () def perform_event(self, evt_name, evt_data=None): """Perform a generic state transition event on billogram object """ url = '{}/command/{}'.format(self._url, evt_name) resp = self._api.post(url, evt_data) self._data = resp['data'] return self def create_payment(self, amount): """Create a manual payment on billogram Only possible in "Unpaid" state. """ assert amount > 0 return self.perform_event('payment', {'amount': amount}) def credit_amount(self, amount): """Credit a specific amount of the billogram Only possible in states "Unpaid", "Sold" and "Ended". """ assert amount > 0 return self.perform_event( 'credit', { 'mode': 'amount', 'amount': amount } ) def credit_full(self): """Credit the full, original amount of the billogram Only possible in states "Unpaid", "Sold" and "Ended". """ return self.perform_event('credit', {'mode': 'full'}) def credit_remaining(self): """Credit the remaining unpaid amount of the billogram Only possible in states "Unpaid", "Sold" and "Ended". """ return self.perform_event('credit', {'mode': 'remaining'}) def send_message(self, message): """Send a message to the recipient of the billogram Possible from all states, except on deleted billograms. """ return self.perform_event('message', {'message': message}) def send_to_collector(self): """Send the billogram to the collection agency Only possible from state "Unpaid". """ return self.perform_event('collect') def send_to_factoring(self): """Send the billogram to the factoring agency to be sold Only possible from state "Unattested". """ return self.perform_event('sell') def send_reminder(self, method=None): """Send a reminder to the recipient 'method' is the type of reminder to be sent: - "Email" - "Letter". Only possible from state "Unpaid". """ if method: assert method in ('Email', 'Letter') return self.perform_event('remind', {'method': method}) return self.perform_event('remind') def send(self, method): """Send the billogram to the recipient 'method' is the medium to send the billogram by: - "Email" - "Letter" - "Email+Letter". Only possible from state "Unattested". """ assert method in ('Email', 'Letter', 'Email+Letter') return self.perform_event('send', {'method': method}) def resend(self, method=None): """Send the billogram to the recipient again 'method' is the medium to send the billogram by: - "Email" - "Letter". Only possible from state "Unpaid". """ if method: assert method in ('Email', 'Letter') return self.perform_event('resend', {'method': method}) return self.perform_event('resend') def get_invoice_pdf(self, letter_id=None, invoice_no=None): """Fetch the PDF content for a specific invoice on this billogram """ import base64 url = '{}.pdf'.format(self._url) params = {} if letter_id: params['letter_id'] = letter_id if invoice_no: params['invoice_no'] = invoice_no resp = self._api.get( url, params, expect_content_type='application/json' ) return base64.b64decode(resp['data']['content']) def get_attachment_pdf(self, letter_id=None, invoice_no=None): """Fetch the PDF attachment for the billogram """ import base64 url = '{}/attachment.pdf'.format(self._url) resp = self._api.get(url, expect_content_type='application/json') return base64.b64decode(resp['data']['content']) def attach_pdf(self, filepath): """Attach a PDF to the billogram """ import base64 import os with file(filepath) as f: content = f.read() filename = os.path.basename(filepath) return self.perform_event( 'attach', { 'content': base64.b64encode(content), 'filename': filename } ) def writeoff(self): """Write-off remaining fees from a billogram. """ return self.perform_event('writeoff') class BillogramQuery(Query): """Represents a query for billogram objects """ def filter_state_any(self, *states): "Find billogram objects with any state of the listed ones" if len(states) == 1 and ( isinstance(states[0], list) or isinstance(states[0], tuple) or isinstance(states[0], set) or isinstance(states[0], frozenset) ): states = states[0] assert all(isinstance(s, basestring) for s in states) return self.filter_field('state', ','.join(states)) class BillogramClass(SimpleClass): """Represents the collection of billogram objects on the Billogram service In addition to the methods of the SimpleClass collection wrapper, also provides specialized creation methods to create billogram objects and state transition them immediately. """ _object_class = BillogramObject def __init__(self, api): super(BillogramClass, self).__init__(api, 'billogram', 'id') def query(self): "Create a query for billogram objects" return BillogramQuery(self) def create_and_send(self, data, method): """Create the billogram and send it to the recipient in one operation 'method' is the medium to send the billogram by: - "Email" - "Letter" - "Email+Letter". New billogram will be in state "Unpaid" or "Ended" (if the total sum would be zero). """ assert method in ('Email', 'Letter', 'Email+Letter') billogram = self.create(data) try: billogram.send(method) except Exception as e: billogram.delete() raise e return billogram def create_and_sell(self, data): """Create the billogram and send it to factoring in one operation New billogram will be in state "Factoring". """ data['_event'] = 'sell' billogram = self.create(data) return billogram # make an exportable namespace-class with all the exceptions BillogramExceptions = type( str('BillogramExceptions'), (), { nm: cl for nm, cl in globals().items() if isinstance(cl, type) and issubclass(cl, BillogramAPIError) } ) # just the BillogramAPI class and the exceptions are really part # of the call API of this module __all__ = ['BillogramAPI', 'BillogramExceptions']
mit
harrischristiansen/MembersPortal
app/Models/LocationRecord.php
499
<?php /* @ Harris Christiansen (Harris@HarrisChristiansen.com) 2016-05-02 Project: Members Tracking Portal */ namespace App\Models; use Illuminate\Database\Eloquent\Model; class LocationRecord extends Model { protected $table = 'location-member'; public function member() { return $this->hasOne('App\Models\Member', 'id', 'member_id'); } public function location() { return $this->hasOne('App\Models\Location', 'id', 'location_id'); } }
mit
mintern/xregexp-quotemeta
test.js
397
const assert = require("assert"); const XRegExp = require("xregexp"); const quotemeta = require("./xregexp-quotemeta"); quotemeta.addSupportTo(XRegExp); assert(XRegExp('^\\Q(?*+)').test('(?*+)')); assert(XRegExp('^\\Q.\\E.').test('.x')); assert(!XRegExp('^\\Q.\\E.').test('xx')); assert(XRegExp('^\\Q\\E$').test('')); assert(!XRegExp('^\\Q\\E$').test('x')); assert.throws(() => XRegExp('\\E'));
mit
samael205/ExcelPHP
PhpSpreadsheet/Style/Borders.php
12189
<?php namespace PhpOffice\PhpSpreadsheet\Style; /** * Copyright (c) 2006 - 2016 PhpSpreadsheet * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * @category PhpSpreadsheet * @copyright Copyright (c) 2006 - 2016 PhpSpreadsheet (https://github.com/PHPOffice/PhpSpreadsheet) * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL * @version ##VERSION##, ##DATE## */ class Borders extends Supervisor implements \PhpOffice\PhpSpreadsheet\IComparable { /* Diagonal directions */ const DIAGONAL_NONE = 0; const DIAGONAL_UP = 1; const DIAGONAL_DOWN = 2; const DIAGONAL_BOTH = 3; /** * Left * * @var Border */ protected $left; /** * Right * * @var Border */ protected $right; /** * Top * * @var Border */ protected $top; /** * Bottom * * @var Border */ protected $bottom; /** * Diagonal * * @var Border */ protected $diagonal; /** * DiagonalDirection * * @var int */ protected $diagonalDirection; /** * All borders psedo-border. Only applies to supervisor. * * @var Border */ protected $allBorders; /** * Outline psedo-border. Only applies to supervisor. * * @var Border */ protected $outline; /** * Inside psedo-border. Only applies to supervisor. * * @var Border */ protected $inside; /** * Vertical pseudo-border. Only applies to supervisor. * * @var Border */ protected $vertical; /** * Horizontal pseudo-border. Only applies to supervisor. * * @var Border */ protected $horizontal; /** * Create a new Borders * * @param bool $isSupervisor Flag indicating if this is a supervisor or not * Leave this value at default unless you understand exactly what * its ramifications are * @param bool $isConditional Flag indicating if this is a conditional style or not * Leave this value at default unless you understand exactly what * its ramifications are */ public function __construct($isSupervisor = false, $isConditional = false) { // Supervisor? parent::__construct($isSupervisor); // Initialise values $this->left = new Border($isSupervisor, $isConditional); $this->right = new Border($isSupervisor, $isConditional); $this->top = new Border($isSupervisor, $isConditional); $this->bottom = new Border($isSupervisor, $isConditional); $this->diagonal = new Border($isSupervisor, $isConditional); $this->diagonalDirection = self::DIAGONAL_NONE; // Specially for supervisor if ($isSupervisor) { // Initialize pseudo-borders $this->allBorders = new Border(true); $this->outline = new Border(true); $this->inside = new Border(true); $this->vertical = new Border(true); $this->horizontal = new Border(true); // bind parent if we are a supervisor $this->left->bindParent($this, 'left'); $this->right->bindParent($this, 'right'); $this->top->bindParent($this, 'top'); $this->bottom->bindParent($this, 'bottom'); $this->diagonal->bindParent($this, 'diagonal'); $this->allBorders->bindParent($this, 'allBorders'); $this->outline->bindParent($this, 'outline'); $this->inside->bindParent($this, 'inside'); $this->vertical->bindParent($this, 'vertical'); $this->horizontal->bindParent($this, 'horizontal'); } } /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor * * @return Borders */ public function getSharedComponent() { return $this->parent->getSharedComponent()->getBorders(); } /** * Build style array from subcomponents * * @param array $array * @return array */ public function getStyleArray($array) { return ['borders' => $array]; } /** * Apply styles from array * * <code> * $spreadsheet->getActiveSheet()->getStyle('B2')->getBorders()->applyFromArray( * array( * 'bottom' => array( * 'style' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_DASHDOT, * 'color' => array( * 'rgb' => '808080' * ) * ), * 'top' => array( * 'style' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_DASHDOT, * 'color' => array( * 'rgb' => '808080' * ) * ) * ) * ); * </code> * <code> * $spreadsheet->getActiveSheet()->getStyle('B2')->getBorders()->applyFromArray( * array( * 'allborders' => array( * 'style' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_DASHDOT, * 'color' => array( * 'rgb' => '808080' * ) * ) * ) * ); * </code> * * @param array $pStyles Array containing style information * @throws \PhpOffice\PhpSpreadsheet\Exception * @return Borders */ public function applyFromArray($pStyles = null) { if (is_array($pStyles)) { if ($this->isSupervisor) { $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); } else { if (isset($pStyles['left'])) { $this->getLeft()->applyFromArray($pStyles['left']); } if (isset($pStyles['right'])) { $this->getRight()->applyFromArray($pStyles['right']); } if (isset($pStyles['top'])) { $this->getTop()->applyFromArray($pStyles['top']); } if (isset($pStyles['bottom'])) { $this->getBottom()->applyFromArray($pStyles['bottom']); } if (isset($pStyles['diagonal'])) { $this->getDiagonal()->applyFromArray($pStyles['diagonal']); } if (isset($pStyles['diagonaldirection'])) { $this->setDiagonalDirection($pStyles['diagonaldirection']); } if (isset($pStyles['allborders'])) { $this->getLeft()->applyFromArray($pStyles['allborders']); $this->getRight()->applyFromArray($pStyles['allborders']); $this->getTop()->applyFromArray($pStyles['allborders']); $this->getBottom()->applyFromArray($pStyles['allborders']); } } } else { throw new \PhpOffice\PhpSpreadsheet\Exception('Invalid style array passed.'); } return $this; } /** * Get Left * * @return Border */ public function getLeft() { return $this->left; } /** * Get Right * * @return Border */ public function getRight() { return $this->right; } /** * Get Top * * @return Border */ public function getTop() { return $this->top; } /** * Get Bottom * * @return Border */ public function getBottom() { return $this->bottom; } /** * Get Diagonal * * @return Border */ public function getDiagonal() { return $this->diagonal; } /** * Get AllBorders (pseudo-border). Only applies to supervisor. * * @throws \PhpOffice\PhpSpreadsheet\Exception * @return Border */ public function getAllBorders() { if (!$this->isSupervisor) { throw new \PhpOffice\PhpSpreadsheet\Exception('Can only get pseudo-border for supervisor.'); } return $this->allBorders; } /** * Get Outline (pseudo-border). Only applies to supervisor. * * @throws \PhpOffice\PhpSpreadsheet\Exception * @return bool */ public function getOutline() { if (!$this->isSupervisor) { throw new \PhpOffice\PhpSpreadsheet\Exception('Can only get pseudo-border for supervisor.'); } return $this->outline; } /** * Get Inside (pseudo-border). Only applies to supervisor. * * @throws \PhpOffice\PhpSpreadsheet\Exception * @return bool */ public function getInside() { if (!$this->isSupervisor) { throw new \PhpOffice\PhpSpreadsheet\Exception('Can only get pseudo-border for supervisor.'); } return $this->inside; } /** * Get Vertical (pseudo-border). Only applies to supervisor. * * @throws \PhpOffice\PhpSpreadsheet\Exception * @return Border */ public function getVertical() { if (!$this->isSupervisor) { throw new \PhpOffice\PhpSpreadsheet\Exception('Can only get pseudo-border for supervisor.'); } return $this->vertical; } /** * Get Horizontal (pseudo-border). Only applies to supervisor. * * @throws \PhpOffice\PhpSpreadsheet\Exception * @return Border */ public function getHorizontal() { if (!$this->isSupervisor) { throw new \PhpOffice\PhpSpreadsheet\Exception('Can only get pseudo-border for supervisor.'); } return $this->horizontal; } /** * Get DiagonalDirection * * @return int */ public function getDiagonalDirection() { if ($this->isSupervisor) { return $this->getSharedComponent()->getDiagonalDirection(); } return $this->diagonalDirection; } /** * Set DiagonalDirection * * @param int $pValue * @return Borders */ public function setDiagonalDirection($pValue = self::DIAGONAL_NONE) { if ($pValue == '') { $pValue = self::DIAGONAL_NONE; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['diagonaldirection' => $pValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->diagonalDirection = $pValue; } return $this; } /** * Get hash code * * @return string Hash code */ public function getHashCode() { if ($this->isSupervisor) { return $this->getSharedComponent()->getHashcode(); } return md5( $this->getLeft()->getHashCode() . $this->getRight()->getHashCode() . $this->getTop()->getHashCode() . $this->getBottom()->getHashCode() . $this->getDiagonal()->getHashCode() . $this->getDiagonalDirection() . __CLASS__ ); } }
mit
tsisociesc/bombeiro-comunitario
admin/assets/src/PFBC/Element/File.php
1643
<?php namespace PFBC\Element; class File extends \PFBC\Element { protected $_attributes = array( "type" => "file", "actSelect" => "Selecionar arquivo", "actRemove" => 'Remover', "actUpdate" => "Alterar", ); public function __construct($label, $name, array $properties = null) { $properties = array_merge_recursive_distinct($this->_attributes, $properties); return parent::__construct($label, $name, $properties); } public function render() { $html = ' <div class="fileinput fileinput-new" data-provides="fileinput"> <div class="input-group"> <div class="form-control uneditable-input" data-trigger="fileinput"> <i class="fa fa-file fileinput-exists"></i> &nbsp; <span class="fileinput-filename"></span> </div> <span class="input-group-addon btn btn-default btn-file"> <span class="fileinput-new">' . $this->_attributes['actSelect'] . '</span> <span class="fileinput-exists">' . $this->_attributes['actUpdate'] . '</span> <input type="file" name="' . $this->_attributes['name'] . '" /> </span> <a href="#" class="input-group-addon btn btn-default fileinput-exists" data-dismiss="fileinput">' . $this->_attributes['actRemove'] . '</a> </div> </div> '; return $html; } }
mit
the01/python-sallie
src/sallie/next_tvdb.py
8625
# -*- coding: UTF-8 -*- """ TVNext implementation for tvdb """ __author__ = "d01" __copyright__ = "Copyright (C) 2016-20, Florian JUNG" __license__ = "MIT" __version__ = "0.2.10" __date__ = "2020-06-15" # Created: 2015-04-29 19:15 import datetime import difflib import typing import dateutil import dateutil.parser import flotils import pytz import tvdb_api from .tv_next import TVNext, TVNextNotFoundException logger = flotils.get_logger() class TVNextTVDB(TVNext): """ Check tv shows with tvdb """ class TVDBUI(tvdb_api.BaseUI): """ Class to select a show based on year """ # pylint: disable=invalid-name current = None def selectSeries(self, allSeries): # noqa: N802, N803 """ Select a series """ tvnext = self.config['tvnext'] """ :type : TVNextTVDB """ key = self.current['key'] year = self.current.get('year') allSeries = [ # noqa: N806 ( series, difflib.SequenceMatcher( None, key, series.get('seriesName', "") ).ratio() ) for series in allSeries ] allSeries.sort(key=lambda x: x[1], reverse=True) tvnext.debug( "Options: {}".format(",".join([ "{} ({:.2f})".format(series.get('seriesName'), ratio) for series, ratio in allSeries ])) ) parts = key.split() if year: year = parts[-1][1:-1] for series, _ratio in allSeries: if series.get('firstAired') and \ series['firstAired'].split('-')[0] == year: # Same year -> assume this one return series return allSeries[0][0] def __init__( self, settings: typing.Optional[typing.Dict[str, typing.Any]] = None ) -> None: """ Initialise instance :param settings: Settings """ if settings is None: settings = {} super().__init__(settings) cache = True if self._cache_path: cache = self._cache_path self.debug("Using cache at {}".format(self._cache_path)) self.debug("Using cache file {}".format(self._cache_file)) self._tvdb_cache = cache self._tvdb = None self._tvdb_api_key = settings['tvdb_api_key'] self._init_tvdb() def _init_tvdb(self) -> None: """ Init tvdb instance """ self.debug("Initializing tvdb instance..") self._tvdb = tvdb_api.Tvdb( cache=self._tvdb_cache, custom_ui=self.TVDBUI, apikey=self._tvdb_api_key ) if self._tvdb_cache: # Fix tvdb_api bug self._tvdb.config['cache_enabled'] = True else: self._tvdb.config['cache_enabled'] = False self._tvdb.authorize() self._tvdb.config['tvnext'] = self self.info("TVDB instance initialized") def _key_error_retry(self, key: str, reauthorized: bool = False) -> typing.Any: """ Retry Upon key error :param key: Key to retry :return: Found data """ if self._tvdb is None: self._init_tvdb() try: return self._tvdb[key] except tvdb_api.tvdb_error as e: if "not authorized" in str(e).lower() and not reauthorized: self._tvdb.authorize() return self._key_error_retry(key, reauthorized=True) raise except KeyError as e: self.warning("{}: Key error '{}'".format(key, e)) self._init_tvdb() return self._tvdb[key] def _show_update(self, key: str) -> bool: """ Update show (and adds it if not already present) :param key: Show name :return: Changed (Might not really have changed - but successfull read) """ self.debug("Updating {}..".format(key)) show = self._shows.setdefault(key, {}) now = pytz.utc.localize(datetime.datetime.utcnow()) year = None year_part = key.split()[-1] if year_part.startswith("(") and year_part.endswith(")"): # Assume year info year = year_part[1:-1] self.TVDBUI.current = { 'key': key, 'year': year, } try: tvdb_show = self._key_error_retry(key) except tvdb_api.tvdb_shownotfound as e: if year: # Assume year info new_key = " ".join(key.split()[:-1]) self.info("Trying {} instead..".format(new_key)) # Try without year info try: tvdb_show = self._tvdb[new_key] except tvdb_api.tvdb_shownotfound as e2: self.error("Show {}: {}".format(new_key, e2)) raise TVNextNotFoundException(new_key) else: self.error("Show {}: {}".format(key, e)) raise TVNextNotFoundException(key) # self.debug("{}".format(tvdb_show)) # for key, item in tvdb_show.data.items(): # self.debug("\n {}: {}".format(key, item)) # for key, item in tvdb_show.items(): # self.debug("\n {}: {}".format(key, item)) # for item in tvdb_show[0][1].keys(): # self.debug("\n {}: {}".format(item, tvdb_show[0][1][item])) show['id_tvdb'] = tvdb_show['id'] show['id_imdb'] = tvdb_show['imdbId'] show['name'] = tvdb_show['seriesname'] show['overview'] = tvdb_show['overview'] show['status'] = tvdb_show.data.get('status', "").upper() show['active'] = show['status'] != "ENDED" show['hiatus'] = False show['air_duration'] = tvdb_show['runtime'] show['air_day'] = tvdb_show['airsDayOfWeek'] show['air_time'] = tvdb_show['airsTime'] show.setdefault('air_timezone', self._timezone) if isinstance(show['air_timezone'], str): show['air_timezone'] = pytz.timezone(show['air_timezone']) if show['air_time']: show['air_time'] = dateutil.parser.parse(show['air_time']).time() # Either correct time # or last possible second on that day (-> upper bound) air_time = show['air_time'] or datetime.time(23, 59, 59) episodes = {} for season_nr in tvdb_show: episodes.setdefault(season_nr, {}) # episode db id name: id_<unique_name_for_source> for episode_nr in tvdb_show[season_nr]: # for key, item in tvdb_show[season_nr][episode_nr].items(): # self.debug("\nep: {}: {}".format(key, item)) episodes[season_nr][episode_nr] = { 'id_tvdb': tvdb_show[season_nr][episode_nr]['id'], 'id_imdb': tvdb_show[season_nr][episode_nr]['imdbId'], 'aired': None, 'name': tvdb_show[season_nr][episode_nr]['episodeName'], 'id': u"{:02d}x{:02d}".format(season_nr, episode_nr) } aired = tvdb_show[season_nr][episode_nr]['firstAired'] if aired: # Use datetime instead of date for tz info localization try: aired = dateutil.parser.parse(aired) except Exception: if aired == "0000-00-00": self.error("Invalid aired date: {}-{}x{}".format( key, season_nr, episode_nr )) else: self.exception("Failed to parse date: {}".format( aired )) aired = None if aired and air_time: aired = datetime.datetime.combine( aired.date(), air_time ) # Set origin tz aired = show['air_timezone'].localize(aired) # Convert to utc aired = aired.astimezone(pytz.utc) episodes[season_nr][episode_nr]['aired'] = aired show['episodes'] = episodes show['accessed'] = now show['errors'] = 0 # Might not really have changed - but successfull read return True
mit
idhamperdameian/Laravel-lang
script/todo.php
7612
<?php class Storage { public function directories(string $path): DirectoryIterator { return new DirectoryIterator( $this->realpath($path) ); } public function getDecodedJson(string $filename) { return file_exists($filename) ? json_decode(file_get_contents($filename), true) : null; } public function load(string $path) { return include $this->realpath($path); } public function store(string $path, string $content): void { $path = $this->realpath($path); file_put_contents($path, $content); } public function realpath(string $path): string { return realpath($path); } } class Output { protected $items = []; protected $eol = PHP_EOL; protected $line = PHP_EOL.PHP_EOL; protected $columns = 10; public function add(string $language, string $value = null): void { if (!array_key_exists($language, $this->items)) { $this->items[$language] = []; } if ($value) { array_push($this->items[$language], $value); } } public function get(): string { $result = $this->header(); $result .= $this->table(); foreach ($this->items as $language => $values) { $result .= $this->summary($language); $result .= $this->content($values); } return $result; } protected function header(): string { return '# Todo list'.$this->eol; } protected function summary(string $language): string { return "{$this->line}## {$language}{$this->line}"; } protected function content(array $values): string { if ($this->isEmpty($values)) { return $this->eol.'All lines are translated 😊'.$this->eol; } $content = implode($this->eol, $values); return <<<HTML <details> <summary>show</summary> {$content} [ [to top](#todo-list) ] </details> HTML; } protected function table(): string { $result = ''; $captions = implode('|', array_fill(0, $this->columns, ' ')); $divider = implode('|', array_fill(0, $this->columns, ':---:')); $result .= "|{$captions}|{$this->eol}"; $result .= "|{$divider}|{$this->eol}"; $keys = array_keys($this->items); $rows = array_chunk($keys, $this->columns); array_map(function ($row) use (&$result) { $row = $this->tableHeaderValue($row); $result .= $row.$this->eol; }, $rows); return $result.$this->eol.$this->eol; } protected function tableHeaderValue(array $languages): string { $languages = array_map(function ($language) { $icon = $this->icon($this->items[$language]); return "[{$language} {$icon}](#$language)"; }, $languages); return implode('|', $languages); } protected function icon($values): string { $is_empty = is_array($values) ? $this->isEmpty($values) : (bool) $values; return $is_empty ? '✔' : '❗'; } protected function isEmpty(array $values): bool { return empty($values); } } class TodoGenerator { /** @var Storage */ protected $storage; /** @var Output */ protected $output; protected $basePath; public function __construct(string $basePath, Storage $storage, Output $output) { $this->storage = $storage; $this->output = $output; $this->basePath = $basePath; $this->load(); } /** * Returns object. * * @param string $basePath base path * * @return TodoGenerator */ public static function make(string $basePath): self { $storage = new Storage(); $output = new Output(); return new self($basePath, $storage, $output); } /** * Save todo list. * * @param string $path */ public function save(string $path): void { $this->storage->store($path, $this->output->get()); } /** * Compare translations and generate file. */ private function load(): void { // Get English version $english = $this->getTranslations('en'); $languages = $this->getLanguages(); $this->compareTranslations($languages, $english); } /** * Returns array of translations by language. * * @param string $language language code * @param string $directory directory * * @return array */ private function getTranslations(string $language, string $directory = __DIR__): array { return [ 'json' => $this->getJsonContent($language, $directory), 'auth' => $this->getContent($language, $directory, 'auth.php'), 'pagination' => $this->getContent($language, $directory, 'pagination.php'), 'passwords' => $this->getContent($language, $directory, 'passwords.php'), 'validation' => $this->getContent($language, $directory, 'validation.php'), ]; } private function getJsonPath(string $language, string $directory): string { $directoryJson = ('en' === $language) ? '/en/' : '/../json/'; return $directory.$directoryJson.$language.'.json'; } private function getJsonContent(string $language, string $directory): ?array { $path = $this->getJsonPath($language, $directory); return $this->storage->getDecodedJson($path); } private function getContent(string $language, string $directory, string $filename) { return $this->storage->load( implode(DIRECTORY_SEPARATOR, [$directory, $language, $filename]) ); } /** * Returns list of languages. * * @return array */ private function getLanguages(): array { $directories = $this->storage->directories($this->basePath); $result = []; foreach ($directories as $directory) { if (!$directory->isDot()) { array_push($result, $directory->getFilename()); } } sort($result); return array_filter($result); } /** * Compare translations. * * @param array $default language by default * @param array $languages others languages */ private function compareTranslations(array $languages, array $default) { array_map(function ($language) use ($default) { $this->output->add($language); $current = $this->getTranslations($language, $this->basePath); foreach ($default as $key => $values) { array_map(function ($key2) use ($key, $current, $language, $default) { if (in_array($key2, ['custom', 'attributes'], true)) { return; } if (!isset($current[$key][$key2])) { $this->output->add( $language, " * {$key} : {$key2} : not present" ); } elseif ($current[$key][$key2] === $default[$key][$key2]) { $this->output->add( $language, " * {$key} : {$key2}" ); } }, array_keys($values)); } }, $languages); } } TodoGenerator::make(__DIR__.'/../src') ->save(__DIR__.'/../todo.md');
mit
zenozeng/gene-pool
lib/gene-pool.js
1526
// genes: 基因库 // n: 单个个体基因数 // weights: 每个基因的权重,影响出现的随机程度 function GenePool(genes, n, weights) { if(n > genes.length) { throw new Error("n must <= genes.length"); } weights = weights || genes.map(function() { return 1; }); // 随机取得一条基因 var getRandomGene = (function(genes, weights) { var sum = 0; var weightBounds = weights.map(function(weight) { sum += weight; return sum; }); return (function() { var random = Math.random() * sum; for(var i = 0; i < weightBounds.length; i++) { if(random < weightBounds[i]) { return genes[i]; } } return genes[weightBounds.length - 1]; }); })(genes, weights); // 获取一个随机个体(数组),该个体内含 n 条不重复的基因 var getRandomIndividual = function() { var genes = [], gene = null; while(genes.length < n) { gene = getRandomGene(); if(genes.indexOf(gene) < 0) { genes.push(gene); } else { genes = []; // 保证概率分布结果符合预期,见:https://github.com/zenozeng/gene-pool/issues/2 } } return genes; }; return { getRandomGene: getRandomGene, getRandomIndividual: getRandomIndividual }; } module.exports = GenePool;
mit
guokaijava/YGCMS
ygcms-core/src/main/java/org/openkoala/security/core/TelePhoneIsExistedException.java
485
package org.openkoala.security.core; public class TelePhoneIsExistedException extends SecurityException { private static final long serialVersionUID = 5363736963932226941L; public TelePhoneIsExistedException() { super(); } public TelePhoneIsExistedException(String message, Throwable cause) { super(message, cause); } public TelePhoneIsExistedException(String message) { super(message); } public TelePhoneIsExistedException(Throwable cause) { super(cause); } }
mit
sgeisler/EasyBitcoin
ByteArray.cpp
2018
// Copyright (c) 2015 Sebastian Geisler // Distributed under the MIT software license, see the accompanying // file LICENSE or http://www.opensource.org/licenses/mit-license.php. #include <stdexcept> #include <memory.h> #include "ByteArray.h" #include "Crypto.h" #include "Conversions.h" ByteArray::ByteArray(const Byte *data, size_t len) : vector<Byte>(len) { memcpy(&(*this)[0], data, len); } void ByteArray::operator+=(const ByteArray &other) { this->insert(this->end(), other.begin(), other.end()); } void ByteArray::operator+=(const Byte &other) { this->push_back(other); } ByteArray ByteArray::operator+(const ByteArray &other) const { ByteArray ret; ret.insert(ret.end(), this->begin(), this->end()); ret.insert(ret.end(), other.begin(), other.end()); return ret; } ByteArray ByteArray::operator+(const Byte other) const { ByteArray ret; ret.insert(ret.end(), this->begin(), this->end()); ret.insert(ret.end(), other); return ret; } std::string ByteArray::toHex() const { return Conversions::toHex(*this); } std::string ByteArray::toBase58() const { return Conversions::toBase58(*this); } std::string ByteArray::toBase58Check(Byte version) const { return Conversions::toBase58Check(*this, version); } ByteArray ByteArray::sha256() const { return Crypto::sha256(*this); } ByteArray ByteArray::ripemd160() const { return Crypto::ripemd160(*this); } ByteArray ByteArray::getSection(ByteArray::size_type begin, ByteArray::size_type len) { if (begin + len > size()) throw std::range_error("section not in bounds of ByteArray"); if (len == 0) return ByteArray(); ByteArray ret; ret.insert(ret.end(), this->begin() + begin, this->begin() + (begin + len)); return ret; } uint16_t ByteArray::toUInt16() { return Conversions::toUInt16(*this); } uint32_t ByteArray::toUInt32() { return Conversions::toUInt32(*this); } uint64_t ByteArray::toUInt64() { return Conversions::toUInt64(*this); }
mit
MadsJensen/malthe_alpha_project
adaboost_src.py
3008
import mne from mne.minimum_norm import (apply_inverse_epochs, read_inverse_operator) import socket import numpy as np # import matplotlib.pyplot as plt from sklearn.ensemble import AdaBoostClassifier # from sklearn.tree import DecisionTreeClassifier # from sklearn.metrics import confusion_matrix from sklearn.cross_validation import StratifiedKFold # import seaborn as sns # Setup paths and prepare raw data hostname = socket.gethostname() if hostname == "Wintermute": # data_path = "/home/mje/mnt/caa/scratch/" data_path = "/home/mje/Projects/malthe_alpha_project/data/" n_jobs = 1 else: data_path = "/projects/MINDLAB2015_MEG-CorticalAlphaAttention/scratch/" n_jobs = 1 subjects_dir = data_path + "fs_subjects_dir/" fname_inv = data_path + '0001-meg-oct-6-inv.fif' fname_epochs = data_path + '0001_p_03_filter_ds_ica-mc_tsss-epo.fif' fname_evoked = data_path + "0001_p_03_filter_ds_ica-mc_raw_tsss-ave.fif" snr = 1.0 # Standard assumption for average data but using it for single trial lambda2 = 1.0 / snr ** 2 method = "dSPM" # use dSPM method (could also be MNE or sLORETA) # Load data inverse_operator = read_inverse_operator(fname_inv) epochs = mne.read_epochs(fname_epochs) epochs.resample(200) stcs_ent_left = apply_inverse_epochs(epochs["ent_left"], inverse_operator, lambda2, method, pick_ori="normal") stcs_ctl_left = apply_inverse_epochs(epochs["ctl_left"], inverse_operator, lambda2, method, pick_ori="normal") src_ctl_l = np.asarray([stc.data.reshape(-1) for stc in stcs_ctl_left]) src_ent_l = np.asarray([stc.data.reshape(-1) for stc in stcs_ent_left]) X = np.vstack([src_ctl_l, src_ent_l]) y = np.concatenate([np.zeros(64), np.ones(64)]) # Setup classificer bdt = AdaBoostClassifier(algorithm="SAMME.R", n_estimators=1000) n_folds = 10 cv = StratifiedKFold(y, n_folds=n_folds) scores = np.zeros(n_folds) feature_importance = np.zeros(stc.data.shape) for ii, (train, test) in enumerate(cv): bdt.fit(X[train], y[train]) y_pred = bdt.predict(X[test]) y_test = y[test] scores[ii] = np.sum(y_pred == y_test) / float(len(y_test)) feature_importance += bdt.feature_importances_.reshape(stc.data.shape) feature_importance /= (ii + 1) # create average importance # create mask to avoid division error feature_importance = np.ma.masked_array(feature_importance, feature_importance == 0) # normalize scores for visualization purposes feature_importance /= feature_importance.std(axis=1)[:, None] feature_importance -= feature_importance.mean(axis=1)[:, None] vertices = [stc.lh_vertno, stc.rh_vertno] stc_feat = mne.SourceEstimate(feature_importance, vertices=vertices, tmin=0, tstep=stc.tstep, subject='0001') stc_feat.save(data_path + "stc_adaboost_feature") # scores_10 = cross_val_score(bdt, X, y, cv=10, n_jobs=1, verbose=False)
mit
onechiporenko/ember-models-table
addon/components/models-table/themes/default/footer.ts
3923
import Component from '@glimmer/component'; import DefaultTheme from '../../../../services/emt-themes/default'; import { SelectOption } from '../../../models-table'; export interface FooterArgs { /** * Bound from [[Core.ModelsTable.themeInstance | ModelsTable.themeInstance]] */ themeInstance: DefaultTheme; /** * Bound from [[Core.ModelsTable.collapseNumPaginationForPagesCount | ModelsTable.collapseNumPaginationForPagesCount]] */ collapseNumPaginationForPagesCount: number; /** * Bound from [[Core.ModelsTable.firstIndex | ModelsTable.firstIndex]] */ firstIndex: number; /** * Bound from [[Core.ModelsTable.lastIndex | ModelsTable.lastIndex]] */ lastIndex: number; /** * Bound from [[Core.ModelsTable.arrangedContentLength | ModelsTable.arrangedContentLength]] */ recordsCount: number; /** * Bound from [[Core.ModelsTable.anyFilterUsed | ModelsTable.anyFilterUsed]] */ anyFilterUsed: boolean; /** * Bound from [[Core.ModelsTable.pageSizeOptions | ModelsTable.pageSizeOptions]] */ pageSizeOptions: SelectOption[]; /** * Bound from [[Core.ModelsTable.currentPageNumberOptions | ModelsTable.currentPageNumberOptions]] */ currentPageNumberOptions: SelectOption[]; /** * Bound from [[Core.ModelsTable.pageSize | ModelsTable.pageSize]] */ pageSize: number; /** * Bound from [[Core.ModelsTable.currentPageNumber | ModelsTable.currentPageNumber]] */ currentPageNumber: number; /** * Bound from [[Core.ModelsTable.showCurrentPageNumberSelect | ModelsTable.showCurrentPageNumberSelect]] */ showCurrentPageNumberSelect: boolean; /** * Bound from [[Core.ModelsTable.pagesCount | ModelsTable.pagesCount]] */ pagesCount: number; /** * Bound from [[Core.ModelsTable.showPageSize | ModelsTable.showPageSize]] */ showPageSize: boolean; /** * Bound from [[Core.ModelsTable.useNumericPagination | ModelsTable.useNumericPagination]] */ useNumericPagination: boolean; /** * Bound from [[Core.ModelsTable.goToPage | ModelsTable.goToPage]] * * @event goToPage */ goToPage: (v: number) => void; /** * Bound from [[Core.ModelsTable.clearFilters | ModelsTable.clearFilters]] * * @event clearFilters */ clearFilters: () => void; /** * Bound from [[Core.ModelsTable.changePageSize | ModelsTable.changePageSize]] * * @event changePageSize */ changePageSize: (v: number) => void; } /** * Footer block used within [[Core.ModelsTable | ModelsTable]]. * * Usage example: * * ```html * <ModelsTable @data={{this.data}} @columns={{this.columns}} as |MT|> * <MT.Footer /> * {{! .... }} * </ModelsTable> * ``` * * Usage example with a block context: * * ```html * <ModelsTable @data={{this.data}} @columns={{this.columns}} as |MT|> * <MT.Footer as |Footer|> * <Footer.Summary /> * <Footer.PageSizeSelect /> * {{#if useNumericPagination}} * <Footer.PaginationNumeric /> * {{else}} * <Footer.PaginationSimple /> * {{/if}} * </MT.Footer> * </ModelsTable> * ``` * * ModelsTableFooter yields references to the following contextual components: * * * [[DefaultTheme.Summary | Summary]] - component with summary info about table data. It also contains button to clear all filters applied to the table * * [[DefaultTheme.PageSizeSelect | PageSizeSelect]] - component with a page sizes dropdown. It allows to select number if records shown on page * * [[DefaultTheme.PaginationNumeric | PaginationNumeric]] - component with a table navigation. It allows to move to the page by its number * * [[DefaultTheme.PaginationSimple | PaginationSimple]] - component with a table navigation. It allows to move to the first, last, prev and next pages (this four buttons are shown always) * * Check own docs for each component to get detailed info. */ export default class Footer extends Component<FooterArgs> {}
mit
ksaua/remock
src/test/java/no/saua/remock/exampleapplication/SuperClass.java
72
package no.saua.remock.exampleapplication; public class SuperClass { }
mit
delian1986/SoftUni-C-Sharp-repo
Programming Fundamenals January 2018/05. Arrays/Arrays More Exercises/06. Heists/Heists.cs
1610
using System; using System.Collections.Generic; using System.Linq; namespace _06._Heists { class Heists { static void Main(string[] args) { int[] sequence = Console.ReadLine().Split().Select(int.Parse).ToArray(); int jewelPrice = sequence[0]; int goldPrice = sequence[1]; long totalEarnings = 0; long totalExpences = 0; string income = string.Empty; while ((income = Console.ReadLine()) != "Jail Time") { string[] materials = income.Split(); string bounty = materials[0]; int expences = int.Parse(materials[1]); int jewelCount = 0; int goldCount = 0; foreach (var item in bounty) { if (item == '%') { jewelCount++; } else if (item == '$') { goldCount++; } } totalEarnings += jewelCount * jewelPrice; totalEarnings += goldCount * goldPrice; totalExpences += expences; } long result =totalEarnings - totalExpences; if (result>= 0) { Console.WriteLine($"Heists will continue. Total earnings: {result}."); } else { Console.WriteLine($"Have to find another job. Lost: {Math.Abs(result)}."); } } } }
mit
eblot/miscripts
Python/files/diffch.py
4231
#!/usr/bin/env python3 """Simple patch file analyzer to extract filename changes.""" from argparse import ArgumentParser, FileType from os import sep as pathsep from sys import modules, stderr from traceback import format_exc def analyze(patchfp, pathstrip, ether, added, removed, moved, adddel, verbose): oldname = '' newname = '' for line in patchfp: if line.startswith('--- '): oldname = line.split(' ', 1)[1].strip() if line.startswith('+++ '): newname = line.split(' ', 1)[1].strip() if oldname and newname: if pathstrip: if not oldname.startswith(pathsep): oldparts = oldname.split(pathsep) oldname = pathsep.join(oldparts[pathstrip:]) if not newname.startswith(pathsep): newparts = newname.split(pathsep) newname = pathsep.join(newparts[pathstrip:]) if oldname != newname: if ether not in (oldname, newname): if moved: if verbose: print('mov: ', end='') print('%s%s%s' % (oldname, ' -> ' if verbose else ' ', newname)) elif adddel: if verbose: print('add: ', end='') print(newname) if verbose: print('del: ', end='') print(oldname) if oldname == ether: if added: if verbose: print('add: ', end='') print(newname) if newname == ether: if removed: if verbose: print('del: ', end='') print(oldname) oldname = '' newname = '' def main(): """Parse command line and execute.""" debug = True try: argparser = ArgumentParser(description=modules[__name__].__doc__) argparser.add_argument('patch', nargs=1, type=FileType('rt'), help='Patch file to analyze') argparser.add_argument('-p', '--strip', type=int, default=1, help='Strip the smallest prefix containing num ' 'leading slashes from each file name found' ' in the patch file (default: 1).') argparser.add_argument('-e', '--ether', default='/dev/null', help='Alternative name to /dev/null') argparser.add_argument('-t', '--terse', action='store_true', help='Only print filenames') argparser.add_argument('-a', '--added', action='store_true', help='Show added (new) files') argparser.add_argument('-d', '--deleted', action='store_true', help='Show deleted (removed) files') argparser.add_argument('-m', '--moved', action='store_true', help='Show moved (renamed) files') argparser.add_argument('-M', '--adddel', action='store_true', help='Show moved files as addition, removal') argparser.add_argument('-A', '--all', action='store_true', help='Show all changed filenames') argparser.add_argument('-D', '--debug', action='store_true', help='enable debug mode') args = argparser.parse_args() debug = args.debug mov = bool(args.moved or args.all) add = bool(args.added or args.all) rem = bool(args.deleted or args.all) mad = (add or rem) and bool(args.adddel) analyze(args.patch[0], args.strip, args.ether, add, rem, mov, mad, args.all and not args.terse) except Exception as exc: print('\nError: %s' % exc, file=stderr) if debug: print(format_exc(chain=False), file=stderr) exit(1) if __name__ == '__main__': main()
mit
chrisAu4000/cycle-input
src/input/view.js
579
import {input, div} from '@cycle/dom' const view = (state$) => { return state$.map(({value, placeholder, transition, className}) => { const cName = className ? '.' + className : '' return div('.cycle-input-wrapper', [ input('.cycle-input' + cName, { attrs: { type: 'text', placeholder: placeholder, value: value, }, style: { height: transition + '%', width: transition + '%', opacity: transition < 30 ? transition / 30 : 1, }, }) ]) }) } export default view
mit
mayconbeserra/auctionata-online-app
src/actions/buyerActions.js
1261
"use strict"; var Dispatcher = require('../dispatcher/appDispatcher'); var BuyerAPI = require('../api/BuyerAPI'); var ActionTypes = require('../constants/actionTypes'); var Promise = require('promise'); var BuyerActions = { initialiseBuyers: function() { Promise.resolve(BuyerAPI.getAllBuyers()).then(function(result) { Dispatcher.dispatch({ actionType: ActionTypes.INITIALISE_BUYERS, initialData: { buyers: result.data } }); }); }, createBuyer: function(buyer) { var newBuyer = BuyerAPI.saveBuyer(buyer); //Hey dispatcher, go tell all the stores that an buyer was just created. Dispatcher.dispatch({ actionType: ActionTypes.CREATE_BUYER, buyer: newBuyer }); }, updateBuyer: function(buyer) { var updatedBuyer = BuyerAPI.saveBuyer(buyer); Dispatcher.dispatch({ actionType: ActionTypes.UPDATE_BUYER, buyer: updatedBuyer }); }, deleteBuyer: function(id) { BuyerAPI.deleteBuyer(id); Dispatcher.dispatch({ actionType: ActionTypes.DELETE_BUYER, id: id }); } }; module.exports = BuyerActions;
mit
yngui/jparse
src/main/java/com/github/jparse/ThenRightParser.java
1915
/* * The MIT License (MIT) * * Copyright (c) 2014 Igor Konev * * 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 com.github.jparse; import static java.util.Objects.requireNonNull; final class ThenRightParser<T, U> extends FluentParser<T, U> { private final Parser<T, ?> parser1; private final Parser<T, ? extends U> parser2; ThenRightParser(Parser<T, ?> parser1, Parser<T, ? extends U> parser2) { this.parser1 = requireNonNull(parser1); this.parser2 = requireNonNull(parser2); } @SuppressWarnings("unchecked") @Override public ParseResult<T, ? extends U> parse(Sequence<T> sequence) { ParseResult<T, ?> result1 = parser1.parse(sequence); if (result1.isSuccess()) { return parser2.parse(result1.getRest()); } else { return (ParseResult<T, ? extends U>) result1; } } }
mit
kolchanov/restapp
src/main/java/net/company/dao/CompanyH2Mapper.java
1514
package net.company.dao; import net.company.model.Beneficial; import net.company.model.Company; import java.util.List; import net.company.model.Country; import org.apache.ibatis.annotations.*; public interface CompanyH2Mapper { @Insert("INSERT INTO COMPANY(COMPANY_ID, NAME, ADDRESS, CITY, COUNTRY_CODE, EMAIL, PHONE) VALUES (#{id}, " + "#{name}, #{address}, #{city}, #{countryCode}, #{email}, #{phone})") @Options(keyProperty = "id", flushCache=true) void createCompany(Company company); List<Company> getAll(); Company getById(@Param("id") int id); @Update("update COMPANY set NAME = #{name}, ADDRESS=#{address}, CITY=#{city}, COUNTRY_CODE=#{countryCode}, " + "EMAIL=#{email}, PHONE=#{phone} where COMPANY_ID = #{id}") void update(Company company); @Select ("select CODE from COUNTRY where LANG = 1 and CODE=#{1}") List<String> checkCountryCode(String code); @Insert("insert into COMPANY_BENEFICIAL (COMPANY_ID, BENEFICIAL_ID, NAME) values(#{company.id}, #{beneficial.id}, #{beneficial.name})") void addBeneficial(@Param("company") Company company, @Param("beneficial") Beneficial beneficial); @Delete("delete from COMPANY_BENEFICIAL where COMPANY_ID = #{company.id} and BENEFICIAL_ID = #{beneficial.id}") void removeBeneficial(@Param("company") Company company, @Param("beneficial") Beneficial benificial); @Select("select CODE, NAME from COUNTRY where LANG = #{lang}") List<Country> getCountries(int lang); }
mit
liminshen/development-environment-structure
gulp/20160514/gulpfile.js
3141
var gulp = require('gulp'), // sass = require('gulp-ruby-sass'), clean = require('gulp-clean'), less = require('gulp-less'), autoprefixer = require('gulp-autoprefixer'), minifycss = require('gulp-minify-css'), rename = require('gulp-rename'), uglify = require('gulp-uglify'), rev = require('gulp-rev'), revCollector = require('gulp-rev-collector'), notify = require('gulp-notify'), minifyHTML = require('gulp-minify-html'); var browserSync = require('browser-sync').create(); var fixerBrowsers = ['last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4']; gulp.task('less',['cleanCss'],function() { return gulp.src('style/less/*.less') .pipe(less()) .pipe(autoprefixer({ browsers: fixerBrowsers, cascade: true, //是否美化属性值 默认:true 像这样: //-webkit-transform: rotate(45deg); // transform: rotate(45deg); remove: true //是否去掉不必要的前缀 默认:true })) .pipe(gulp.dest('style/css')) .pipe(minifycss()) .pipe(rev()) .pipe(rename(function (path) { path.basename += '.min'; })) .pipe(gulp.dest('dist/style/css')) .pipe(rev.manifest()) .pipe(gulp.dest('dist/style')) .pipe(notify({ message: 'Styles task complete' })) .pipe(browserSync.stream()); }); gulp.task('miniJS',function () { return gulp.src(['js/app/*.js','!js/*.min.js']) .pipe(uglify({ mangle:{except: ['require' ,'exports' ,'module' ,'$']},//排除混淆关键字 compress: true,//类型:Boolean 默认:true 是否完全压缩 preserveComments: 'all' //保留所有注释 })) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest('js/app')) .pipe(notify({ message: 'Script task complete' })) .pipe(browserSync.stream()); }) gulp.task('server', ['less'], function() { browserSync.init({ server: "./", port: 8080 }); gulp.watch("style/less/**/*.less", ['less']); gulp.watch("*.html").on('change', browserSync.reload); }); gulp.task('cleanCss',function () { return gulp.src('dist/style/css/*.min.css') .pipe(clean()); }); gulp.task('build:css-md5-web',function () { return gulp.src(['./dist/style/*.json','./web/*.html']) .pipe( revCollector({ replaceReved: true })) .pipe(minifyHTML()) .pipe(gulp.dest('./dist/web')); }); gulp.task('build:css-md5-wap',function () { return gulp.src(['./dist/style/*.json','./wap/*.html']) .pipe( revCollector({ replaceReved: true })) .pipe(minifyHTML()) .pipe(gulp.dest('./dist/wap')); }); gulp.task('build:css-md5-index',function () { return gulp.src(['./dist/style/*.json','./*.html']) .pipe( revCollector({ replaceReved: true }) ) .pipe(minifyHTML()) .pipe(gulp.dest('./dist/')); }); gulp.task('build',['build:css-md5-web','build:css-md5-wap','build:css-md5-index']);
mit
whitel/calagator-openshift
app/controllers/versions_controller.rb
534
class VersionsController < ApplicationController def edit @version = Version.find(params[:id]) @record = @version.next.try(:reify) || @version.item singular = @record.class.name.singularize.underscore plural = @record.class.name.pluralize.underscore self.instance_variable_set("@#{singular}", @record) if request.xhr? render :partial => "/#{plural}/form", :locals => { singular.to_sym => @record } else render "#{plural}/edit", :locals => { singular.to_sym => @record } end end end
mit
camptocamp/ngeo
test/spec/ngeo/getbrowserlanguage.spec.js
1985
// The MIT License (MIT) // // Copyright (c) 2019-2021 Camptocamp SA // // 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 {getBrowserLanguage} from 'ngeo/utils'; import {stub} from 'sinon'; describe('ngeo.misc.getBrowserLanguage', () => { /** @type {any} */ let languages; /** @type {any} */ let language; beforeEach(() => { languages = stub(window.navigator, 'languages'); language = stub(window.navigator, 'language'); }); afterEach(() => { languages.restore(); language.restore(); }); it('gets language from navigator.languages', () => { languages.value(['en-US', 'zh-CN', 'ja-JP', 'fr-FR']); const langCode = getBrowserLanguage(['de', 'fr', 'it']); expect(langCode).toBe('fr'); }); it('gets language from navigator.language', () => { languages.value(undefined); language.value('fr-FR'); const langCode = getBrowserLanguage(['de', 'fr', 'it']); expect(langCode).toBe('fr'); }); });
mit
johannes-riesterer/Verdriller
Particle.cpp
1304
/* * File: Particle.cpp * Author: johannes * * Created on 24. Juli 2014, 14:29 */ #include "Particle.h" Particle::Particle() { this->dynamic = true; this->mass = 1.0f; this->invMass = 1.0f / this->mass; this->gravity = true; this->force(0) = 0.0f; this->force(1) = 0.0f; this->force(2) = 0.0f; this->velocity(0) = 0.0f; this->velocity(1) = 0.0f; this->velocity(2) = 0.0f; }; Particle::Particle(const Particle& orig) { }; Particle::~Particle() { }; void Particle::updatePosition(float deltaTime) { if(this->dynamic) { //store position before update this->positionBeforeUpdate = this->position; //integrate position over time this->velocity+= deltaTime * this->invMass * this->force; this->position += deltaTime * this->velocity; //clear external forces and add gravity this->force(0) = 0.0f; if(this->gravity) { this->force(1) = -9.8f; } else { this->force(1) = 0.0; } this->force(2) = 0.0f; } }; void Particle::updateVelocity(float deltaTime) { if(this->dynamic) { this->velocity = (1.0f/deltaTime) * (this->position - this->positionBeforeUpdate); } };
mit
pineal/Leetcode_OJ
cpp/204_Count_Primes.cpp
641
//O(n^2) class Solution { public: int countPrimes(int n) { int count = 0; for (int i = 2; i < n; i++) { int j; int is_prime = 1; for (j = 2; j < i; j++) { if (i % j == 0) { is_prime = 0; break; } } count += is_prime; } return count; } }; //O(n^1.5) class Solution { public: int countPrimes(int n) { vector<bool> prime(n, true); prime[0] = false, prime[1] = false; for (int i = 0; i < sqrt(n); i++) { if (prime[i]) { for (int j = i*i; j < n; j += i) { prime[j] = false; } } } return count(prime.begin(), prime.end(), true); } };
mit
kazuhira-r/javaee7-scala-examples
cdi-dependent/src/main/java/org/littlewings/javaee/service/interceptor/Trace.java
558
package org.littlewings.javaee.service.interceptor; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.annotation.Priority; import javax.interceptor.Interceptor; import javax.interceptor.InterceptorBinding; @InterceptorBinding @Inherited @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Priority(Interceptor.Priority.APPLICATION) public @interface Trace { }
mit
sindresorhus/gulp-autoprefixer
test.js
2147
import path from 'path'; import test from 'ava'; import Vinyl from 'vinyl'; import sourceMaps from 'gulp-sourcemaps'; import pEvent from 'p-event'; import autoprefixer from '.'; test('autoprefix CSS', async t => { const stream = autoprefixer(); const data = pEvent(stream, 'data'); stream.end(new Vinyl({ cwd: __dirname, base: path.join(__dirname, 'fixture'), path: path.join(__dirname, 'fixture', 'fixture.css'), contents: Buffer.from('::placeholder {\n\tcolor: gray;\n}') })); const file = await data; t.regex(file.contents.toString(), /-/); t.is(file.relative, 'fixture.css'); }); test('generate source maps', async t => { const init = sourceMaps.init(); const write = sourceMaps.write(); const data = pEvent(write, 'data'); init .pipe(autoprefixer({ overrideBrowserslist: ['Firefox ESR'] })) .pipe(write); init.end(new Vinyl({ cwd: __dirname, base: path.join(__dirname, 'fixture'), path: path.join(__dirname, 'fixture', 'fixture.css'), contents: Buffer.from('a {\n\tdisplay: flex;\n}'), sourceMap: '' })); const file = await data; t.is(file.sourceMap.mappings, 'AAAA;CACC,aAAa;AACd'); const contents = file.contents.toString(); t.regex(contents, /flex/); t.regex(contents, /sourceMappingURL=data:application\/json;charset=utf8;base64/); }); test('read upstream source maps', async t => { let testFile; const stream = autoprefixer(); const write = sourceMaps.write(); const sourcesContent = [ 'a {\n display: flex;\n}\n', 'a {\n\tdisplay: flex;\n}\n' ]; const data = pEvent(write, 'data'); stream.pipe(write); stream.end( testFile = new Vinyl({ cwd: __dirname, base: path.join(__dirname, 'fixture'), path: path.join(__dirname, 'fixture', 'fixture.css'), contents: Buffer.from('a {\n\tdisplay: flex;\n}\n') }), testFile.sourceMap = { version: 3, sources: ['imported.less'], names: [], mappings: 'AAAA;EACC,aAAA', file: 'fixture.css', sourcesContent: ['a {\n display: flex;\n}\n'] } ); const file = await data; t.is(file.sourceMap.sourcesContent[0], sourcesContent[0]); t.is(file.sourceMap.sourcesContent[1], sourcesContent[1]); });
mit
fallenswordhelper/fallenswordhelper
src/modules/quickbuff/populateBuffs.js
1560
import getElementById from '../common/getElementById'; import outputFormat from '../system/outputFormat'; import querySelector from '../common/querySelector'; import setInnerHtml from '../dom/setInnerHtml'; function buffTimeLeft(secs) { const m = Math.floor(secs / 60); const s = secs % 60; let buffTimeToExpire = outputFormat(m, 'm'); if (m > 0 && s > 0) { buffTimeToExpire += ' '; } buffTimeToExpire += outputFormat(s, 's'); return buffTimeToExpire; } function timeToExpire(s) { const buffTimeToExpire = buffTimeLeft(s); return `<span class="fshLime">On</span>&nbsp;<span class="fshBuffOn">(${ buffTimeToExpire})</span>`; } function isAvailable(buff) { const elem = querySelector(`#buff-outer input[data-name="${buff}"]`); if (elem) { return `<span class="quickbuffActivate" data-buffid="${elem.value }">Activate</span>`; } return '<span class="fshRed;">Off</span>'; } function buffRunning(dict, buff) { const s = dict[buff] || 0; if (s) { return timeToExpire(s); } return isAvailable(buff); } function getBuff(dict, buff, inject) { setInnerHtml(buffRunning(dict, buff), inject); } function makeDictionary(acc, curr) { acc[curr.name] = curr.duration; return acc; } export default function populateBuffs(responseText) { const skl = responseText._skills.reduce(makeDictionary, {}); getBuff(skl, 'Guild Buffer', getElementById('fshGB')); getBuff(skl, 'Buff Master', getElementById('fshBM')); getBuff(skl, 'Extend', getElementById('fshExt')); getBuff(skl, 'Reinforce', getElementById('fshRI')); }
mit
welovekpop/uwave-web-welovekpop.club
es/utils/createGenerateClassName.js
482
export default function createGenerateClassName() { var counter = 0; function getNextUnknownName() { counter += 1; return "Component" + counter; } function generateClassName(rule, styleSheet) { var componentName = styleSheet.options.name || getNextUnknownName(); if (rule.key === 'root') { return componentName; } return componentName + "-" + rule.key; } return generateClassName; } //# sourceMappingURL=createGenerateClassName.js.map
mit
park-manager/parkmanager
src/Module/CoreModule/Test/Infrastructure/UserInterface/HttpResponseAssertions.php
2070
<?php declare(strict_types=1); /* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ namespace ParkManager\Module\CoreModule\Test\Infrastructure\UserInterface; use PHPUnit\Framework\Assert; use Symfony\Component\HttpKernel\Client; use Symfony\Component\VarDumper\VarDumper; final class HttpResponseAssertions { public static function assertRequestWasSuccessful(Client $client): void { if (! $client->getResponse()->isSuccessful()) { Assert::fail( 'Last request was not successful (statusCode: ]200 - 300]):' . VarDumper::dump($client->getInternalRequest()) . VarDumper::dump($client->getInternalResponse()) ); } Assert::assertTrue(true); } public static function assertRequestStatus(Client $client, int $statusCode = 200): void { if ($statusCode !== $client->getResponse()->getStatusCode()) { Assert::assertEquals( $statusCode, $client->getResponse()->getStatusCode(), 'Last response did not match status-code. ' . VarDumper::dump($client->getInternalRequest()) . VarDumper::dump($client->getInternalResponse()) ); } Assert::assertTrue(true); } public static function assertRequestWasRedirected(Client $client, string ...$expectedUrls): void { foreach ($expectedUrls as $expectedUrl) { if (! $client->getResponse()->isRedirect($expectedUrl)) { Assert::fail( 'Last request was not a redirect to: ' . $expectedUrl . VarDumper::dump($client->getInternalRequest()) . VarDumper::dump($client->getInternalResponse()) ); } $client->followRedirect(); } self::assertRequestWasSuccessful($client); } }
mit
freefair/android-library
playground/src/main/java/io/freefair/android/fader/ColorFader.java
909
package io.freefair.android.fader; import android.graphics.Color; /** * Created by larsgrefer on 30.01.15. */ public class ColorFader extends BaseFader<Integer> { protected IntFader redFader, greenFader, blueFader, alphaFader; public ColorFader(int from, int to) { this.from = from; this.to = to; setBounds(from, to); } @Override public void setBounds(Integer from, Integer to) { redFader = new IntFader(Color.red(from), Color.red(to)); greenFader = new IntFader(Color.green(from), Color.green(to)); blueFader = new IntFader(Color.blue(from), Color.blue(to)); alphaFader = new IntFader(Color.alpha(from), Color.alpha(to)); } @Override public Integer getValue(double weight) { return Color.argb(alphaFader.getValue(weight), redFader.getValue(weight), greenFader.getValue(weight), blueFader.getValue(weight) ); } }
mit
ICJIA/icjia-tvpp
statamic/core/API/Email.php
1305
<?php namespace Statamic\API; use Closure; class Email { /** * The email builder instance * * @return \Statamic\Email\Builder */ private static function email() { return app('Statamic\Email\Builder'); } /** * Begin building an email * * @return \Statamic\Email\Builder */ public static function create() { return self::email(); } /** * Begin building an email, populating the 'to' field * * @param string $address * @param string|null $name * @return \Statamic\Email\Builder */ public static function to($address, $name = null) { return self::email()->to($address, $name); } /** * Begin building an email, populating the 'from' field * * @param string $address * @param string|null $name * @return \Statamic\Email\Builder */ public static function from($address, $name = null) { return self::email()->from($address, $name); } /** * Begin building an email, populating the template * * @param string $template * @return \Statamic\Email\Builder */ public static function template($template) { return self::email()->template($template); } }
mit
arafato/ltl2fsm
ltl2fsm/dummy.ts.cpp
21
// empty dummy file
mit
mdemin914/metaforce
lib/metaforce/job/deploy.rb
2078
module Metaforce class Job::Deploy < Job # Public: Instantiate a new deploy job. # # Examples # # job = Metaforce::Job::Deploy.new(client, './path/to/deploy') # # => #<Metaforce::Job::Deploy @id=nil> # # Returns self. def initialize(client, path, options={}) super(client, :deploy) @path, @options = path, options end # Public: Perform the job. # # Examples # # job = Metaforce::Job::Deploy.new(client, './path/to/deploy') # job.perform # # => #<Metaforce::Job::Deploy @id='1234'> # # Returns self. def perform @id = client._deploy(payload, @options).id super end # Public: Get the detailed status of the deploy. # # Examples # # job.result # # => { :id => '1234', :success => true, ... } # # Returns the DeployResult (http://www.salesforce.com/us/developer/docs/api_meta/Content/meta_deployresult.htm). def result @result ||= client.status(id, :deploy) end # Public: Returns true if the deploy was successful. # # Examples # # job.success? # # => true # # Returns true or false based on the DeployResult. def success? result.success end private # Internal: Base64 encodes the contents of the zip file. # # Examples # # job.payload # # => '<lots of base64 encoded content>' # # Returns the content of the zip file encoded to base64. def payload Base64.encode64(File.open(file, 'rb').read) end # Internal: Returns the path to the zip file. def file File.file?(@path) ? @path : zip_file end # Internal: Creates a zip file with the contents of the directory. def zip_file path = Dir.mktmpdir File.join(path, 'deploy.zip').tap do |path| Zip::File.open(path, Zip::File::CREATE) do |zip| Dir["#{@path}/**/**"].each do |file| zip.add(file.sub("#{File.dirname(@path)}/", ''), file) end end end end end end
mit
fancyJelley/test-node-project
config/db.js
56
module.exports = { url: 'mongodb://localhost/images' }
mit
bladestery/Sapphire
example_apps/AndroidStudioMinnie/sapphire/src/main/java/org/ddogleg/sorting/QuickSort_F64.java
4792
/* * Copyright (c) 2012-2013, Peter Abeles. All Rights Reserved. * * This file is part of DDogleg (http://ddogleg.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ddogleg.sorting; /** * An implementation of the quick sort algorithm from Numerical Recipes Third Edition * that is specified for arrays of doubles. * * A small amount of memory is declared for this sorting algorithm. * * This implementation seems to often perform slower than Shell sort. A comment in Numerical * recipes about unnecessary array checks makes me think this is slow because java always * does a bounds check on arrays. * * This has slightly better performance than Arrays.sort(double[]). Not noticeable in most applications. */ public class QuickSort_F64 { // an architecture dependent tuning parameter private int M = 7; private int NSTACK; private int istack[]; public QuickSort_F64() { NSTACK = 65; istack = new int[NSTACK]; } public QuickSort_F64( int NSTACK , int M ) { this.M = M; this.NSTACK = NSTACK; istack = new int[NSTACK]; } public void sort( double[] arr , int length ) { int i,ir,j,k; int jstack = -1; int l = 0; // if I ever publish a book I will never use variable l in an algorithm with lots of 1 double a; ir=length-1; double temp; for(;;) { if( ir-l < M) { for( j=l+1;j<=ir;j++) { a = arr[j]; for( i=j-1; i>=l;i-- ) { if( arr[i] <= a ) break; arr[i+1]=arr[i]; } arr[i+1]=a; } if(jstack < 0) break; ir = istack[jstack--]; l=istack[jstack--]; } else { k=(l+ir)>>>1; temp = arr[k]; arr[k] = arr[l+1]; arr[l+1] = temp; if( arr[l] > arr[ir]) { temp = arr[l]; arr[l] = arr[ir]; arr[ir] = temp; } if( arr[l+1] > arr[ir]) { temp = arr[l+1]; arr[l+1] = arr[ir]; arr[ir] = temp; } if( arr[l] > arr[l+1]) { temp = arr[l]; arr[l] = arr[l+1]; arr[l+1] = temp; } i=l+1; j=ir; a=arr[l+1]; for(;;) { do { i++; } while( arr[i] < a); do { j--; } while( arr[j] > a); if(j < i ) break; temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } arr[l+1]=arr[j]; arr[j]=a; jstack += 2; if( jstack >= NSTACK ) throw new RuntimeException("NSTACK too small"); if( ir-i+1 >= j-l ) { istack[jstack] = ir; istack[jstack-1] = i; ir=j-1; } else { istack[jstack] = j-1; istack[jstack-1] = l; l=i; } } } } public void sort( double[] arr , int length , int indexes[] ) { for( int i = 0; i < length; i++ ) { indexes[i] = i; } int i,ir,j,k; int jstack = -1; int l = 0; // if I ever publish a book I will never use variable l in an algorithm with lots of 1 double a; ir=length-1; int temp; for(;;) { if( ir-l < M) { for( j=l+1;j<=ir;j++) { a = arr[indexes[j]]; temp = indexes[j]; for( i=j-1; i>=l;i-- ) { if( arr[indexes[i]] <= a ) break; indexes[i+1]=indexes[i]; } indexes[i+1]=temp; } if(jstack < 0) break; ir = istack[jstack--]; l=istack[jstack--]; } else { k=(l+ir)>>>1; temp = indexes[k]; indexes[k] = indexes[l+1]; indexes[l+1] = temp; if( arr[indexes[l]] > arr[indexes[ir]]) { temp = indexes[l]; indexes[l] = indexes[ir]; indexes[ir] = temp; } if( arr[indexes[l+1]] > arr[indexes[ir]]) { temp = indexes[l+1]; indexes[l+1] = indexes[ir]; indexes[ir] = temp; } if( arr[indexes[l]] > arr[indexes[l+1]]) { temp = indexes[l]; indexes[l] = indexes[l+1]; indexes[l+1] = temp; } i=l+1; j=ir; a=arr[indexes[l+1]]; for(;;) { do { i++; } while( arr[indexes[i]] < a); do { j--; } while( arr[indexes[j]] > a); if(j < i ) break; temp = indexes[i]; indexes[i] = indexes[j]; indexes[j] = temp; } temp = indexes[l+1]; indexes[l+1]=indexes[j]; indexes[j]=temp; jstack += 2; if( jstack >= NSTACK ) throw new RuntimeException("NSTACK too small"); if( ir-i+1 >= j-l ) { istack[jstack] = ir; istack[jstack-1] = i; ir=j-1; } else { istack[jstack] = j-1; istack[jstack-1] = l; l=i; } } } } }
mit
unshiftio/sessionstorage
test.js
1157
describe('sessionStorage', function () { 'use strict'; var assume = require('assume') , sessionStorage = require('./'); it('is exported as object', function () { assume(sessionStorage).is.a('object'); }); it('as the API methods', function () { assume(sessionStorage.getItem).is.a('function'); assume(sessionStorage.setItem).is.a('function'); assume(sessionStorage.removeItem).is.a('function'); assume(sessionStorage.clear).is.a('function'); assume(sessionStorage.length).is.a('number'); }); it('works as intended', function () { sessionStorage.setItem('foo', 'bar'); assume(sessionStorage.length).equals(1); assume(sessionStorage.getItem('foo')).equals('bar'); sessionStorage.setItem('hello', 'world'); assume(sessionStorage.length).equals(2); assume(sessionStorage.getItem('hello')).equals('world'); sessionStorage.removeItem('hello'); assume(sessionStorage.length).equals(1); assume(sessionStorage.getItem('hello')).is.a('null'); assume(sessionStorage.getItem('foo')).equals('bar'); sessionStorage.clear(); assume(sessionStorage.length).equals(0); }); });
mit
pocketberserker/my-lord
mylord-jvm/src/main/scala/mylord/services/WandboxClient.scala
1291
package mylord package services import argonaut._, Argonaut._ import scalaz._ import scalaz.concurrent.Task import org.http4s._ import org.http4s.dsl._ import org.http4s.argonaut._ import org.http4s.client._ import org.http4s.client.blaze.defaultClient import org.http4s.Status.ResponseClass.Successful class WandboxClient() { import Wandbox._ private val client = defaultClient private def response[T](res: Task[Response])(implicit D: EntityDecoder[T]) : Action[T] = EitherT(res.flatMap { case Successful(resp) => resp.as[T].map(\/-(_)) case resp => Task.now(-\/(resp.status.toString)) }) def list: Action[List[Compiler]] = { implicit val compilersDecoder = jsonOf[List[Compiler]] Url.list.flatMap(uri => response[List[Compiler]](client(uri))) } def compile(c: Compile): Action[CompileResult] = { implicit val compileEncoder = jsonEncoderOf[Compile] implicit val compileResultDecoder = jsonOf[CompileResult] Url.compile.flatMap(uri => { val req = POST(uri, c) response[CompileResult](client(req)) }) } def permlink(link: Path): Action[PermanentLink] = { implicit val permLinkDecoder = jsonOf[PermanentLink] Url.permlink(link.toString) .flatMap(uri => response[PermanentLink](client(uri))) } }
mit
iruwl/todo
application/config/database.php
2705
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /* | ------------------------------------------------------------------- | DATABASE CONNECTIVITY SETTINGS | ------------------------------------------------------------------- | This file will contain the settings needed to access your database. | | For complete instructions please consult the 'Database Connection' | page of the User Guide. | | ------------------------------------------------------------------- | EXPLANATION OF VARIABLES | ------------------------------------------------------------------- | | ['hostname'] The hostname of your database server. | ['username'] The username used to connect to the database | ['password'] The password used to connect to the database | ['database'] The name of the database you want to connect to | ['dbdriver'] The database type. ie: mysql. Currently supported: mysql, mysqli, postgre, odbc, mssql, sqlite, oci8 | ['dbprefix'] You can add an optional prefix, which will be added | to the table name when using the Active Record class | ['pconnect'] TRUE/FALSE - Whether to use a persistent connection | ['db_debug'] TRUE/FALSE - Whether database errors should be displayed. | ['cache_on'] TRUE/FALSE - Enables/disables query caching | ['cachedir'] The path to the folder where cache files should be stored | ['char_set'] The character set used in communicating with the database | ['dbcollat'] The character collation used in communicating with the database | ['swap_pre'] A default table prefix that should be swapped with the dbprefix | ['autoinit'] Whether or not to automatically initialize the database. | ['stricton'] TRUE/FALSE - forces 'Strict Mode' connections | - good for ensuring strict SQL while developing | | The $active_group variable lets you choose which connection group to | make active. By default there is only one group (the 'default' group). | | The $active_record variables lets you determine whether or not to load | the active record class */ $active_group = 'default'; $active_record = TRUE; $db['default']['hostname'] = 'localhost'; $db['default']['username'] = 'root'; $db['default']['password'] = 'root'; $db['default']['database'] = 'todo'; $db['default']['dbdriver'] = 'mysqli'; $db['default']['dbprefix'] = ''; $db['default']['pconnect'] = TRUE; $db['default']['db_debug'] = TRUE; $db['default']['cache_on'] = FALSE; $db['default']['cachedir'] = ''; $db['default']['char_set'] = 'utf8'; $db['default']['dbcollat'] = 'utf8_general_ci'; $db['default']['swap_pre'] = ''; $db['default']['autoinit'] = TRUE; $db['default']['stricton'] = FALSE; /* End of file database.php */ /* Location: ./application/config/database.php */
mit
ppikachu/gl_theme
functions.php
897
<?php /** * Sage includes * * The $sage_includes array determines the code library included in your theme. * Add or remove files to the array as needed. Supports child theme overrides. * * Please note that missing files will produce a fatal error. * * @link https://github.com/roots/sage/pull/1042 */ $sage_includes = [ 'lib/assets.php', // Scripts and stylesheets 'lib/extras.php', // Custom functions 'lib/setup.php', // Theme setup 'lib/titles.php', // Page titles 'lib/wrapper.php', // Theme wrapper class 'lib/customizer.php', // Theme customizer 'lib/bs4navwalker.php', 'lib/mis-extras.php', 'lib/gallery.php' ]; foreach ($sage_includes as $file) { if (!$filepath = locate_template($file)) { trigger_error(sprintf(__('Error locating %s for inclusion', 'sage'), $file), E_USER_ERROR); } require_once $filepath; } unset($file, $filepath);
mit
SRoddis/Mongo.Migration
Mongo.Migration/Services/IDocumentVersionService.cs
824
using System; using System.Collections.Generic; using Mongo.Migration.Documents; using Mongo.Migration.Migrations.Document; using MongoDB.Bson; namespace Mongo.Migration.Services { public interface IDocumentVersionService { string GetVersionFieldName(); DocumentVersion GetCurrentOrLatestMigrationVersion(Type type); DocumentVersion GetCollectionVersion(Type type); DocumentVersion GetVersionOrDefault(BsonDocument document); void SetVersion(BsonDocument document, DocumentVersion version); void DetermineVersion<TClass>(TClass instance) where TClass : class, IDocument; DocumentVersion DetermineLastVersion( DocumentVersion version, List<IDocumentMigration> migrations, int currentMigration); } }
mit
streamlink/streamlink-twitch-gui
src/app/data/models/twitch/stream-followed/serializer.js
514
import TwitchSerializer from "data/models/twitch/serializer"; export default TwitchSerializer.extend({ modelNameFromPayloadKey() { return "twitch-stream-followed"; }, attrs: { stream: { deserialize: "records" } }, normalize( modelClass, resourceHash, prop ) { const foreignKey = this.store.serializerFor( "twitch-stream" ).primaryKey; resourceHash = { [ this.primaryKey ]: resourceHash[ foreignKey ], stream: resourceHash }; return this._super( modelClass, resourceHash, prop ); } });
mit
voidfiles/jsonschematics
tests/test_json.py
2186
import json import unittest from schematics.models import Model from schematics.types import StringType, URLType, IntType, LongType, DecimalType from schematics.types.compound import ModelType, ListType from jsonschematics import to_jsonschema class BankAccount(Model): account_id = LongType(required=True, min_value=0) amount = DecimalType() class BirthPlace(Model): name = StringType(required=True, min_length=1, max_length=30) class Person(Model): name = StringType(required=True) website = URLType() age = IntType() birth_place = ModelType(BirthPlace) bank_accounts = ListType(ModelType(BankAccount)) test_data = { 'name': u'Joe Strummer', 'website': 'http://soundcloud.com/joestrummer', 'age': 15, 'birth_place': { 'name': 'Somewhere, World' }, 'bank_accounts': [{ 'account_id': long(123), 'amount': 10.23, }, { 'account_id': long(456), 'amount': 100.54, }] } converted_schema_string = '{"required": ["name"], "type": "object", "properties": {"website": {"type": "string"}, "bank_accounts": {"items": {"required": ["account_id"], "type": "object", "properties": {"amount": {"type": "number"}, "account_id": {"minimum": 0, "type": "integer"}}, "title": "BankAccount"}, "type": "array", "title": "BankAccount Set"}, "age": {"type": "integer"}, "birth_place": {"required": ["name"], "type": "object", "properties": {"name": {"minLength": 1, "type": "string", "maxLength": 30}}, "title": "BirthPlace"}, "name": {"type": "string"}}, "title": "Person"}' class TestModelFunctions(unittest.TestCase): def test_schema_serialization(self): val = to_jsonschema(Person) self.assertEquals(val, converted_schema_string) def test_validation_schema_validation(self): from jsonschema import validate person = Person(test_data) try: person.validate() except: self.fail("person.validate() raised Exception unexpectedly!") try: validate(test_data, json.loads(converted_schema_string)) except: self.fail("jsonschema.validate() raised Exception unexpectedly!")
mit
SaladbowlCreative/Snake
src/Domain/Properties/AssemblyInfo.cs
1399
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Domain")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("SaladLab")] [assembly: AssemblyProduct("Domain")] [assembly: AssemblyCopyright("Copyright © 2016 SaladLab")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("44ebce90-aaba-4704-beac-66c59bff179d")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
sapegin/social-likes-next
test/social-likes.spec.js
2325
import test from 'ava'; import SocialLikes from '../src/social-likes'; import { createWidget } from './button.spec'; /* eslint-disable max-len */ export function createButtons() { let container = document.createElement('div'); container.appendChild(createWidget({}, 'facebook')); container.appendChild(createWidget({}, 'twitter')); return container; } test('SocialLikes constructor should initialize container', t => { let container = createButtons(); let likes = new SocialLikes(container); t.ok(likes); t.is(container.className, 'social-likes social-likes_visible'); }); test('SocialLikes constructor should initialize buttons', t => { let likes = new SocialLikes(createButtons()); t.is(likes.buttons.length, 2); }); test('SocialLikes constructor should pass options to each button', t => { let likes = new SocialLikes(createButtons(), {}); t.is(likes.buttons[0].options.title, 'My Little Pony'); t.is(likes.buttons[1].options.title, 'My Little Pony'); }); test('SocialLikes constructor should set default URL and title', t => { let likes = new SocialLikes(createButtons()); t.is(likes.buttons[0].options.url, 'about:blank'); t.is(likes.buttons[0].options.title, 'My Little Pony'); }); test('SocialLikes constructor should merge options with default options', t => { let likes = new SocialLikes(createButtons(), { url: 'http://example.com', }); t.is(likes.buttons[0].options.url, 'http://example.com'); t.is(likes.buttons[0].options.title, 'My Little Pony'); }); test('SocialLikes constructor should merge options with data-attributes', t => { let container = createButtons(); container.setAttribute('data-title', 'Foo'); let likes = new SocialLikes(container); t.is(likes.buttons[0].options.url, 'about:blank'); t.is(likes.buttons[0].options.title, 'Foo'); }); test('SocialLikes.update should not update options when URL is the same', t => { let likes = new SocialLikes(createButtons(), {}); likes.update({ url: 'about:blank', title: 'Foo', }); t.is(likes.buttons[0].options.title, 'My Little Pony'); }); test('SocialLikes.update should update options for every button when URL is different', t => { let likes = new SocialLikes(createButtons(), {}); likes.update({ url: 'http://example.com', title: 'Foo', }); t.is(likes.buttons[0].options.title, 'Foo'); });
mit
philnash/twilio-node
lib/base/Version.d.ts
2437
import Domain = require('./Domain'); import TwilioClient = require('../rest/Twilio'); declare class Version { constructor(solutelydomain: Domain, version: string); /** * Generate absolute url from a uri * * @param uri uri to transform * @return transformed url */ absoluteUrl(uri: string): string; /** * Generate relative url from a uri * * @param uri uri to transform * @return transformed url */ relativeUrl(uri: string): string; /** * Make a request against the domain * * @param opts request options * @return promise that resolves to request response */ request(opts: TwilioClient.RequestOptions): Promise<any>; /** * Fetch a instance of a record * @throws {Error} If response returns non 2xx status code * * @param opts request options * @return promise that resolves to fetched result */ fetch(opts: TwilioClient.RequestOptions): Promise<any>; /** * Update a record * @throws {Error} If response returns non 2xx status code * * @param opts request options * @return promise that resolves to updated result */ update(opts: TwilioClient.RequestOptions): Promise<any>; /** * Delete a record * @throws {Error} If response returns a 5xx status * * @param opts request options * @return promise that resolves to true if record was deleted */ remove(opts: TwilioClient.RequestOptions): Promise<boolean>; /** * Create a new record * @throws {Error} If response returns non 2xx or 201 status code * * @param opts request options * @return promise that resolves to created record */ create(opts: TwilioClient.RequestOptions): Promise<any>; /** * Fetch a page of records * * @param opts request options * @return promise that resolves to page of records */ page(opts: TwilioClient.RequestOptions): Promise<any>; /** * Process limits for list requests * * @param opts Page limit options passed to the request */ readLimits(opts: Version.PageLimitOptions): Version.PageLimit; } declare namespace Version { export interface PageLimitOptions { /** * The maximum number of items to fetch */ limit: number; /** * The maximum number of items to return with every request */ pageSize: number; } export interface PageLimit { limit: number; pageSize: number; pageLimit: number; } } export = Version;
mit
pprmint/cheetos
ph/js/script.js
4292
$( function () { var id_list = []; var fresh_count = 0; var feed_cache = ""; function post_template (d) { var html = ""; html += '<div class="post msg col-lg-7 col-md-offset-3" data-id=' + d.id + '>'; html += '<p>' + unescape(decodeURIComponent(d.message)) + '</p> '; html += ' <p>' + unescape(decodeURIComponent(d.place_tag)) + ", " + unescape(decodeURIComponent(d.sender)) + ", " + d.sender_number +'</p>'; html += '<p><span class="label label-default timestamp" data-time=' + d.date_created + '>' + d.date_created + '</span></p>'; html += '<p><a href="http://reliefboard.com/ph/post.php?id=' + d.id + '" title="Permalink" target="_blank">Permalink</a></p>'; html += '<div class="fb-like" data-href="http://reliefboard.com/ph/post.php?id=' + d.id + '" data-layout="standard" data-action="like" data-show-faces="true" data-share="true"></div>'; html += '<div><a href="https://twitter.com/share" data-text="' + unescape(decodeURIComponent(d.message)) + ' - ' + unescape(decodeURIComponent(d.place_tag)) + ' - ' + unescape(decodeURIComponent(d.sender)) + ' #reliefboard VIA reliefboard.com" class="twitter-share-button" data-lang="en" data-related="reliefboardph:The official account of ReliefBoard">Tweet</a></div>'; html += '</div>'; return html; } function init () { /* START THE FETCH */ $.ajax( { type: "GET", url: "http://www.reliefboard.com/messages/feed" } ).done( function ( result ) { var html = ""; _.each( result.data.result, function(d) { id_list.push(d.id); html = html + post_template(d); }); $( "#msg" ).html(""); $( "#msg" ).append( html ); $( ".timestamp" ).prettyDate(); FB.XFBML.parse(); $.getScript('http://platform.twitter.com/widgets.js'); }); } init(); /* PRETTY DATE */ setInterval( function() { $( ".timestamp" ).prettyDate(); }, 10000); /* FETCH */ setInterval( function() { $.ajax( { type: "GET", url: "http://www.reliefboard.com/messages/feed" } ).done( function ( result ) { var html = ""; var title = $("title").text(); title = title.replace(/\([1-9][0-9]{0,2}\)/g, ''); _.each( result.data.result, function(d) { if( ! ( $.inArray( d.id , id_list ) > -1 ) ) { id_list.push(d.id); html = html + post_template(d); feed_cache = html + feed_cache; fresh_count = fresh_count + 1; } }); if( fresh_count > 0 ) { $(".notif").show(); $(".notif").css("display","block"); $("#count").text(fresh_count); $("title").text(title + " (" + fresh_count + ")" ); } }); }, 5000); $(document).on("click", ".notif", function(e) { e.preventDefault(); $( "#msg" ).prepend( feed_cache ); $(".notif").hide(); $( ".timestamp" ).prettyDate(); feed_cache = ""; fresh_count = 0; var title = $("title").text(); title = title.replace(/\([1-9][0-9]{0,2}\)/g, ''); $("title").text(title); FB.XFBML.parse(); $.getScript('http://platform.twitter.com/widgets.js'); }); $("form").bind("keypress", function(e) { if (e.keyCode == 13) { return false; } }); $(document).on("keyup", "#search", function(e) { e.preventDefault(); var val = $(this).val(); var search_count = 0; $( "#search-count" ).text(search_count); if( val.length > 0 ) { $(".search-container").show(); } else { $(".search-container").hide(); init(); return; } $.ajax( { type: "GET", url: "http://reliefboard.com/messages/search?q=" + val } ).done( function ( result ) { var html = ""; _.each( result.data.result, function(d) { id_list.push(d.id); html = html + post_template(d); search_count = search_count + 1; }); $( "#msg" ).html(""); $( "#msg" ).append( html ); $( ".timestamp" ).prettyDate(); $( "#search-count" ).text(search_count); FB.XFBML.parse(); $.getScript('http://platform.twitter.com/widgets.js'); }); }); $( ".timestamp" ).prettyDate(); });
mit
Squeegy/fleximage
test/rails_root/db/migrate/005_create_photo_s3s.rb
183
class CreatePhotoS3s < ActiveRecord::Migration def self.up create_table :photo_s3s do |t| t.timestamps end end def self.down drop_table :photo_s3s end end
mit
ea-zhongxiaochun/angularStudy
app/heroes.component.js
2946
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1 = require('@angular/core'); var router_1 = require('@angular/router'); var hero_service_1 = require('./hero.service'); var HeroesComponent = (function () { function HeroesComponent(heroService, router) { this.heroService = heroService; this.router = router; } HeroesComponent.prototype.getHeroes = function () { var _this = this; this.heroService .getHeroes() .then(function (heroes) { return _this.heroes = heroes; }); }; HeroesComponent.prototype.add = function (name) { var _this = this; name = name.trim(); if (!name) { return; } this.heroService.create(name) .then(function (hero) { _this.heroes.push(hero); _this.selectedHero = null; }); }; HeroesComponent.prototype.delete = function (hero) { var _this = this; this.heroService .delete(hero.id) .then(function () { _this.heroes = _this.heroes.filter(function (h) { return h !== hero; }); if (_this.selectedHero === hero) { _this.selectedHero = null; } }); }; HeroesComponent.prototype.ngOnInit = function () { this.getHeroes(); }; HeroesComponent.prototype.onSelect = function (hero) { this.selectedHero = hero; }; HeroesComponent.prototype.gotoDetail = function () { this.router.navigate(['/detail', this.selectedHero.id]); }; HeroesComponent = __decorate([ core_1.Component({ moduleId: module.id, selector: 'my-heroes', templateUrl: 'heroes.component.html', styleUrls: ['heroes.component.css'] }), __metadata('design:paramtypes', [hero_service_1.HeroService, router_1.Router]) ], HeroesComponent); return HeroesComponent; }()); exports.HeroesComponent = HeroesComponent; /* Copyright 2016 Google Inc. All Rights Reserved. Use of this source code is governed by an MIT-style license that can be found in the LICENSE file at http://angular.io/license */ //# sourceMappingURL=heroes.component.js.map
mit
Flowman/Integration-Kit
ConfigMgr.QuickTools.Device/ResultCacheControl.Designer.cs
14185
namespace ConfigMgr.QuickTools.Device { partial class ResultCacheControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.numericUpDown1 = new System.Windows.Forms.NumericUpDown(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.labelLocation = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.labelCacheSize = new System.Windows.Forms.Label(); this.labelSpaceToUse = new System.Windows.Forms.Label(); this.labelUsedSize = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.listViewContent = new Microsoft.ConfigurationManagement.AdminConsole.Common.SmsSearchableListView(); this.columnHeaderID = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeaderSize = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeaderLastUsed = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeaderLocation = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); this.toolStripMenuItemDelete = new System.Windows.Forms.ToolStripMenuItem(); this.buttonClearCache = new System.Windows.Forms.Button(); this.trackBarWithoutFocus1 = new ConfigMgr.QuickTools.Device.TrackBarWithoutFocus(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit(); this.contextMenuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.trackBarWithoutFocus1)).BeginInit(); this.SuspendLayout(); // // numericUpDown1 // this.numericUpDown1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.numericUpDown1.Enabled = false; this.numericUpDown1.Location = new System.Drawing.Point(273, 78); this.numericUpDown1.Name = "numericUpDown1"; this.numericUpDown1.Size = new System.Drawing.Size(97, 20); this.numericUpDown1.TabIndex = 1; this.numericUpDown1.ValueChanged += new System.EventHandler(this.NumericUpDown1_ValueChanged); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(10, 59); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(144, 13); this.label1.TabIndex = 3; this.label1.Text = "Amount of disk space to use:"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(10, 10); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(54, 13); this.label2.TabIndex = 4; this.label2.Text = "Location: "; // // labelLocation // this.labelLocation.AutoSize = true; this.labelLocation.Location = new System.Drawing.Point(64, 10); this.labelLocation.Name = "labelLocation"; this.labelLocation.Size = new System.Drawing.Size(0, 13); this.labelLocation.TabIndex = 5; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(10, 35); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(98, 13); this.label3.TabIndex = 6; this.label3.Text = "Current cache size:"; // // labelCacheSize // this.labelCacheSize.AutoSize = true; this.labelCacheSize.Location = new System.Drawing.Point(108, 35); this.labelCacheSize.Name = "labelCacheSize"; this.labelCacheSize.Size = new System.Drawing.Size(0, 13); this.labelCacheSize.TabIndex = 7; // // labelSpaceToUse // this.labelSpaceToUse.AutoSize = true; this.labelSpaceToUse.Location = new System.Drawing.Point(154, 59); this.labelSpaceToUse.Name = "labelSpaceToUse"; this.labelSpaceToUse.Size = new System.Drawing.Size(0, 13); this.labelSpaceToUse.TabIndex = 8; // // labelUsedSize // this.labelUsedSize.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.labelUsedSize.AutoSize = true; this.labelUsedSize.Location = new System.Drawing.Point(97, 333); this.labelUsedSize.Name = "labelUsedSize"; this.labelUsedSize.Size = new System.Drawing.Size(0, 13); this.labelUsedSize.TabIndex = 10; // // label5 // this.label5.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(8, 333); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(89, 13); this.label5.TabIndex = 9; this.label5.Text = "Used cache size:"; // // listViewListContent // this.listViewContent.Activation = System.Windows.Forms.ItemActivation.Standard; this.listViewContent.Alignment = System.Windows.Forms.ListViewAlignment.Top; this.listViewContent.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.listViewContent.AutoSort = true; this.listViewContent.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.listViewContent.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeaderLocation, this.columnHeaderSize, this.columnHeaderLastUsed, this.columnHeaderID}); this.listViewContent.ContextMenuStrip = this.contextMenuStrip1; this.listViewContent.CustomNoResultsText = null; this.listViewContent.FullRowSelect = true; this.listViewContent.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Clickable; this.listViewContent.HideSelection = false; this.listViewContent.IsLoading = false; this.listViewContent.LargeImageList = null; this.listViewContent.Location = new System.Drawing.Point(10, 119); this.listViewContent.MultiSelect = true; this.listViewContent.Name = "listViewListContent"; this.listViewContent.ShowSearchBar = true; this.listViewContent.Size = new System.Drawing.Size(360, 203); this.listViewContent.SmallImageList = null; this.listViewContent.Sorting = System.Windows.Forms.SortOrder.Ascending; this.listViewContent.StateImageList = null; this.listViewContent.TabIndex = 11; this.listViewContent.TileSize = new System.Drawing.Size(0, 0); this.listViewContent.UseCompatibleStateImageBehavior = false; this.listViewContent.View = System.Windows.Forms.View.Details; // // columnHeaderID // this.columnHeaderID.Text = "ID"; this.columnHeaderID.Width = 80; // // columnHeaderSize // this.columnHeaderSize.Text = "Size"; this.columnHeaderSize.Width = 80; // // columnHeaderLastUsed // this.columnHeaderLastUsed.Text = "Last Used"; this.columnHeaderLastUsed.Width = 80; // // columnHeaderLocation // this.columnHeaderLocation.Text = "Location"; this.columnHeaderLocation.Width = 150; // // contextMenuStrip1 // this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItemDelete}); this.contextMenuStrip1.Name = "contextMenuStrip1"; this.contextMenuStrip1.Size = new System.Drawing.Size(108, 26); this.contextMenuStrip1.Opening += new System.ComponentModel.CancelEventHandler(this.ContextMenuStrip1_Opening); // // toolStripMenuItemDelete // this.toolStripMenuItemDelete.Name = "toolStripMenuItemDelete"; this.toolStripMenuItemDelete.Size = new System.Drawing.Size(180, 22); this.toolStripMenuItemDelete.Text = "Delete"; this.toolStripMenuItemDelete.Click += new System.EventHandler(this.ToolStripMenuItemDelete_Click); // // buttonClearCache // this.buttonClearCache.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonClearCache.Location = new System.Drawing.Point(295, 328); this.buttonClearCache.Name = "buttonClearCache"; this.buttonClearCache.Size = new System.Drawing.Size(75, 23); this.buttonClearCache.TabIndex = 12; this.buttonClearCache.Text = "Clear Cache"; this.buttonClearCache.UseVisualStyleBackColor = true; this.buttonClearCache.Click += new System.EventHandler(this.ButtonClearCache_Click); // // trackBarWithoutFocus1 // this.trackBarWithoutFocus1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.trackBarWithoutFocus1.Enabled = false; this.trackBarWithoutFocus1.Location = new System.Drawing.Point(10, 78); this.trackBarWithoutFocus1.Name = "trackBarWithoutFocus1"; this.trackBarWithoutFocus1.Size = new System.Drawing.Size(257, 45); this.trackBarWithoutFocus1.TabIndex = 2; this.trackBarWithoutFocus1.ValueChanged += new System.EventHandler(this.TrackBar1_ValueChanged); // // ResultCacheControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.buttonClearCache); this.Controls.Add(this.listViewContent); this.Controls.Add(this.labelUsedSize); this.Controls.Add(this.label5); this.Controls.Add(this.labelSpaceToUse); this.Controls.Add(this.labelCacheSize); this.Controls.Add(this.label3); this.Controls.Add(this.labelLocation); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.trackBarWithoutFocus1); this.Controls.Add(this.numericUpDown1); this.Name = "ResultCacheControl"; ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit(); this.contextMenuStrip1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.trackBarWithoutFocus1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.NumericUpDown numericUpDown1; private TrackBarWithoutFocus trackBarWithoutFocus1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label labelLocation; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label labelCacheSize; private System.Windows.Forms.Label labelSpaceToUse; private System.Windows.Forms.Label labelUsedSize; private System.Windows.Forms.Label label5; private Microsoft.ConfigurationManagement.AdminConsole.Common.SmsSearchableListView listViewContent; private System.Windows.Forms.Button buttonClearCache; private System.Windows.Forms.ColumnHeader columnHeaderID; private System.Windows.Forms.ColumnHeader columnHeaderSize; private System.Windows.Forms.ColumnHeader columnHeaderLastUsed; private System.Windows.Forms.ColumnHeader columnHeaderLocation; private System.Windows.Forms.ContextMenuStrip contextMenuStrip1; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemDelete; } }
mit
imba3r/grabber
ui/src/app/shared/pipes/smart-date.pipe.spec.ts
630
import { SmartDatePipe } from './smart-date.pipe'; describe('SmartDatePipe', () => { let pipe: SmartDatePipe; beforeEach(() => { pipe = new SmartDatePipe(); }); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transform date to "time ago"', () => { const now = new Date(); now.setDate(now.getDate() - 9); expect(pipe.transform(now.getTime())).toEqual('9 days ago'); }); it('transform date to "date"', () => { const now = new Date(); now.setDate(now.getDate() - 10); expect(pipe.transform(now.getTime())).toEqual(now.toLocaleDateString('en-GB')); }); });
mit
leanwork/lean-codepack
src/Lean.CodePack/Leanwork.CodePack.Mvc/CustomRoutes/AdminRoute.cs
1851
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace Leanwork.CodePack.Mvc { public class CustomRoute : Route { public string Name { get; set; } public string Group { get; set; } public CustomRoute(string url, IRouteHandler routeHandler) : base(url, routeHandler) { } } public static class AreaRegistrationContextExtensions { public static void MapCustomRoute(this AreaRegistrationContext context, string name, string url, object defaults, string[] namespaces, string group = "") { context.MapCustomRoute(name, url, defaults, null, namespaces, group: group); } public static void MapCustomRoute(this AreaRegistrationContext context, string name, string url, object defaults, object constraints, string[] namespaces, string group = "") { if (context == null) throw new ArgumentNullException("context"); if (url == null) throw new ArgumentNullException("url"); var route = new CustomRoute(url, new MvcRouteHandler()) { Name = name, Defaults = new RouteValueDictionary(defaults), Constraints = new RouteValueDictionary(constraints), DataTokens = new RouteValueDictionary(), Group = group }; if ((namespaces != null) && (namespaces.Length > 0)) { route.DataTokens["Namespaces"] = namespaces; } route.DataTokens["area"] = context.AreaName; if (String.IsNullOrEmpty(name)) context.Routes.Add(route); else context.Routes.Add(name, route); } } }
mit
metfan/rabbit-setup
bootstrap.php
236
<?php /* * This file bootstrap autoload for phpunit */ $file = __DIR__.'/vendor/autoload.php'; if (!file_exists($file)) { throw new RuntimeException('Install dependencies to run test suite.'); } $autoload = require_once $file;
mit
slashrocket/rocketbot
config/application.rb
1400
require File.expand_path('../boot', __FILE__) require 'action_controller/railtie' require 'action_view/railtie' require 'action_mailer/railtie' require 'action_mailer/railtie' require 'active_job/railtie' require 'rails/test_unit/railtie' require 'sprockets/railtie' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Rocketbot class Application < Rails::Application config.api_only = true config.eager_load_paths << Rails.root.join('lib') # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Do not swallow errors in after_commit/after_rollback callbacks. # config.active_record.raise_in_transactional_callbacks = true end end
mit
jstrait/beats
lib/beats/kit.rb
1653
module Beats class Kit class LabelNotFoundError < RuntimeError; end PLACEHOLDER_TRACK_NAME = "empty_track_placeholder_name_234hkj32hjk4hjkhds23" def initialize(items, num_channels, bits_per_sample) @items = items @labels = @items.keys.freeze @num_channels = num_channels @bits_per_sample = bits_per_sample end attr_reader :labels, :num_channels, :bits_per_sample # Returns the sample data for a sound contained in the Kit. If the all sounds in the # kit are mono, then this will be a flat Array of Integers between -32768 and 32767. # Otherwise, this will be an Array of Integers pairs between -32768 and 32767. # # label - The name of the sound to get sample data for. If the sound was defined in # the Kit section of a song file, this will generally be a descriptive label # such as "bass" or "snare". If defined in a track but not the kit, it will # generally be a file name such as "my_sounds/hihat/hi_hat.wav". # # Examples # # # If @num_channels is 1, a flat Array of Integers: # get_sample_data("bass") # # => [154, 7023, 8132, 2622, -132, 34, ..., -6702] # # # If @num_channels is 2, a Array of Integers pairs: # get_sample_data("snare") # # => [[57, 1265], [-452, 10543], [-2531, 12643], [-6372, 11653], ..., [5482, 25673]] # # Returns the sample data Array for the sound bound to label. def get_sample_data(label) unless @items.has_key?(label) raise LabelNotFoundError, "Kit doesn't contain sound '#{label}'." end @items[label] end end end
mit
araneforseti/api-tester
spec/api-tester/modules/format_spec.rb
2802
# frozen_string_literal: true require 'spec_helper' require 'webmock/rspec' require 'api-tester/definition/response' require 'api-tester/definition/request' require 'api-tester/definition/endpoint' require 'api-tester/definition/contract' require 'api-tester/modules/format' require 'api-tester/reporter/api_report' require 'api-tester/test_helper' describe ApiTester::Format do let(:url) { 'www.example.com' } let(:request) { ApiTester::Request.new } let(:endpoint) { ApiTester::Endpoint.new name: 'Test', relative_url: '' } let(:contract) { ApiTester::Contract.new name: 'Test', base_url: url } let(:expected_code) { 400 } let(:expected_response) { ApiTester::Response.new status_code: expected_code } let(:expected_body) { '{"numKey": 1, "string_key": "string"}' } let(:expected_fields) { [ApiTester::Field.new(name: 'numKey'), ApiTester::Field.new(name: 'string_key')] } let(:request_fields) { [ApiTester::ArrayField.new(name: 'arr')] } let(:report) { ApiTester::ApiReport.new } before :each do expected_fields.each do |field| expected_response.add_field field end request_fields.each do |field| request.add_field field end endpoint.add_method verb: ApiTester::SupportedVerbs::POST, response: expected_response, request: request endpoint.bad_request_response = expected_response contract.add_endpoint endpoint stub_request(:post, url).to_return(body: expected_body, status: expected_code) end context 'post request' do it 'everything works' do expect(ApiTester::Format.go(contract).size).to eq 0 end it 'gets a simple string' do stub_request(:post, url).to_return(body: 'bad request', status: expected_code) expect(ApiTester::Format.go(contract).size).to be >= 1 end end context 'should use test helper' do before :each do test_helper_mock = Class.new(ApiTester::TestHelper) do def before RestClient.get('www.test.com/before') end def after RestClient.get('www.test.com/after') end end endpoint.test_helper = test_helper_mock.new stub_request(:get, 'www.test.com/before').to_return(body: '', status: 200) stub_request(:get, 'www.test.com/after').to_return(body: '', status: 200) expect(ApiTester::Format.go(contract).size).to eq 0 end it 'should make use of test helper before method' do expect(a_request(:get, 'www.test.com/before')).to have_been_made.at_least_once end it 'should make use of test helper after method' do expect(a_request(:get, 'www.test.com/after')).to have_been_made.at_least_once end end end
mit
ghthou/learning-taotaoMall
taotao-search/src/main/java/com/taotao/search/pojo/SearchResult.java
277
package com.taotao.search.pojo; import java.util.List; import lombok.Data; @Data public class SearchResult { //商品列表 private List<Item> itemList; //总记录数 private long recordCount; //总页数 private long pageCount; //当前页 private long curPage; }
mit
sdellis/figgy.filemanager
test/figgy.filemanager.spec.js
670
// For authoring Nightwatch tests, see // http://nightwatchjs.org/guide#usage var config = require('../nightwatch.conf.js'); module.exports = { // adapted from: https://git.io/vodU0 before: function (browser, done) { server = require('../server')(done) // done is a callback that executes when the server is started }, after: function () { server.close() }, 'default e2e tests': function(browser) { browser .url('localhost:3000') .waitForElementVisible('#sortable', 5000) .assert.elementPresent('.thumbnail') //.assert.containsText('.caption:first', '1') .assert.elementCount('#sortable img', 32) .end() } };
mit
tercenya/invalesco
bin/ops/06_player_match_rank_skew.rb
666
#!/usr/bin/env ruby require_relative '../bootstrap' require 'invalesco/ranking' counts = {} include Ranking Match.all.each do |match| blue_points = team_points(match.blue_participants) red_points = team_points(match.red_participants) total = blue_points + red_points delta = (blue_points - red_points).abs winner = blue_points > red_points ? :blue : :red counts[delta] ||= { count: 0, upset: {} } counts[delta][:upset][total] ||= 0 upset = match.winner == winner ? 0 : 1 counts[delta][:upset][total] += upset counts[delta][:count] += 1 end Urf::TeamRankSkew.delete_all counts.each do |k,v| Urf::TeamRankSkew.create(v.merge(id: k)) end
mit
mcodegeeks/OpenKODE-Framework
01_Develop/libXMCocos2D-v3/Source/2d/draw_nodes/CCDrawNode.cpp
14542
/* ----------------------------------------------------------------------------------- * * File CCDrawNode.cpp * Ported By Young-Hwan Mun * Contact xmsoft77@gmail.com * * ----------------------------------------------------------------------------------- * * Copyright (c) 2010-2014 XMSoft * Copyright (c) 2010-2013 cocos2d-x.org * Copyright (c) 2012 Scott Lembcke and Howling Moon Software * * http://www.cocos2d-x.org * * ----------------------------------------------------------------------------------- * * 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. * * --------------------------------------------------------------------------------- */ #include "2d/draw_nodes/CCDrawNode.h" #include "shaders/CCShaderCache.h" #include "support/CCNotificationCenter.h" #include "CCEventType.h" #include "2d/CCConfiguration.h" NS_CC_BEGIN // Vertex2F == CGPoint in 32-bits, but not in 64-bits (OS X) // that's why the "v2f" functions are needed static Vertex2F v2fzero(0.0f,0.0f); static inline Vertex2F v2f(float x, float y) { Vertex2F ret(x, y); return ret; } static inline Vertex2F v2fadd(const Vertex2F &v0, const Vertex2F &v1) { return v2f(v0.x+v1.x, v0.y+v1.y); } static inline Vertex2F v2fsub(const Vertex2F &v0, const Vertex2F &v1) { return v2f(v0.x-v1.x, v0.y-v1.y); } static inline Vertex2F v2fmult(const Vertex2F &v, float s) { return v2f(v.x * s, v.y * s); } static inline Vertex2F v2fperp(const Vertex2F &p0) { return v2f(-p0.y, p0.x); } static inline Vertex2F v2fneg(const Vertex2F &p0) { return v2f(-p0.x, - p0.y); } static inline float v2fdot(const Vertex2F &p0, const Vertex2F &p1) { return p0.x * p1.x + p0.y * p1.y; } static inline Vertex2F v2fforangle(float _a_) { return v2f(kdCosf(_a_), kdSinf(_a_)); } static inline Vertex2F v2fnormalize(const Vertex2F &p) { Point r = Point(p.x, p.y).normalize(); return v2f(r.x, r.y); } static inline Vertex2F __v2f(const Point &v) { //#ifdef __LP64__ return v2f(v.x, v.y); // #else // return * ((Vertex2F*) &v); // #endif } static inline Tex2F __t(const Vertex2F &v) { return *(Tex2F*)&v; } // implementation of DrawNode DrawNode::DrawNode() : m_uVao(0) , m_uVbo(0) , m_nBufferCapacity(0) , m_nBufferCount(0) , m_pBuffer(NULL) , m_bDirty(false) { m_tBlendFunc = BlendFunc::ALPHA_PREMULTIPLIED; } DrawNode::~DrawNode() { kdFree(m_pBuffer); m_pBuffer = NULL; glDeleteBuffers(1, &m_uVbo); m_uVbo = 0; if (Configuration::getInstance()->supportsShareableVAO()) { glDeleteVertexArrays(1, &m_uVao); GL::bindVAO(0); m_uVao = 0; } #if CC_ENABLE_CACHE_TEXTURE_DATA NotificationCenter::getInstance()->removeObserver(this, EVENT_COME_TO_FOREGROUND); #endif } DrawNode* DrawNode::create() { DrawNode* pRet = new DrawNode(); if (pRet && pRet->init()) { pRet->autorelease(); } else { CC_SAFE_DELETE(pRet); } return pRet; } KDvoid DrawNode::ensureCapacity ( KDint32 nCount ) { CCASSERT(nCount>=0, "capacity must be >= 0"); if(m_nBufferCount + nCount > m_nBufferCapacity) { m_nBufferCapacity += KD_MAX(m_nBufferCapacity, nCount); m_pBuffer = (V2F_C4B_T2F*) kdRealloc(m_pBuffer, m_nBufferCapacity*sizeof(V2F_C4B_T2F)); } } bool DrawNode::init() { m_tBlendFunc = BlendFunc::ALPHA_PREMULTIPLIED; setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_LENGTH_TEXTURE_COLOR)); ensureCapacity(512); if (Configuration::getInstance()->supportsShareableVAO()) { glGenVertexArrays(1, &m_uVao); GL::bindVAO(m_uVao); } glGenBuffers(1, &m_uVbo); glBindBuffer(GL_ARRAY_BUFFER, m_uVbo); glBufferData(GL_ARRAY_BUFFER, sizeof(V2F_C4B_T2F)* m_nBufferCapacity, m_pBuffer, GL_STREAM_DRAW); glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_POSITION); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, vertices)); glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_COLOR); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, colors)); glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_TEX_COORDS); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORDS, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, texCoords)); glBindBuffer(GL_ARRAY_BUFFER, 0); if (Configuration::getInstance()->supportsShareableVAO()) { GL::bindVAO(0); } CHECK_GL_ERROR_DEBUG(); m_bDirty = true; #if CC_ENABLE_CACHE_TEXTURE_DATA // Need to listen the event only when not use batchnode, because it will use VBO NotificationCenter::getInstance()->addObserver(this, callfuncO_selector(DrawNode::listenBackToForeground), EVENT_COME_TO_FOREGROUND, NULL); #endif return true; } void DrawNode::render() { if (m_bDirty) { glBindBuffer(GL_ARRAY_BUFFER, m_uVbo); glBufferData(GL_ARRAY_BUFFER, sizeof(V2F_C4B_T2F)*m_nBufferCapacity, m_pBuffer, GL_STREAM_DRAW); m_bDirty = false; } if (Configuration::getInstance()->supportsShareableVAO()) { GL::bindVAO(m_uVao); } else { GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX); glBindBuffer(GL_ARRAY_BUFFER, m_uVbo); // vertex glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, vertices)); // color glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, colors)); // texcood glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORDS, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, texCoords)); } glDrawArrays(GL_TRIANGLES, 0, m_nBufferCount); glBindBuffer(GL_ARRAY_BUFFER, 0); CC_INCREMENT_GL_DRAWS(1); CHECK_GL_ERROR_DEBUG(); } void DrawNode::draw() { CC_NODE_DRAW_SETUP(); GL::blendFunc(m_tBlendFunc.src, m_tBlendFunc.dst); render(); } void DrawNode::drawDot(const Point &pos, float radius, const Color4F &color) { unsigned int vertex_count = 2*3; ensureCapacity(vertex_count); V2F_C4B_T2F a = {Vertex2F(pos.x - radius, pos.y - radius), Color4B(color), Tex2F(-1.0, -1.0) }; V2F_C4B_T2F b = {Vertex2F(pos.x - radius, pos.y + radius), Color4B(color), Tex2F(-1.0, 1.0) }; V2F_C4B_T2F c = {Vertex2F(pos.x + radius, pos.y + radius), Color4B(color), Tex2F( 1.0, 1.0) }; V2F_C4B_T2F d = {Vertex2F(pos.x + radius, pos.y - radius), Color4B(color), Tex2F( 1.0, -1.0) }; V2F_C4B_T2F_Triangle *triangles = (V2F_C4B_T2F_Triangle *)(m_pBuffer + m_nBufferCount); V2F_C4B_T2F_Triangle triangle0 = {a, b, c}; V2F_C4B_T2F_Triangle triangle1 = {a, c, d}; triangles[0] = triangle0; triangles[1] = triangle1; m_nBufferCount += vertex_count; m_bDirty = true; } void DrawNode::drawSegment(const Point &from, const Point &to, float radius, const Color4F &color) { unsigned int vertex_count = 6*3; ensureCapacity(vertex_count); Vertex2F a = __v2f(from); Vertex2F b = __v2f(to); Vertex2F n = v2fnormalize(v2fperp(v2fsub(b, a))); Vertex2F t = v2fperp(n); Vertex2F nw = v2fmult(n, radius); Vertex2F tw = v2fmult(t, radius); Vertex2F v0 = v2fsub(b, v2fadd(nw, tw)); Vertex2F v1 = v2fadd(b, v2fsub(nw, tw)); Vertex2F v2 = v2fsub(b, nw); Vertex2F v3 = v2fadd(b, nw); Vertex2F v4 = v2fsub(a, nw); Vertex2F v5 = v2fadd(a, nw); Vertex2F v6 = v2fsub(a, v2fsub(nw, tw)); Vertex2F v7 = v2fadd(a, v2fadd(nw, tw)); V2F_C4B_T2F_Triangle *triangles = (V2F_C4B_T2F_Triangle *)(m_pBuffer + m_nBufferCount); V2F_C4B_T2F_Triangle triangles0 = { {v0, Color4B(color), __t(v2fneg(v2fadd(n, t)))}, {v1, Color4B(color), __t(v2fsub(n, t))}, {v2, Color4B(color), __t(v2fneg(n))}, }; triangles[0] = triangles0; V2F_C4B_T2F_Triangle triangles1 = { {v3, Color4B(color), __t(n)}, {v1, Color4B(color), __t(v2fsub(n, t))}, {v2, Color4B(color), __t(v2fneg(n))}, }; triangles[1] = triangles1; V2F_C4B_T2F_Triangle triangles2 = { {v3, Color4B(color), __t(n)}, {v4, Color4B(color), __t(v2fneg(n))}, {v2, Color4B(color), __t(v2fneg(n))}, }; triangles[2] = triangles2; V2F_C4B_T2F_Triangle triangles3 = { {v3, Color4B(color), __t(n)}, {v4, Color4B(color), __t(v2fneg(n))}, {v5, Color4B(color), __t(n) }, }; triangles[3] = triangles3; V2F_C4B_T2F_Triangle triangles4 = { {v6, Color4B(color), __t(v2fsub(t, n))}, {v4, Color4B(color), __t(v2fneg(n)) }, {v5, Color4B(color), __t(n)}, }; triangles[4] = triangles4; V2F_C4B_T2F_Triangle triangles5 = { {v6, Color4B(color), __t(v2fsub(t, n))}, {v7, Color4B(color), __t(v2fadd(n, t))}, {v5, Color4B(color), __t(n)}, }; triangles[5] = triangles5; m_nBufferCount += vertex_count; m_bDirty = true; } KDvoid DrawNode::drawPolygon ( Point* pVerts, KDint32 nCount, const Color4F& tFillColor, KDfloat fBorderWidth, const Color4F& tBorderColor ) { CCASSERT(nCount >= 0, "invalid count value"); struct ExtrudeVerts {Vertex2F offset, n;}; struct ExtrudeVerts* extrude = (struct ExtrudeVerts*) kdMalloc(sizeof(struct ExtrudeVerts)*nCount); kdMemset(extrude, 0, sizeof(struct ExtrudeVerts)*nCount); for (long i = 0; i < nCount; i++) { Vertex2F v0 = __v2f(pVerts[(i-1+nCount)%nCount]); Vertex2F v1 = __v2f(pVerts[i]); Vertex2F v2 = __v2f(pVerts[(i+1)%nCount]); Vertex2F n1 = v2fnormalize(v2fperp(v2fsub(v1, v0))); Vertex2F n2 = v2fnormalize(v2fperp(v2fsub(v2, v1))); Vertex2F offset = v2fmult(v2fadd(n1, n2), 1.0/(v2fdot(n1, n2) + 1.0)); struct ExtrudeVerts tmp = {offset, n2}; extrude[i] = tmp; } bool outline = (tBorderColor.a > 0.0 && fBorderWidth > 0.0); unsigned int triangle_count = 3*nCount - 2; unsigned int vertex_count = 3*triangle_count; ensureCapacity(vertex_count); V2F_C4B_T2F_Triangle *triangles = (V2F_C4B_T2F_Triangle *)(m_pBuffer + m_nBufferCount); V2F_C4B_T2F_Triangle *cursor = triangles; float inset = (outline == false ? 0.5 : 0.0); for (long i = 0; i < nCount-2; i++) { Vertex2F v0 = v2fsub(__v2f(pVerts[0 ]), v2fmult(extrude[0 ].offset, inset)); Vertex2F v1 = v2fsub(__v2f(pVerts[i+1]), v2fmult(extrude[i+1].offset, inset)); Vertex2F v2 = v2fsub(__v2f(pVerts[i+2]), v2fmult(extrude[i+2].offset, inset)); V2F_C4B_T2F_Triangle tmp = { {v0, Color4B(tFillColor), __t(v2fzero)}, {v1, Color4B(tFillColor), __t(v2fzero)}, {v2, Color4B(tFillColor), __t(v2fzero)}, }; *cursor++ = tmp; } for(long i = 0; i < nCount; i++) { long j = (i+1)%nCount; Vertex2F v0 = __v2f(pVerts[i]); Vertex2F v1 = __v2f(pVerts[j]); Vertex2F n0 = extrude[i].n; Vertex2F offset0 = extrude[i].offset; Vertex2F offset1 = extrude[j].offset; if(outline) { Vertex2F inner0 = v2fsub(v0, v2fmult(offset0, fBorderWidth)); Vertex2F inner1 = v2fsub(v1, v2fmult(offset1, fBorderWidth)); Vertex2F outer0 = v2fadd(v0, v2fmult(offset0, fBorderWidth)); Vertex2F outer1 = v2fadd(v1, v2fmult(offset1, fBorderWidth)); V2F_C4B_T2F_Triangle tmp1 = { {inner0, Color4B(tBorderColor), __t(v2fneg(n0))}, {inner1, Color4B(tBorderColor), __t(v2fneg(n0))}, {outer1, Color4B(tBorderColor), __t(n0)} }; *cursor++ = tmp1; V2F_C4B_T2F_Triangle tmp2 = { {inner0, Color4B(tBorderColor), __t(v2fneg(n0))}, {outer0, Color4B(tBorderColor), __t(n0)}, {outer1, Color4B(tBorderColor), __t(n0)} }; *cursor++ = tmp2; } else { Vertex2F inner0 = v2fsub(v0, v2fmult(offset0, 0.5)); Vertex2F inner1 = v2fsub(v1, v2fmult(offset1, 0.5)); Vertex2F outer0 = v2fadd(v0, v2fmult(offset0, 0.5)); Vertex2F outer1 = v2fadd(v1, v2fmult(offset1, 0.5)); V2F_C4B_T2F_Triangle tmp1 = { {inner0, Color4B(tFillColor), __t(v2fzero)}, {inner1, Color4B(tFillColor), __t(v2fzero)}, {outer1, Color4B(tFillColor), __t(n0)} }; *cursor++ = tmp1; V2F_C4B_T2F_Triangle tmp2 = { {inner0, Color4B(tFillColor), __t(v2fzero)}, {outer0, Color4B(tFillColor), __t(n0)}, {outer1, Color4B(tFillColor), __t(n0)} }; *cursor++ = tmp2; } } m_nBufferCount += vertex_count; m_bDirty = true; kdFree(extrude); } void DrawNode::clear() { m_nBufferCount = 0; m_bDirty = true; } const BlendFunc& DrawNode::getBlendFunc() const { return m_tBlendFunc; } void DrawNode::setBlendFunc(const BlendFunc &blendFunc) { m_tBlendFunc = blendFunc; } /** listen the event that coming to foreground on Android */ void DrawNode::listenBackToForeground(Object *obj) { init(); } NS_CC_END
mit
kybarg/material-ui
packages/material-ui-icons/src/MissedVideoCallSharp.js
263
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M17 10.5V6H3v12h14v-4.5l4 4v-11l-4 4zM10 15l-3.89-3.89v2.55H5V9.22h4.44v1.11H6.89l3.11 3.1 4.22-4.22.78.79-5 5z" /> , 'MissedVideoCallSharp');
mit
robig/stlab
src/net/robig/stlab/gui/preferences/AbstractPreferenceControl.java
744
package net.robig.stlab.gui.preferences; import javax.swing.JComponent; import javax.swing.JFrame; import net.robig.stlab.util.config.AbstractValue; import net.robig.stlab.util.config.IConfigListener; import net.robig.stlab.util.config.ObjectConfig; public abstract class AbstractPreferenceControl implements IConfigListener { String name=null; AbstractValue<?> configValue=null; JFrame parent=null; public void setParent(JFrame p){ parent=p; } public AbstractPreferenceControl(String name,AbstractValue<?> config) { this.name=name; configValue=config; ObjectConfig.addConfigListener(this); } public String getName() { return name; } public abstract void onChange(); public abstract JComponent getComponent(); }
mit
volodymyr-nakvasiuk/sandbox
src/Application/Gillbus/EtravelsBundle/Entity/Client.php
2068
<?php namespace Application\Gillbus\EtravelsBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Client * * @ORM\Table(name="client") * @ORM\Entity */ class Client { /** * @var string * * @ORM\Column(name="email", type="string", length=80, nullable=false) */ private $email; /** * @var string * * @ORM\Column(name="phone", type="string", length=30, nullable=false) */ private $phone; /** * @var \DateTime * * @ORM\Column(name="date_create", type="datetime", nullable=false) */ private $dateCreate = 'CURRENT_TIMESTAMP'; /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; /** * Set email * * @param string $email * * @return Client */ public function setEmail($email) { $this->email = $email; return $this; } /** * Get email * * @return string */ public function getEmail() { return $this->email; } /** * Set phone * * @param string $phone * * @return Client */ public function setPhone($phone) { $this->phone = $phone; return $this; } /** * Get phone * * @return string */ public function getPhone() { return $this->phone; } /** * Set dateCreate * * @param \DateTime $dateCreate * * @return Client */ public function setDateCreate($dateCreate) { $this->dateCreate = $dateCreate; return $this; } /** * Get dateCreate * * @return \DateTime */ public function getDateCreate() { return $this->dateCreate; } /** * Get id * * @return integer */ public function getId() { return $this->id; } public function __toString() { return $this->email.', '.$this->phone; } }
mit
yogeshsaroya/new-cdnjs
ajax/libs/angular-strap/2.1.5/modules/button.js
129
version https://git-lfs.github.com/spec/v1 oid sha256:a00dc2289daf5baec0ef0e011e74ee133b27fd17750cbc48cd720a97ae670d5d size 6106
mit
jtrauer/AuTuMN_framework
autumn_model/spreadsheet.py
4134
from xlrd import open_workbook from numpy import nan import numpy import os import tool_kit ####################################### ### Individual spreadsheet readers ### ####################################### class GlobalTbReportReader: """ Reader object for the WHO's Global TB Report 2016. Illustrates general structure for spreadsheet readers. """ def __init__(self, country_to_read): self.data = {} self.tab_name = 'TB_burden_countries_2016-04-19' self.key = 'tb' self.parlist = [] self.filename = 'xls/gtb_data.xlsx' self.start_row = 1 self.horizontal = False self.start_column = 0 self.indices = [] self.year_indices = {} self.country_to_read = country_to_read def parse_col(self, col): """ Read and interpret a column of the spreadsheet Args: col: The column to be read """ col = tool_kit.replace_specified_value(col, nan, '') # if it's the country column (the first one), find the indices for the country being simulated if col[0] == 'country': for i in range(len(col)): if col[i] == self.country_to_read: self.indices += [i] # ignore irrelevant columns elif 'iso' in col[0] or 'g_who' in col[0] or 'source' in col[0]: pass # find years to read from year column elif col[0] == 'year': for i in self.indices: self.year_indices[int(col[i])] = i # get data from the remaining (data) columns else: self.data[str(col[0])] = {} for year in self.year_indices: if not numpy.isnan(col[self.year_indices[year]]): self.data[col[0]][year] = col[self.year_indices[year]] def get_data(self): """ Return the read data. """ return self.data ######################### ### Master functions ### ######################### def read_xls_with_sheet_readers(sheet_readers): """ Runs each of the individual readers (currently only one) to gather all the data from the input spreadsheets. Args: sheet_readers: The sheet readers that have been collated into a list Returns: All the data from the reading process as a single object """ result = {} for reader in sheet_readers: # check that the spreadsheet to be read exists try: print('Reading file', os.getcwd(), reader.filename) workbook = open_workbook(reader.filename) # if sheet unavailable, print error message but continue except: print('Unable to open spreadsheet') # if the workbook was found to be available available, read the sheet in question else: sheet = workbook.sheet_by_name(reader.tab_name) # read in the direction that the reader expects (either horizontal or vertical) if reader.horizontal: for i_row in range(reader.start_row, sheet.nrows): reader.parse_row(sheet.row_values(i_row)) else: for i_col in range(reader.start_column, sheet.ncols): reader.parse_col(sheet.col_values(i_col)) result[reader.key] = reader.get_data() return result def read_input_data_xls(sheets_to_read, country=None): """ Compile sheet readers into a list according to which ones have been selected. Note that most readers now take the country in question as an input, while only the fixed parameters sheet reader does not. Args: sheets_to_read: A list containing the strings that are also the 'keys' attribute of each reader country: Country being read Returns: A single data structure containing all the data to be read """ sheet_readers = [] if 'tb' in sheets_to_read: sheet_readers.append(GlobalTbReportReader(country)) for reader in sheet_readers: reader.filename = os.path.join(reader.filename) return read_xls_with_sheet_readers(sheet_readers)
mit
AntonAbramov/angular-study
gulpfile.js
3204
'use strict'; var gulp = require('gulp'), uglify = require('gulp-uglify'), // minify js jshint = require('gulp-jshint'), // linting sourcemaps = require('gulp-sourcemaps'), sass = require('gulp-sass'), // Scss, sass autoprefixer = require('gulp-autoprefixer'), // add prefixes on specific css rules minifycss = require('gulp-minify-css'), // minify css concat = require('gulp-concat'), // concatinate files spritesmith = require('gulp.spritesmith'), // generate scss with sprites info plumber = require('gulp-plumber'), // if any error gulp is not break ngAnnotate = require('gulp-ng-annotate'), htmlmin = require('gulp-htmlmin'), imageop = require('gulp-image-optimization'); // process JS files and return the stream. //gulp.task('js', function () { // return gulp.src('js/*js') // .pipe(plumber()) // .pipe(uglify()); // //.pipe(gulp.dest('dist/js')); //}); gulp.task('images', function(cb) { gulp.src(['img/**/*.png','img/**/*.jpg','img/**/*.gif','img/**/*.jpeg']).pipe(imageop({ optimizationLevel: 7, progressive: true, interlaced: true })).pipe(gulp.dest('public/img')).on('end', cb).on('error', cb); }); gulp.task('js', function () { return gulp.src(['js/**/angular.min.js', 'js/**/*.js']) .pipe(concat('app.js')) .pipe(ngAnnotate()) .pipe(uglify()) .pipe(gulp.dest('./')) .pipe(gulp.dest('public/')); }); // Lint js gulp.task('jshint', function () { return gulp.src('js/**/*.js') .pipe(jshint('.jshintrc')) .pipe(jshint.reporter('jshint-stylish')); }); //generate styles from scss files and minify it gulp.task('sass', function() { return gulp.src('scss/**/*.scss') .pipe(plumber()) .pipe(sass({ style: 'expanded' })) .pipe(autoprefixer({ browsers: ['last 30 versions'], cascade: false })) .pipe(gulp.dest('css')) .pipe(minifycss()) .pipe(gulp.dest('public/css')); }); //generate scss with sprites gulp.task('sprite', function() { var spriteData = gulp.src('./images/icons/*.*') // source path of the sprite images .pipe(spritesmith({ imgName: '../img/sprite.png', cssName: '_sprite.scss', cssFormat: 'scss', algorithm: 'binary-tree' })); spriteData.img.pipe(gulp.dest('./img/')); // output path for the sprite spriteData.css.pipe(gulp.dest('./scss/base/')); // output path for the CSS }); gulp.task('templates', function() { return gulp.src('templates/**/*.html') .pipe(htmlmin({collapseWhitespace: true})) .pipe(gulp.dest('public/templates')); }); gulp.task('htmlIndex', function() { return gulp.src('index.html') .pipe(htmlmin({collapseWhitespace: true})) .pipe(gulp.dest('public/')); }); //watchers gulp.task('watch', function(){ gulp.watch("scss/**/*.scss", ['sass']); gulp.watch("js/**/*.js", ['jshint', 'js']); gulp.watch(['./*.html'], ['htmlIndex']); gulp.watch(['./templates/**.*.html'], ['templates']); }); gulp.task('serve', ['sprite', 'images', 'sass', 'js', 'htmlIndex', 'templates', 'watch']); gulp.task('default', ['sprite', 'sass', 'js'], function () {});
mit
jphacks/KS_1602
db/migrate/20161029060703_create_categories.rb
191
class CreateCategories < ActiveRecord::Migration[5.0] def change create_table :categories do |t| t.integer :CATEDORY_ID t.string :NAME t.timestamps end end end
mit
stas-vilchik/bdd-ml
data/3951.js
2318
{ let action; let current; sequence = typeof value === "object" ? value : sequence.concat(value.split("|")); timedAction( function() { current = sequence.shift(); action = getAction(current); value = getValue(current); switch (action) { case "countdown": value = parseInt(value, 10) || 10; value = value > 0 ? value : 10; timedAction( function(index) { if (index === 0) { if (sequence.length === 0) { S.Shape.switchShape(S.ShapeBuilder.letter("")); } else { performAction(sequence); } } else { S.Shape.switchShape(S.ShapeBuilder.letter(index), true); } }, 1000, value, true ); break; case "rectangle": value = value && value.split("x"); value = value && value.length === 2 ? value : [maxShapeSize, maxShapeSize / 2]; S.Shape.switchShape( S.ShapeBuilder.rectangle( Math.min(maxShapeSize, parseInt(value[0], 10)), Math.min(maxShapeSize, parseInt(value[1], 10)) ) ); break; case "circle": value = parseInt(value, 10) || maxShapeSize; value = Math.min(value, maxShapeSize); S.Shape.switchShape(S.ShapeBuilder.circle(value)); break; case "time": let t = formatTime(new Date()); if (sequence.length > 0) { S.Shape.switchShape(S.ShapeBuilder.letter(t)); } else { timedAction(function() { t = formatTime(new Date()); if (t !== time) { time = t; S.Shape.switchShape(S.ShapeBuilder.letter(time)); } }, 1000); } break; case "icon": S.ShapeBuilder.imageFile(value, function(obj) { S.Shape.switchShape(obj); }); break; default: S.Shape.switchShape( S.ShapeBuilder.letter(current[0] === cmd ? "What?" : current) ); } }, 2000, sequence.length ); }
mit
elearninglondon/ematrix_2015
system/expressionengine/third_party/content_elements/elements/rich_text/views/preview.php
40
<span style="color: black">{value}<span>
mit
erlimar/prototypeguide
src/application/static/js/app/controllers/editor.ctrl.js
4261
/** * @ngdoc module * @name EditorCtrl * @description * * Controller do Editor de Protótipos */ PrototypeGuideApp.controller('EditorCtrl', function ($scope, $compile) { /********************************** Consts ***********************************/ var COMPONENTPREFIX = 'pg', COMPONENTBUTTON = 'button'; /********************************** Publish methods ***********************************/ $scope.export = { mensagem: 'Mensagem na controller EDITOR mudada!', clica: function() { alert('olá!'); } }; $scope.getComponent = function(componentId) { var component_ = jQuery(getTemplate(componentId)); component_.addClass('app-component-editing'); $compile(component_.contents())($scope); return component_; } $scope.mensagem = 'Mensagem na controller EDITOR!'; $scope.mensagem2 = 'Outra msg'; /********************************** Private methods ***********************************/ var componentList_ = [ { id: 'pg.button', template: '<span><button class="btn">Button</button></span>' }, { id: 'pg.button.primary', template: '<span><button class="btn btn-primary">Button Primary</button></span>' }, { id: 'pg.button.warning', template: '<span><button class="btn btn-warning">Button Warning</button></span>' }, { id: 'pg.button.info', template: '<span><button class="btn btn-info">Button Info</button></span>' }, { id: 'pg.button.success', template: '<span><button class="btn btn-success">Button Success</button></span>' }, { id: 'pg.layout.crud1', template: [ '<div class="container-fluid">', ' <div class="row-fluid">', ' <h2>CRUD #1</h2>', ' </div>', ' <div class="row-fluid">', ' <div class="span10">', ' <p>You search form here!</p>', ' </div>', ' <div class="span2">', ' <button class="btn">Search...</button>', ' </div>', ' </div>', ' <div class="row-fluid">', ' <div class="span10">', ' <p>You search form here!</p>', ' </div>', ' <div class="span2">', ' <button class="btn btn-success"><i class="icon-white icon-plus"></i></button>', ' <button class="btn btn-danger"><i class="icon-white icon-minus"></i></button>', ' <button class="btn btn-info"><i class="icon-white icon-edit"></i></button>', ' </div>', ' </div>', ' <div class="row-fluid">', ' <p>Layout CRUD #3</p>', ' </div>', '</div>' ] }, { id: 'pg.alert', template: [ '<div>', ' <alert type="danger">mensagem [{{ 1 + 2 }}] ({{ mensagem + \']][[\' + mensagem2 }} - {{ teste }})</alert>', ' <button class="btn btn-success" ng-click="teste = !teste">Muda!</button>', '</div>' ] }, { id: 'pg.tooltip', template: [ '<span>', '<input type="text" value="Clique aqui!" tooltip="Esta é a dica do campo" tooltip-trigger="focus" tooltip-placement="right" class="form-control" />', '</span>' ] }, { id: 'pg.tooltip2', template: [ '<div>', ' <div class="form-group">', ' <label>Texto do Popup:</label>', ' <input type="text" ng-model="dynamicPopover" class="form-control" value="Digite aqui o valor">', ' </div>', ' <div class="form-group">', ' <label>Título:</label>', ' <input type="text" ng-model="dynamicPopoverTitle" class="form-control" value="Digite o valor aqui">', ' </div>', ' <button popover="{{dynamicPopover}}" popover-title="{{dynamicPopoverTitle}}" class="btn btn-default">Dynamic Popover</button>', '</div>' ] } ]; var getTemplate = function(componentId){ for(var idx in componentList_){ if(componentList_[idx].id == componentId) { var template_ = componentList_[idx].template; if(Array.isArray(template_)) template_ = template_.join('\n'); return template_; } } return null; }; });
mit
PingPlusPlus/pingpp-php
example/charge/channel_extra/cb_alipay.php
461
<?php return [ // 可选,支付类型。默认值为:1(商品购买)。 'payment_type' => '1', // 可选,分账列表。 'split_fund_info' => [ [ 'account' => '2088866088886666', // 接受分账资金的支付宝账户ID。 'amount' => 1, // 分账的金额。 'desc' => 'split_desc desc', // 分账描述信息。 ] ], ];
mit