text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Install the tests and test utilities
import os from setuptools import setup base_dir = os.path.dirname(__file__) with open(os.path.join(base_dir, "README.rst")) as f: long_description = f.read() setup( name="TxSNI", description="easy-to-use SNI endpoint for twisted", packages=[ "txsni", "txsni.test", "txsni.test.certs", "twisted.plugins", ], install_requires=[ "Twisted[tls]>=14.0", "pyOpenSSL>=0.14", ], version="0.1.6", long_description=long_description, license="MIT", url="https://github.com/glyph/txsni", classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: MacOS :: MacOS X", "Operating System :: POSIX", "Operating System :: POSIX :: Linux", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Security :: Cryptography", ], )
import os from setuptools import setup base_dir = os.path.dirname(__file__) with open(os.path.join(base_dir, "README.rst")) as f: long_description = f.read() setup( name="TxSNI", description="easy-to-use SNI endpoint for twisted", packages=[ "txsni", "twisted.plugins", ], install_requires=[ "Twisted[tls]>=14.0", "pyOpenSSL>=0.14", ], version="0.1.6", long_description=long_description, license="MIT", url="https://github.com/glyph/txsni", classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: MacOS :: MacOS X", "Operating System :: POSIX", "Operating System :: POSIX :: Linux", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Security :: Cryptography", ], )
Test for character range regex introduced in bfgex 1.1.1
package br.com.six2six.fixturefactory.function; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertTrue; import org.junit.Test; import br.com.six2six.fixturefactory.function.impl.RegexFunction; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; @RunWith(Parameterized.class) public class RegexFunctionTest { @Parameters(name= "{index}: regex {0}={1}") public static Iterable<String[]> data() { return Arrays.asList(new String[][]{ {"String", "\\w{8}"}, {"Number", "\\d{3,8}"}, {"Phone number", "(\\d{2})-(\\d{4})-(\\d{4})"}, {"MD5", "[0-9a-f]{32}"} }); } private String regexName; private String pattern; public RegexFunctionTest(String regexName, String pattern) { this.regexName = regexName; this.pattern = pattern; } @Test public void testAgainstRegex() { String value = new RegexFunction(pattern).generateValue(); assertNotNull(String.format("Generated %s can not be null", regexName), regexName); assertTrue(String.format("Generated %s (%s) no match with %s", regexName, value, pattern), value.matches(pattern)); } }
package br.com.six2six.fixturefactory.function; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertTrue; import org.junit.Test; import br.com.six2six.fixturefactory.function.impl.RegexFunction; public class RegexFunctionTest { @Test public void regexString() { String pattern = "\\w{8}"; String value = new RegexFunction(pattern).generateValue(); assertNotNull("Generated string can not be null", value); assertTrue(String.format("Generated string no match with %s", pattern), value.matches(pattern)); } @Test public void regexNumber() { String pattern = "\\d{3,8}"; String value = new RegexFunction(pattern).generateValue(); assertNotNull("Generated number can not be null", value); assertTrue(String.format("Generated number no match with %s", pattern), value.matches(pattern)); } @Test public void regexPhoneNumber() { String pattern = "(\\d{2})-(\\d{4})-(\\d{4})"; String value = new RegexFunction(pattern).generateValue(); assertNotNull("Generated phone number can not be null", value); assertTrue(String.format("Generated phone number no match with %s", pattern), value.matches(pattern)); } }
Add guide for how to create test db for mysql
package utils import ( "fmt" "os" _ "github.com/go-sql-driver/mysql" "github.com/jinzhu/gorm" _ "github.com/lib/pq" ) func TestDB() *gorm.DB { dbuser, dbpwd, dbname := "qor", "qor", "qor_test" if os.Getenv("TEST_ENV") == "CI" { dbuser, dbpwd = os.Getenv("DB_USER"), os.Getenv("DB_PWD") } var db gorm.DB var err error if os.Getenv("TEST_DB") == "postgres" { db, err = gorm.Open("postgres", fmt.Sprintf("postgres://%s:%s@localhost/%s?sslmode=disable", dbuser, dbpwd, dbname)) } else { // CREATE USER 'qor'@'localhost' IDENTIFIED BY 'qor'; // CREATE DATABASE qor_test; // GRANT ALL ON qor_test.* TO 'qor'@'localhost'; db, err = gorm.Open("mysql", fmt.Sprintf("%s:%s@/%s?charset=utf8&parseTime=True&loc=Local", dbuser, dbpwd, dbname)) } if err != nil { panic(err) } return &db }
package utils import ( "fmt" "os" _ "github.com/go-sql-driver/mysql" "github.com/jinzhu/gorm" _ "github.com/lib/pq" ) func TestDB() *gorm.DB { dbuser, dbpwd, dbname := "qor", "qor", "qor_test" if os.Getenv("TEST_ENV") == "CI" { dbuser, dbpwd = os.Getenv("DB_USER"), os.Getenv("DB_PWD") } var db gorm.DB var err error if os.Getenv("TEST_DB") == "postgres" { db, err = gorm.Open("postgres", fmt.Sprintf("postgres://%s:%s@localhost/%s?sslmode=disable", dbuser, dbpwd, dbname)) } else { db, err = gorm.Open("mysql", fmt.Sprintf("%s:%s@/%s?charset=utf8&parseTime=True&loc=Local", dbuser, dbpwd, dbname)) } if err != nil { panic(err) } return &db }
Move private function to outside of exported scope
var winston = require('winston'), utils = require('../utils'); function boundVolume(vol) { if(vol < 0) { vol = 0; } else if(vol > 100) { vol = 100; } return vol; } module.exports = function(radio, command, logger) { logger = logger || winston; var commandPromise; if(command.hasOwnProperty('value')) { var absoluteVol = parseInt(command.value); commandPromise = radio.sendCommands([ ['setvol', boundVolume(absoluteVol)] ]); } else if(command.hasOwnProperty('diff')) { commandPromise = radio.status() .then(function(statusString) { var volume = statusString.match(/volume: (\d{1,3})$/m)[1]; var newVol = parseInt(volume)+parseInt(command.diff); return radio.sendCommands([['setvol', boundVolume(newVol)]]); }, utils.failedPromiseHandler()); } return commandPromise; };
var winston = require('winston'), utils = require('../utils'); module.exports = function(radio, command, logger) { logger = logger || winston; function boundVolume(vol) { if(vol < 0) { vol = 0; } else if(vol > 100) { vol = 100; } return vol; } var commandPromise; if(command.hasOwnProperty('value')) { var absoluteVol = parseInt(command.value); commandPromise = radio.sendCommands([ ['setvol', boundVolume(absoluteVol)] ]); } else if(command.hasOwnProperty('diff')) { commandPromise = radio.status() .then(function(statusString) { var volume = statusString.match(/volume: (\d{1,3})$/m)[1]; var newVol = parseInt(volume)+parseInt(command.diff); return radio.sendCommands([['setvol', boundVolume(newVol)]]); }, utils.failedPromiseHandler()); } return commandPromise; };
Update loader config for test.
<?php /** * PHPCI - Continuous Integration for PHP * * @copyright Copyright 2013, Block 8 Limited. * @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md * @link http://www.phptesting.org/ */ // Let PHP take a guess as to the default timezone, if the user hasn't set one: date_default_timezone_set(@date_default_timezone_get()); // Load Composer autoloader: require_once(dirname(__DIR__) . '/vendor/autoload.php'); // If the PHPCI config file is not where we expect it, try looking in // env for an alternative config path. $configFile = dirname(__FILE__) . '/../PHPCI/config.yml'; if (!file_exists($configFile)) { $configEnv = getenv('phpci_config_file'); if (!empty($configEnv)) { $configFile = $configEnv; } } // Load configuration if present: $conf = array(); $conf['b8']['app']['namespace'] = 'PHPCI'; $conf['b8']['app']['default_controller'] = 'Home'; $conf['b8']['view']['path'] = dirname(__DIR__) . '/PHPCI/View/'; $config = new b8\Config($conf); if (file_exists($configFile)) { $config->loadYaml($configFile); } require_once(dirname(__DIR__) . '/vars.php'); \PHPCI\Helper\Lang::init($config);
<?php /** * PHPCI - Continuous Integration for PHP * * @copyright Copyright 2013, Block 8 Limited. * @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md * @link http://www.phptesting.org/ */ // Let PHP take a guess as to the default timezone, if the user hasn't set one: date_default_timezone_set(@date_default_timezone_get()); // Load Composer autoloader: require_once(dirname(__DIR__) . '/vendor/autoload.php'); // Load configuration if present: $conf = array(); $conf['b8']['app']['namespace'] = 'PHPCI'; $conf['b8']['app']['default_controller'] = 'Home'; $conf['b8']['view']['path'] = dirname(__DIR__) . '/../PHPCI/View/'; // If the PHPCI config file is not where we expect it, try looking in // env for an alternative config path. $configFile = dirname(__FILE__) . '/../PHPCI/config.yml'; if (!file_exists($configFile)) { $configEnv = getenv('phpci_config_file'); if (!empty($configEnv)) { $configFile = $configEnv; } } $config = new b8\Config($conf); if (file_exists($configFile)) { $config->loadYaml($configFile); } require_once(dirname(__DIR__) . '/vars.php'); \PHPCI\Helper\Lang::init($config);
Remove first image to be used as cover for post
/** * Main JS file for Casper behaviours */ /*globals jQuery, document */ (function ($) { "use strict"; $(document).ready(function(){ $(".post-content").fitVids(); /** * Add parallax effect for blog cover photo */ $(window).stellar({ horizontalScrolling: false, parallaxElements: true }); /** * Set first image as cover photo for post */ //// var mainImage = $('img[alt="main-image"]'); var mainImage = $('.post-content').find('img').first(); if ( mainImage.length > 0){ var mainImageSource = mainImage.attr('src'); $('.post-header').css('background-image','url('+mainImageSource+')'); mainImage.remove(); } }); }(jQuery));
/** * Main JS file for Casper behaviours */ /*globals jQuery, document */ (function ($) { "use strict"; $(document).ready(function(){ $(".post-content").fitVids(); /** * Add parallax effect for blog cover photo */ $(window).stellar({ horizontalScrolling: false, parallaxElements: true }); /** * Set first image as cover photo for post */ //// var mainImage = $('img[alt="main-image"]'); var mainImage = $('.post-content').find('img').first(); if ( mainImage.length > 0){ var mainImageSource = mainImage.attr('src'); $('.post-header').css('background-image','url('+mainImageSource+')'); // mainImage.remove(); } }); }(jQuery));
Use mediumtext instead of text
/** * hive.js * Copyright (C) 2013-2016 Marcel Klehr <mklehr@gmx.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the Mozilla Public License version 2 * as published by the Mozilla Foundation. * * This program 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 General Public License for more details.te * * You should have received a copy of the Mozilla Public License * along with this program. If not, see <https://www.mozilla.org/en-US/MPL/2.0/>. */ /** * Snapshot */ module.exports = { identity: 'snapshot' , connection: 'default' , autoPK: false , attributes: { id: { type: 'string' , primaryKey: true } // the changeset , changes: 'mediumtext' // the content resulting from the changes , contents: 'mediumtext' // belongsTo a document , document: { model: 'document' } // belongsTo an author , author: { model: 'user' } , parent: { model: 'snapshot' } //Automagically created: //, createdAt //, updatedAt } // Class methods , post: function*() { this.throw(403) } }
/** * hive.js * Copyright (C) 2013-2016 Marcel Klehr <mklehr@gmx.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the Mozilla Public License version 2 * as published by the Mozilla Foundation. * * This program 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 General Public License for more details. * * You should have received a copy of the Mozilla Public License * along with this program. If not, see <https://www.mozilla.org/en-US/MPL/2.0/>. */ /** * Snapshot */ module.exports = { identity: 'snapshot' , connection: 'default' , autoPK: false , attributes: { id: { type: 'string' , primaryKey: true } // the changeset , changes: 'text' // the content resulting from the changes , contents: 'text' // belongsTo a document , document: { model: 'document' } // belongsTo an author , author: { model: 'user' } , parent: { model: 'snapshot' } //Automagically created: //, createdAt //, updatedAt } // Class methods , post: function*() { this.throw(403) } }
Add is_ha variable to change config rollback
# -*- coding: utf-8 -*- import logging from workflow.steps.mysql.resize import run_vm_script from workflow.steps.util.base import BaseStep LOG = logging.getLogger(__name__) class ChangeDatabaseConfigFile(BaseStep): def __unicode__(self): return "Changing database config file..." def do(self, workflow_dict): context_dict = { 'CONFIGFILE': True, 'IS_HA': workflow_dict['databaseinfra'].plan.is_ha }, ret_script = run_vm_script( workflow_dict=workflow_dict, context_dict=context_dict, script=workflow_dict['cloudstackpack'].script, ) return ret_script def undo(self, workflow_dict): context_dict = { 'CONFIGFILE': True, 'IS_HA': workflow_dict['databaseinfra'].plan.is_ha, } ret_script = run_vm_script( workflow_dict=workflow_dict, context_dict=context_dict, script=workflow_dict['original_cloudstackpack'].script, ) return ret_script
# -*- coding: utf-8 -*- import logging from . import run_vm_script from ...util.base import BaseStep LOG = logging.getLogger(__name__) class ChangeDatabaseConfigFile(BaseStep): def __unicode__(self): return "Changing database config file..." def do(self, workflow_dict): context_dict = { 'CONFIGFILE': True, 'IS_HA': workflow_dict['databaseinfra'].plan.is_ha }, ret_script = run_vm_script( workflow_dict=workflow_dict, context_dict=context_dict, script=workflow_dict['cloudstackpack'].script, ) return ret_script def undo(self, workflow_dict): context_dict = { 'CONFIGFILE': True, } ret_script = run_vm_script( workflow_dict=workflow_dict, context_dict=context_dict, script=workflow_dict['original_cloudstackpack'].script, ) return ret_script
Fix bug - wrong variable after her rename
<?php /** * Model * * @author: Michal Hojgr <michal.hojgr@gmail.com> * */ class ModLoader { /** * @var Cache */ private $cache; /** * @var ModMapper */ private $modMapper; /** * @param Cache $cache * @param ModMapper $modMapper */ public function __construct(Cache $cache, ModMapper $modMapper) { $this->cache = $cache; $this->modMapper = $modMapper; } /** * Loads all versions, caches them and in case that * cache was made recently, it reads from cache * * @param int $count how many versions to show * @param int $start * @return array */ public function getVersions($count, $start = 0) { /** * Load from cache */ $files = $this->cache->getCachedVersions($this->modMapper); /** * Get latest version and the others */ $latest = $files[0]; unset($files[0]); $others = array_values($files); // buffer count so it must not count every loop $buffer_count = count($others); for($i = 0; $i < $count; $i++) { if($i < $start || $i > $start + $buffer_count) unset($others[$i]); } return array("latest" => $latest, "others" => $others); } }
<?php /** * Model * * @author: Michal Hojgr <michal.hojgr@gmail.com> * */ class ModLoader { /** * @var Cache */ private $cache; /** * @var ModMapper */ private $modMapper; /** * @param Cache $cache * @param ModMapper $modMapper */ public function __construct(Cache $cache, ModMapper $modMapper) { $this->cache = $cache; $this->modMapper = $modMapper; } /** * Loads all versions, caches them and in case that * cache was made recently, it reads from cache * * @param int $count how many versions to show * @param int $start * @return array */ public function getVersions($count, $start = 0) { /** * Load from cache */ $files = $this->cache->getCachedVersions($this->modMapper); /** * Get latest version and the others */ $latest = $files[0]; unset($files[0]); $others = array_values($files); // buffer count so it must not count every loop $buffer_count = count($others); for($i = 0; $i < $count; $i++) { if($i < $start || $i > $start + $count) unset($others[$i]); } return array("latest" => $latest, "others" => $others); } }
Add API to LmdbReader (used by gan_features.py)
# Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import lmdb class DbReader(object): """ Reads a database """ def __init__(self, location): """ Arguments: location -- where is the database """ self._db = lmdb.open( location, map_size=1024**3, # 1MB readonly=True, lock=False) with self._db.begin() as txn: self.total_entries = txn.stat()['entries'] self.txn = self._db.begin() def entries(self): """ Generator returning all entries in the DB """ with self._db.begin() as txn: cursor = txn.cursor() for item in cursor: yield item def entry(self, key): """Return single entry""" return self.txn.get(key)
# Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved. from __future__ import absolute_import import lmdb class DbReader(object): """ Reads a database """ def __init__(self, location): """ Arguments: location -- where is the database """ self._db = lmdb.open( location, map_size=1024**3, # 1MB readonly=True, lock=False) with self._db.begin() as txn: self.total_entries = txn.stat()['entries'] def entries(self): """ Generator returning all entries in the DB """ with self._db.begin() as txn: cursor = txn.cursor() for item in cursor: yield item
Add new CertificationTypes for section compliance
package types const ( ZigbeeCertificationType string = "zigbee" MatterCertificationType string = "matter" AccessControlType string = "access control" ProductSecurityType string = "product security" ) // List of Certification Types type CertificationTypes []string var CertificationTypesList = CertificationTypes{ZigbeeCertificationType, MatterCertificationType, AccessControlType, ProductSecurityType} func IsValidCertificationType(certificationType string) bool { for _, i := range CertificationTypesList { if i == certificationType { return true } } return false } const ( CodeProvisional uint32 = 1 CodeCertified uint32 = 2 CodeRevoked uint32 = 3 ) const ( ParentPFCCertificationRoute = "parent" ChildPFCCertificationRoute = "child" DefaultPFCCertificationRoute = "" ) // List of PFC Certification Routes. type PFCCertificationRoutes []string var PFCCertificationRouteList = PFCCertificationRoutes{ParentPFCCertificationRoute, ChildPFCCertificationRoute, DefaultPFCCertificationRoute} func IsValidPFCCertificationRoute(certificationRoute string) bool { for _, i := range PFCCertificationRouteList { if i == certificationRoute { return true } } return false }
package types const ( ZigbeeCertificationType string = "zigbee" MatterCertificationType string = "matter" ) // List of Certification Types type CertificationTypes []string var CertificationTypesList = CertificationTypes{ZigbeeCertificationType, MatterCertificationType} func IsValidCertificationType(certificationType string) bool { for _, i := range CertificationTypesList { if i == certificationType { return true } } return false } const ( CodeProvisional uint32 = 1 CodeCertified uint32 = 2 CodeRevoked uint32 = 3 ) const ( ParentPFCCertificationRoute = "parent" ChildPFCCertificationRoute = "child" DefaultPFCCertificationRoute = "" ) // List of PFC Certification Routes. type PFCCertificationRoutes []string var PFCCertificationRouteList = PFCCertificationRoutes{ParentPFCCertificationRoute, ChildPFCCertificationRoute, DefaultPFCCertificationRoute} func IsValidPFCCertificationRoute(certificationRoute string) bool { for _, i := range PFCCertificationRouteList { if i == certificationRoute { return true } } return false }
Remove number of talks variable from pages that dont use it. The speaker package and the talk ideas pages didn't use the number_of_talks variable, so it had no sense to give it to them. Since it is now only used in one place it makes more sense to inline it
<?php declare(strict_types=1); /** * Copyright (c) 2013-2017 OpenCFP * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. * * @see https://github.com/opencfp/opencfp */ namespace OpenCFP\Http\Controller; use OpenCFP\Domain\Model\Talk; use Symfony\Component\HttpFoundation\Response; class PagesController extends BaseController { public function showHomepage(): Response { return $this->render('home.twig', [ 'number_of_talks' => Talk::count(), ]); } public function showSpeakerPackage(): Response { return $this->render('package.twig'); } public function showTalkIdeas(): Response { return $this->render('ideas.twig'); } }
<?php declare(strict_types=1); /** * Copyright (c) 2013-2017 OpenCFP * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. * * @see https://github.com/opencfp/opencfp */ namespace OpenCFP\Http\Controller; use OpenCFP\Domain\Model\Talk; use Symfony\Component\HttpFoundation\Response; class PagesController extends BaseController { public function showHomepage(): Response { return $this->render('home.twig', $this->getContextWithTalksCount()); } public function showSpeakerPackage(): Response { return $this->render('package.twig', $this->getContextWithTalksCount()); } public function showTalkIdeas(): Response { return $this->render('ideas.twig', $this->getContextWithTalksCount()); } private function getContextWithTalksCount() { return ['number_of_talks' => Talk::count()]; } }
Add Python 3.4 and 3.5 to classifiers
from setuptools import setup setup( name='tldr', version="0.1.3", author='Felix Yan', author_email='felixonmars@gmail.com', url='https://github.com/felixonmars/tldr-python-client', description='command line client for tldr', license='MIT', py_modules=['tldr'], scripts=['tldr.py'], install_requires=['six', 'termcolor', 'colorama'], tests_require=[ 'pytest-runner', ], entry_points={ 'console_scripts': ['tldr = tldr:main'] }, classifiers=[ "Development Status :: 4 - Beta", "License :: OSI Approved :: MIT License", "Environment :: Console", "Intended Audience :: End Users/Desktop", "Natural Language :: English", "Operating System :: POSIX :: Linux", "Operating System :: MacOS :: MacOS X", "Operating System :: POSIX :: SunOS/Solaris", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Topic :: Utilities", "Topic :: System" ] )
from setuptools import setup setup( name='tldr', version="0.1.3", author='Felix Yan', author_email='felixonmars@gmail.com', url='https://github.com/felixonmars/tldr-python-client', description='command line client for tldr', license='MIT', py_modules=['tldr'], scripts=['tldr.py'], install_requires=['six', 'termcolor', 'colorama'], tests_require=[ 'pytest-runner', ], entry_points={ 'console_scripts': ['tldr = tldr:main'] }, classifiers=[ "Development Status :: 4 - Beta", "License :: OSI Approved :: MIT License", "Environment :: Console", "Intended Audience :: End Users/Desktop", "Natural Language :: English", "Operating System :: POSIX :: Linux", "Operating System :: MacOS :: MacOS X", "Operating System :: POSIX :: SunOS/Solaris", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Topic :: Utilities", "Topic :: System" ] )
Fix HTTP service error message.
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Log; class HTTPServiceProvider extends ServiceProvider { /** * Indicates that the loading of this provider is deferred. * * @var bool */ protected $defer = true; /** * Bootstrap any HTTP services. * * @return void */ public function boot() { // } /** * Register any HTTP services. * * @return void */ public function register() { if (function_exists('curl_version')) { $driver = 'cURLService'; } else if (ini_get('allow_url_fopen')) { $driver = 'fopenService'; } else { Log::error('Load the cURL module or enable allow_url_fopen in your PHP configuration.'); } $this->app->singleton('App\Contracts\HTTP', 'App\Services\HTTP\\'.$driver); } /** * Get the services provided by this provider. * * @return array */ public function provides() { return ['App\Contracts\HTTP']; } }
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class HTTPServiceProvider extends ServiceProvider { /** * Indicates that the loading of this provider is deferred. * * @var bool */ protected $defer = true; /** * Bootstrap any HTTP services. * * @return void */ public function boot() { // } /** * Register any HTTP services. * * @return void */ public function register() { if (function_exists('curl_version')) { $driver = 'cURLService'; } else if (ini_get('allow_url_fopen')) { $driver = 'fopenService'; } else { Log::error('Load the cURL module or enable allow_url_fopen in your PHP configuration.'); } $this->app->singleton('App\Contracts\HTTP', 'App\Services\HTTP\\'.$driver); } /** * Get the services provided by this provider. * * @return array */ public function provides() { return ['App\Contracts\HTTP']; } }
Fix logic around lost connection.
"""Test client that connects and sends infinite data.""" import sys from tulip import * def dprint(*args): print('source:', *args, file=sys.stderr) class Client(Protocol): data = b'x'*16*1024 def connection_made(self, tr): dprint('connecting to', tr.get_extra_info('addr')) self.tr = tr self.lost = False self.loop = get_event_loop() self.waiter = Future() self.write_some_data() def write_some_data(self): if self.lost: dprint('lost already') return dprint('writing', len(self.data), 'bytes') self.tr.write(self.data) self.loop.call_soon(self.write_some_data) def connection_lost(self, exc): dprint('lost connection', repr(exc)) self.lost = True self.waiter.set_result(None) @coroutine def start(loop): tr, pr = yield from loop.create_connection(Client, 'localhost', 1111) dprint('tr =', tr) dprint('pr =', pr) res = yield from pr.waiter return res def main(): loop = get_event_loop() loop.run_until_complete(start(loop)) if __name__ == '__main__': main()
"""Test client that connects and sends infinite data.""" import sys from tulip import * def dprint(*args): print('source:', *args, file=sys.stderr) class Client(Protocol): data = b'x'*16*1024 def connection_made(self, tr): dprint('connecting to', tr.get_extra_info('addr')) self.tr = tr self.lost = False self.loop = get_event_loop() self.waiter = Future() self.write_some_data() def write_some_data(self): dprint('writing', len(self.data), 'bytes') self.tr.write(self.data) if not self.lost: self.loop.call_soon(self.write_some_data) def connection_lost(self, exc): dprint('lost connection', repr(exc)) self.lost = True self.waiter.set_result(None) @coroutine def start(loop): tr, pr = yield from loop.create_connection(Client, 'localhost', 1111) dprint('tr =', tr) dprint('pr =', pr) res = yield from pr.waiter return res def main(): loop = get_event_loop() loop.run_until_complete(start(loop)) if __name__ == '__main__': main()
Add part message to event
<?php namespace Dan\Irc\Packets; use Dan\Contracts\PacketContract; use Dan\Irc\Connection; class PacketPart implements PacketContract { public function handle(Connection $connection, array $from, array $data) { if($from[0] != $connection->user->nick()) { $channel = $connection->getChannel($data[0]); $channel->removeUser($from[0]); } else $connection->removeChannel($data[0]); event('irc.packets.part', [ 'user' => user($from), 'channel' => $connection->getChannel($data[0]), 'connection' => $connection, 'message' => $data[1] ?? null ]); if(!DEBUG) console("[<magenta>{$connection->getName()}</magenta>] <yellow>{$from[0]}</yellow> <cyan>left {$data[0]}</cyan>"); } }
<?php namespace Dan\Irc\Packets; use Dan\Contracts\PacketContract; use Dan\Irc\Connection; class PacketPart implements PacketContract { public function handle(Connection $connection, array $from, array $data) { if($from[0] != $connection->user->nick()) { $channel = $connection->getChannel($data[0]); $channel->removeUser($from[0]); } else $connection->removeChannel($data[0]); event('irc.packets.part', [ 'user' => user($from), 'channel' => $connection->getChannel($data[0]), 'connection' => $connection ]); if(!DEBUG) console("[<magenta>{$connection->getName()}</magenta>] <yellow>{$from[0]}</yellow> <cyan>left {$data[0]}</cyan>"); } }
Fix lint errors in test server
#!/usr/bin/env node /** * Minimal server for local, manual web page testing. */ /* eslint-disable strict, no-console *//* tslint:disable no-console */ 'use strict'; const portfinder = require('portfinder'); const http = require('http'); const path = require('path'); const nodeStatic = require('node-static'); const webroot = path.resolve(process.argv[2]); portfinder.basePort = Number(process.env.PORT) || 1234; const fileServer = new nodeStatic.Server(webroot, { cache: false }); const server = http.createServer((req, res) => { req.on('end', () => { fileServer.serve(req, res, (err) => { if (err) { console.error(`Error serving ${req.url} - ${err.message}`); res.writeHead(err.status, err.headers); res.end(); } }); }).resume(); }); portfinder .getPortPromise() .then((port) => { server.listen(port, () => { console.log(`\nTesting server running on http://localhost:${port}`); }); }) .catch((err) => { throw err; }); process.on('SIGINT', () => { console.log('\nServer terminated'); try { server.close(() => { process.exit(0); }); } catch (err) { console.error(err); process.exit(1); } });
#!/usr/bin/env node /** * Minimal server for local, manual web page testing. */ 'use strict'; // eslint-disable-line const portfinder = require('portfinder'); const http = require('http'); const path = require('path'); const nodeStatic = require('node-static'); const webroot = path.resolve(process.argv[2]); portfinder.basePort = Number(process.env.PORT) || 1234; const fileServer = new nodeStatic.Server(webroot, { cache: false }); const server = http.createServer((req, res) => { req.on('end', () => { fileServer.serve(req, res, (err) => { if (err) { console.error(`Error serving ${req.url} - ${err.message}`); res.writeHead(err.status, err.headers); res.end(); } }); }).resume(); }); portfinder .getPortPromise() .then((port) => { server.listen(port, () => { console.log(`\nTesting server running on http://localhost:${port}`); }); }) .catch((err) => { throw err; }); process.on('SIGINT', () => { console.log('\nServer terminated'); try { server.close(() => { process.exit(0); }); } catch (err) { console.error(err); process.exit(1); } });
Fix all the bugs in writing data and confirming clear
var ipc = require('ipc') var fs = require('fs') var userData = require('./user-data.js') document.addEventListener('DOMContentLoaded', function (event) { var data = userData.getData() var clearAllButton = document.getElementById('clear-all-challenges') updateIndex(data.contents) ipc.on('confirm-clear-response', function (response) { if (response === 1) return else clearAllChallenges(data) }) clearAllButton.addEventListener('click', function () { ipc.send('confirm-clear') }) function updateIndex (data) { for (var chal in data) { if (data[chal].completed) { var currentText = document.getElementById(chal).innerHTML var completedText = "<span class='completed-challenge-list'>[ Completed ]</span>" document.getElementById(chal).innerHTML = completedText + ' ' + currentText } } } }) function clearAllChallenges (data) { for (var chal in data.contents) { if (data.contents[chal].completed) { data.contents[chal].completed = false var completedElement = '#' + chal + ' .completed-challenge-list' document.querySelector(completedElement).remove() } } fs.writeFileSync(data.path, JSON.stringify(data.contents, null, 2)) }
var ipc = require('ipc') var userData = require('./user-data.js') document.addEventListener('DOMContentLoaded', function (event) { var data = userData.getData() updateIndex(data.contents) ipc.on('confirm-clear-response', function (response) { if (response === 1) return else clearAllChallenges() }) var clearAllButton = document.getElementById('clear-all-challenges') clearAllButton.addEventListener('click', function () { for (var chal in data) { if (data[chal].completed) { data[chal].completed = false var completedElement = '#' + chal + ' .completed-challenge-list' document.querySelector(completedElement).remove() } } userData.updateData(data, function (err) { // this takes in a challenge, which you're not doing if (err) return console.log(err) }) }) function updateIndex (data) { for (var chal in data) { if (data[chal].completed) { var currentText = document.getElementById(chal).innerHTML var completedText = "<span class='completed-challenge-list'>[ Completed ]</span>" document.getElementById(chal).innerHTML = completedText + ' ' + currentText } } } })
Use map for smarter iteration.
def read_file(filename): # Open the file file_obj = open(filename) # Iterate over lines in the file for line in file_obj: # Split line by spaces (creates a list) # Alternatives: split(',') numbers = line.split() if len(numbers) != 2: # Convert strings to numbers # map() calls the first argument on every item in the second # argument and returns a list of results. numbers = map(float, numbers) else: # We're processing a header print 'Skipping header line' return contents # Just for debugging purposes read_file('data.txt')
def read_file(filename): # Open the file file_obj = open(filename) # Iterate over lines in the file for line in file_obj: # Split line by spaces (creates a list) # Alternatives: split(',') numbers = line.split() if len(numbers) != 2: # Convert strings to numbers numbers2 = [] for number in numbers: # Convert number to float number = float(number) # Append to temperary list numbers2.append(number) # Replace numbers by numbers2 numbers = numbers2 else: # We're processing a header print 'Skipping header line' return contents # Just for debugging purposes read_file('data.txt')
[CleanUp] Remove redundant @version phpdoc tag
<?php /** * @title API Interface * * @author Pierre-Henry Soria <ph7software@gmail.com> * @copyright (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / Framework / Payment / Gateway / Api */ namespace PH7\Framework\Payment\Gateway\Api; defined('PH7') or exit('Restricted access'); interface Api { /** * Get Checkout URL. * * @param string $sOptionalParam Default '' * * @return string */ public function getUrl($sOptionalParam = ''); /** * Get message status. * * @return string */ public function getMsg(); /** * Check if the transaction is valid. * * @param string $sOptionalParam1 Default '' * @param string $sOptionalParam2 Default '' * * @return boolean */ public function valid($sOptionalParam1 = '', $sOptionalParam2 = ''); }
<?php /** * @title API Interface * * @author Pierre-Henry Soria <ph7software@gmail.com> * @copyright (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / Framework / Payment / Gateway / Api * @version 1.0 */ namespace PH7\Framework\Payment\Gateway\Api; defined('PH7') or exit('Restricted access'); interface Api { /** * Get Checkout URL. * * @param string $sOptionalParam Default '' * * @return string */ public function getUrl($sOptionalParam = ''); /** * Get message status. * * @return string */ public function getMsg(); /** * Check if the transaction is valid. * * @param string $sOptionalParam1 Default '' * @param string $sOptionalParam2 Default '' * * @return boolean */ public function valid($sOptionalParam1 = '', $sOptionalParam2 = ''); }
Add runCmd method to execute CMD handlers
// test/lib/TempDir.js // 'use strict'; var cmds = require('../../lib/commands'); var fs = require('fs'); var path = require('path'); var spawnSync = require('child_process').spawnSync; var mkdirp = require('mkdirp'); var rimraf = require('rimraf'); var TempDir = { tmpLocation: null, prepare: function () { mkdirp.sync(this.tmpLocation); }, clean: function () { rimraf.sync(this.tmpLocation); }, getPath: function (name) { return path.join(this.tmpLocation, name); }, read: function (name) { return fs.readFileSync(this.getPath(name), 'utf8'); }, readJson: function (name) { return JSON.parse(this.read(name)); }, exists: function (name) { return fs.accessSync(path.join(this.tmpLocation, name), fs.F_OK); }, runCmd: function (cmd, argv) { argv = [cmd].concat(argv); return cmds[cmd](argv, this.tmpLocation); }, collider: function (args) { args = args || []; return spawnSync('collider', args, { cwd: this.tmpLocation }); }, }; module.exports = TempDir;
// test/lib/TempDir.js // 'use strict'; var fs = require('fs'); var path = require('path'); var spawnSync = require('child_process').spawnSync; var mkdirp = require('mkdirp'); var rimraf = require('rimraf'); var TempDir = { tmpLocation: null, prepare: function () { mkdirp.sync(this.tmpLocation); }, clean: function () { rimraf.sync(this.tmpLocation); }, getPath: function (name) { return path.join(this.tmpLocation, name); }, read: function (name) { return fs.readFileSync(this.getPath(name), 'utf8'); }, readJson: function (name) { return JSON.parse(this.read(name)); }, exists: function (name) { return fs.accessSync(path.join(this.tmpLocation, name), fs.F_OK); }, collider: function (args) { args = args || []; return spawnSync('collider', args, { cwd: this.tmpLocation }); }, }; module.exports = TempDir;
Add EbicsPy Launchpad repository url
# -*- coding: utf-8 -*- { 'name': "l10n_fr_ebics", 'summary': """Implementation of the EBICS banking protocol""", 'description': """ This module provides an interface to echanges files with banks. It's curently a beta version. This module isbased on the library ebicsPy. It maps Odoo with the ebicspy API. https://code.launchpad.net/~aurelien-dumaine/+junk/ebicspy This program 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. """, 'author': "Aurélien DUMAINE - aurelien.dumaine@free.fr", 'website': "http://www.dumaine.me", # Categories can be used to filter modules in modules listing # Check https://github.com/odoo/odoo/blob/master/openerp/addons/base/module/module_data.xml # for the full list 'category': 'Uncategorized', 'version': '0.1', # any module necessary for this one to work correctly 'depends': ['base'], # always loaded 'data': [ # 'security/ir.model.access.csv', 'templates.xml', 'views/ebics.xml', ], # only loaded in demonstration mode 'demo': [ 'demo.xml', ], }
# -*- coding: utf-8 -*- { 'name': "l10n_fr_ebics", 'summary': """Implementation of the EBICS banking protocol""", 'description': """ This module provides an interface to echanges files with banks. It's curently a beta version. This program 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. """, 'author': "Aurélien DUMAINE - aurelien.dumaine@free.fr", 'website': "http://www.dumaine.me", # Categories can be used to filter modules in modules listing # Check https://github.com/odoo/odoo/blob/master/openerp/addons/base/module/module_data.xml # for the full list 'category': 'Uncategorized', 'version': '0.1', # any module necessary for this one to work correctly 'depends': ['base'], # always loaded 'data': [ # 'security/ir.model.access.csv', 'templates.xml', 'views/ebics.xml', ], # only loaded in demonstration mode 'demo': [ 'demo.xml', ], }
Add role assignments foreign keys to db
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateRoleAssignmentsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('party_assignments', function (Blueprint $table) { $table->uuid('party_uuid'); $table->foreign('party_uuid')->references('uuid')->on('parties'); $table->uuid('agreement_uuid'); $table->foreign('agreement_uuid')->references('uuid')->on('agreements'); $table->uuid('role_uuid'); $table->foreign('role_uuid')->references('uuid')->on('roles'); $table->unique(['role_uuid', 'agreement_uuid']); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('role_assignments'); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateRoleAssignmentsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('party_assignments', function (Blueprint $table) { $table->uuid('party_uuid'); $table->uuid('agreement_uuid'); $table->uuid('role_uuid'); $table->unique(['role_uuid', 'agreement_uuid']); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('role_assignments'); } }
Simplify - Less is more
#!/usr/local/bin/python3 -u __author__ = 'Oliver Ratzesberger <https://github.com/fxstein>' __copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger' __license__ = 'Apache License, Version 2.0' # Make sure we have access to SentientHome commons import os, sys sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..') # Sentient Home configuration from common.shconfig import shConfig from common.sheventhandler import shEventHandler import logging as log import time # Simple tracer that 'fires' events on a predefined interval config = shConfig('~/.config/home/home.cfg', name='SentientHome Tracer') handler = shEventHandler(config, config.getfloat('sentienthome', 'tracer_interval', 10)) count = 0 while True: count += 1 event = [{ 'name': 'tracer', # Time Series Name 'columns': ['time', 'count'], # Keys # time in milliseconds since epoch 'points': [[time.time()*1000, count]] # Data points }] log.debug('Event data: %s', event) handler.postEvent(event) # We reset the poll interval in case the configuration has changed handler.sleep(config.getfloat('sentienthome', 'tracer_interval', 10))
#!/usr/local/bin/python3 -u __author__ = 'Oliver Ratzesberger <https://github.com/fxstein>' __copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger' __license__ = 'Apache License, Version 2.0' # Make sure we have access to SentientHome commons import os, sys sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..') # Sentient Home configuration from common.shconfig import shConfig from common.sheventhandler import shEventHandler import logging as log import time # Simple tracer that 'fires' events on a predefined interval config = shConfig('~/.config/home/home.cfg', name='SentientHome Tracer') handler = shEventHandler(config, config.getfloat('sentienthome', 'tracer_interval', 10)) count = 0 while True: count += 1 # time in milliseconds since epoch tm = time.time()*1000 event = [{ 'name': 'tracer', # Time Series Name 'columns': ['time', 'count'], # Keys 'points': [[tm, count]] # Data points }] log.debug('Event data: %s', event) handler.postEvent(event) # We reset the poll interval in case the configuration has changed handler.sleep(config.getfloat('sentienthome', 'tracer_interval', 10))
Include signInStrategy for future updates
'use strict'; var express = require('express'); var kraken = require('kraken-js'); var db = require('./lib/db'); var crypto = require('./lib/crypto'); var passport = require('passport'); var signUpStrategy= require('./lib/registration');//?? //var signInStrategy = require('./lib/login'); var options, app; /* * Create and configure application. Also exports application instance for use by tests. * See https://github.com/krakenjs/kraken-js#options for additional configuration options. */ options = { onconfig: function (config, next) { /* * Add any additional config setup or overrides here. `config` is an initialized * `confit` (https://github.com/krakenjs/confit/) configuration object. */ db.config(config.get('databaseConfig')); signUpStrategy(passport); //??? //signInStrategy(passport); var cryptConfig = config.get('bcrypt'); crypto.setCryptoLevel(cryptConfig.difficulty); //userLib.addUsers(); next(null, config); } }; app = module.exports = express(); // app.use(passport.initialize()); app.use(passport.session()); // app.use(kraken(options)); app.on('start', function () { console.log('Application ready to serve requests.'); console.log('Environment: %s', app.kraken.get('env:env')); });
'use strict'; var express = require('express'); var kraken = require('kraken-js'); var db = require('./lib/db'); var crypto = require('./lib/crypto'); var passport = require('passport'); var localStrategy = require('./lib/registration');//?? var options, app; /* * Create and configure application. Also exports application instance for use by tests. * See https://github.com/krakenjs/kraken-js#options for additional configuration options. */ options = { onconfig: function (config, next) { /* * Add any additional config setup or overrides here. `config` is an initialized * `confit` (https://github.com/krakenjs/confit/) configuration object. */ db.config(config.get('databaseConfig')); localStrategy(passport); //??? var cryptConfig = config.get('bcrypt'); crypto.setCryptoLevel(cryptConfig.difficulty); //userLib.addUsers(); next(null, config); } }; app = module.exports = express(); // app.use(passport.initialize()); app.use(passport.session()); // app.use(kraken(options)); app.on('start', function () { console.log('Application ready to serve requests.'); console.log('Environment: %s', app.kraken.get('env:env')); });
Use Java naming conventions for constants
package sqlancer.common; import java.util.regex.Matcher; import java.util.regex.Pattern; public final class DBMSCommon { private static final Pattern SQLANCER_INDEX_PATTERN = Pattern.compile("^i\\d+"); private DBMSCommon() { } public static String createTableName(int nr) { return String.format("t%d", nr); } public static String createColumnName(int nr) { return String.format("c%d", nr); } public static String createIndexName(int nr) { return String.format("i%d", nr); } public static boolean matchesIndexName(String indexName) { Matcher matcher = SQLANCER_INDEX_PATTERN.matcher(indexName); return matcher.matches(); } }
package sqlancer.common; import java.util.regex.Matcher; import java.util.regex.Pattern; public final class DBMSCommon { private static final Pattern sqlancerIndexPattern = Pattern.compile("^i\\d+"); private DBMSCommon() { } public static String createTableName(int nr) { return String.format("t%d", nr); } public static String createColumnName(int nr) { return String.format("c%d", nr); } public static String createIndexName(int nr) { return String.format("i%d", nr); } public static boolean matchesIndexName(String indexName) { Matcher matcher = sqlancerIndexPattern.matcher(indexName); return matcher.matches(); } }
Remove no longer used code
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from parler.forms import TranslatableModelForm from sortedm2m.forms import SortedMultipleChoiceField from .models import Category, QuestionListPlugin, Question class CategoryAdminForm(TranslatableModelForm): class Meta: model = Category # def clean_slug(self): # slug = self.cleaned_data['slug'] # translations_model = Category._meta.translations_model # categories_with_slug = translations_model.objects.filter(slug=slug) # if self.instance.pk: # # Make sure to exclude references from this master :) # categories_with_slug = categories_with_slug.exclude( # master_id=self.instance.pk) # if categories_with_slug.exists(): # raise forms.ValidationError( # 'A category with this slug already exists.') # return slug class QuestionListPluginForm(forms.ModelForm): questions = SortedMultipleChoiceField(queryset=Question.objects.none()) class Meta: model = QuestionListPlugin def __init__(self, *args, **kwargs): super(QuestionListPluginForm, self).__init__(*args, **kwargs) questions_field = self.fields['questions'] questions_field.queryset = Question.objects.language()
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from parler.forms import TranslatableModelForm from sortedm2m.forms import SortedMultipleChoiceField from .models import Category, QuestionListPlugin, Question class CategoryAdminForm(TranslatableModelForm): class Meta: model = Category def clean_slug(self): slug = self.cleaned_data['slug'] translations_model = Category._meta.translations_model categories_with_slug = translations_model.objects.filter(slug=slug) if self.instance.pk: # Make sure to exclude references from this master :) categories_with_slug = categories_with_slug.exclude( master_id=self.instance.pk) if categories_with_slug.exists(): raise forms.ValidationError( 'A category with this slug already exists.') return slug class QuestionListPluginForm(forms.ModelForm): questions = SortedMultipleChoiceField(queryset=Question.objects.none()) class Meta: model = QuestionListPlugin def __init__(self, *args, **kwargs): super(QuestionListPluginForm, self).__init__(*args, **kwargs) questions_field = self.fields['questions'] questions_field.queryset = Question.objects.language()
Revert repr change, it looks worse for small example arrays
from __future__ import absolute_import, division, print_function from . import _arrayprint from ...datadescriptor import RemoteDataDescriptor def array_repr(a): pre = 'array(' post = ',\n' + ' '*len(pre) + "dshape='" + str(a.dshape) + "'" + ')' # TODO: create a mechanism for data descriptor to override # printing. if isinstance(a._data, RemoteDataDescriptor): body = 'RemoteDataDescriptor(%r)' % a._data.url else: body = _arrayprint.array2string(a._data, separator=', ', prefix=' '*len(pre)) return pre + body + post
from __future__ import absolute_import, division, print_function from . import _arrayprint from ...datadescriptor import RemoteDataDescriptor def array_repr(a): # TODO: create a mechanism for data descriptor to override # printing. if isinstance(a._data, RemoteDataDescriptor): body = 'RemoteDataDescriptor(%r)' % a._data.url else: body = _arrayprint.array2string(a._data, separator=', ') pre = 'array(' post = ',\n' + ' '*len(pre) + "dshape='" + str(a.dshape) + "'" + ')' # For a multi-line, start it on the next line so things align properly if '\n' in body: pre += '\n' return pre + body + post
Rewrite toString() to avoid confusion with edges in "dot" foramt
package com.github.ferstl.depgraph; import java.util.Objects; import org.apache.maven.shared.dependency.graph.DependencyNode; class Edge { final DependencyNode from; final DependencyNode to; public Edge(DependencyNode from, DependencyNode to) { this.from = from; this.to = to; } @Override public int hashCode() { return Objects.hash(this.from.getArtifact(), this.to.getArtifact()); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof Edge)) {return false; } Edge other = (Edge) obj; return Objects.equals(this.from.getArtifact(), other.from.getArtifact()) && Objects.equals(this.to.getArtifact(), other.to.getArtifact()); } @Override public String toString() { return "Edge[" + this.from + ", " + this.to + "]"; } }
package com.github.ferstl.depgraph; import java.util.Objects; import org.apache.maven.shared.dependency.graph.DependencyNode; class Edge { final DependencyNode from; final DependencyNode to; public Edge(DependencyNode from, DependencyNode to) { this.from = from; this.to = to; } @Override public int hashCode() { return Objects.hash(this.from.getArtifact(), this.to.getArtifact()); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof Edge)) {return false; } Edge other = (Edge) obj; return Objects.equals(this.from.getArtifact(), other.from.getArtifact()) && Objects.equals(this.to.getArtifact(), other.to.getArtifact()); } @Override public String toString() { return "\"" + this.from + "\" -> \"" + this.to + "\";"; } }
Update simple demo to use center, not pos
;(function(exports) { var SimpleGame = function(autoFocus) { var coq = new Coquette(this, "simple-canvas", 500, 150, "#000", autoFocus); coq.entities.create(Person, { center: { x:250, y:40 }, color:"#099" }); // paramour coq.entities.create(Person, { center: { x:256, y:110 }, color:"#f07", // player update: function() { if (coq.inputter.isDown(coq.inputter.UP_ARROW)) { this.center.y -= 0.4; } }, collision: function(other) { other.center.y = this.center.y; // follow the player } }); }; var Person = function(_, settings) { for (var i in settings) { this[i] = settings[i]; } this.size = { x:9, y:9 }; this.draw = function(ctx) { ctx.fillStyle = settings.color; ctx.fillRect(this.center.x, this.center.y, this.size.x, this.size.y); }; }; exports.SimpleGame = SimpleGame; })(this);
;(function(exports) { var Game = function(autoFocus) { var coq = new Coquette(this, "canvas", 500, 150, "#000", autoFocus); coq.entities.create(Person, { pos:{ x:250, y:40 }, color:"#099" }); // paramour coq.entities.create(Person, { pos:{ x:256, y:110 }, color:"#f07", // player update: function() { if (coq.inputter.isDown(coq.inputter.UP_ARROW)) { this.pos.y -= 0.4; } }, collision: function(other) { other.pos.y = this.pos.y; // follow the player } }); }; var Person = function(_, settings) { for (var i in settings) { this[i] = settings[i]; } this.size = { x:9, y:9 }; this.draw = function(ctx) { ctx.fillStyle = settings.color; ctx.fillRect(this.pos.x, this.pos.y, this.size.x, this.size.y); }; }; exports.Game = Game; })(this);
Make date imports more flexible Now ut works with `YYYY-MM-DD HH:MM:SS` and with `YYYY-MM-DDTHH:MM:SS`.
from rows import fields class IntegerField(fields.IntegerField): @classmethod def deserialize(cls, value, *args, **kwargs): try: # Rows cannot convert values such as '2011.0' to integer value = int(float(value)) except: pass return super(IntegerField, cls).deserialize(value) class DateAsStringField(fields.DateField): INPUT_FORMAT = '%Y-%m-%d %H:%M:%S' OUTPUT_FORMAT = '%Y-%m-%d' @classmethod def deserialize(cls, value, *args, **kwargs): value = value.replace('T', ' ') # normalize date/time separator return super(DateAsStringField, cls).deserialize(value)
from datetime import date from rows import fields class IntegerField(fields.IntegerField): @classmethod def deserialize(cls, value, *args, **kwargs): try: # Rows cannot convert values such as '2011.0' to integer value = int(float(value)) except: pass return super(IntegerField, cls).deserialize(value) class DateAsStringField(fields.DateField): INPUT_FORMAT = '%Y-%m-%dT%H:%M:%S' OUTPUT_FORMAT = '%Y-%m-%d' @classmethod def deserialize(cls, value, *args, **kwargs): value = super(DateAsStringField, cls).deserialize(value) if value: # useful when serializing it to Celery return value.strftime(cls.OUTPUT_FORMAT)
Change placeholder text in sign in form
<form name="loginform" action="<?php echo wp_login_url($_SERVER['REQUEST_URI']);?>" method="post"> <input type="hidden" name="redirect_to" value="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" /> <input type="hidden" name="user-cookie" value="1" /> <p> <input type="text" name="log" placeholder="CID eller e-postadress" <?php if(isset($_POST['user_email'])) echo 'value="'. $_POST['user_email'] .'" autofocus' ?> /> <input type="password" name="pwd" placeholder="Lösenord" /> </p> <p> <label><input type="checkbox" id="rememberme" name="rememberme" value="forever" checked="checked" /> Håll mig inloggad</label> <input type="submit" name="submit" class="small" value="Logga in" /> </p> </form>
<form name="loginform" action="<?php echo wp_login_url($_SERVER['REQUEST_URI']);?>" method="post"> <input type="hidden" name="redirect_to" value="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" /> <input type="hidden" name="user-cookie" value="1" /> <p> <input type="text" name="log" placeholder="E-postadress eller nick" <?php if(isset($_POST['user_email'])) echo 'value="'. $_POST['user_email'] .'" autofocus' ?> /> <input type="password" name="pwd" placeholder="Lösenord" /> </p> <p> <label><input type="checkbox" id="rememberme" name="rememberme" value="forever" checked="checked" /> Håll mig inloggad</label> <input type="submit" name="submit" class="small" value="Logga in" /> </p> </form>
Document is a ParentNode (not documented in MDN)
<?php namespace phpgt\dom; /** * @property-read Element $body * @property-read Element $head */ class HTMLDocument extends Document { use LivePropertyGetter, ParentNode; public function __construct($html) { parent::__construct(); $this->loadHTML($html); } public function querySelector(string $selectors) { return $this->documentElement->querySelector($selectors); } public function querySelectorAll(string $selectors):HTMLCollection { return $this->documentElement->querySelectorAll($selectors); } private function prop_head():Element { return $this->getOrCreateElement("head"); } private function prop_body():Element { return $this->getOrCreateElement("body"); } private function getOrCreateElement(string $tagName):Element { $element = $this->documentElement->querySelector($tagName); if(is_null($element)) { $element = $this->createElement($tagName); $this->documentElement->appendChild($element); } return $element; } }#
<?php namespace phpgt\dom; /** * @property-read Element $body * @property-read HTMLCollection $children * @property-read Element $head */ class HTMLDocument extends Document { use LivePropertyGetter; public function __construct($html) { parent::__construct(); $this->loadHTML($html); } public function querySelector(string $selectors) { return $this->documentElement->querySelector($selectors); } public function querySelectorAll(string $selectors):HTMLCollection { return $this->documentElement->querySelectorAll($selectors); } private function prop_head():Element { return $this->getOrCreateElement("head"); } private function prop_body():Element { return $this->getOrCreateElement("body"); } private function prop_children():HTMLCollection { return $this->documentElement->children; } private function getOrCreateElement(string $tagName):Element { $element = $this->documentElement->querySelector($tagName); if(is_null($element)) { $element = $this->createElement($tagName); $this->documentElement->appendChild($element); } return $element; } }#
Remove complex pluralisation as WP API does not do this (it only adds an 's');
import humps from 'humps'; import ContentTypes from './constants/ContentTypes'; const contentTypeNames = Object.keys(ContentTypes) .map((name) => humps.camelize(name)); export const customContentTypes = {}; export function registerCustomContentType (name, { namePlural = null, requestSlug = null } = {}) { if (typeof name !== 'string') { throw new Error('Expecting name of Custom Content Type to be a string.'); } const contentTypeNameTaken = Object.keys(customContentTypes).includes(name) || contentTypeNames.includes(name); if (contentTypeNameTaken) { throw new Error( `The Content Type name "${name}" is already taken. ` + `Choose another non-conflicting name.` ); } namePlural = namePlural || name + 's'; requestSlug = requestSlug || humps.decamelize(namePlural, { separator: '-' }); return customContentTypes[name] = { name, namePlural, requestSlug }; }
import humps from 'humps'; import ContentTypes from './constants/ContentTypes'; const contentTypeNames = Object.keys(ContentTypes) .map((name) => humps.camelize(name)); function makePluralContentTypeName (name) { return name[name.length - 1] === 'y' ? name.substr(0, name.length - 1) + 'ies' : name + 's' } export const customContentTypes = {}; export function registerCustomContentType (name, { namePlural = null, requestSlug = null } = {}) { if (typeof name !== 'string') { throw new Error('Expecting name of Custom Content Type to be a string.'); } if (contentTypeNames.includes(name.toLowerCase())) { throw new Error( `The Content Type name "${name}" is already taken by a built-in. ` + `Choose another non-conflicting name.` ); } namePlural = namePlural || makePluralContentTypeName(name); requestSlug = requestSlug || humps.decamelize(name.toLowerCase(), { split: /_/, separator: '-' }); return customContentTypes[name] = { name, namePlural, requestSlug }; }
Fix annoying bug in connect middleware
// Local web server running on port 9001 with livereload functionality module.exports = function(grunt) { grunt.config('connect', { livereload: { options: { port: 9001, middleware: function(connect, options) { return[ require('connect-livereload')(), connect.static(options.base[0]), connect.directory(options.base) ]; } }, }, }); grunt.loadNpmTasks('grunt-contrib-connect'); };
// Local web server running on port 9001 with livereload functionality module.exports = function(grunt) { grunt.config('connect', { livereload: { options: { port: 9001, middleware: function(connect, options) { return[ require('connect-livereload')(), connect.static(options.base), connect.directory(options.base) ]; } }, }, }); grunt.loadNpmTasks('grunt-contrib-connect'); };
Set event content to QR code
/* * GET home page. */ var mongo = require('mongodb'); var appconf = require('konphyg')(__dirname + '/../config')('conf'); exports.byid = function(req, res){ var event_id = req.params.id; var mongo_client = require('mongodb').MongoClient; var mongoUri = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || appconf.mongodb_url; mongo_client.connect(mongoUri, function (err, db) { var collection = db.collection('events'); collection.findOne({event_id: event_id}, function(err, item) { if(err) { console.log(err); res.render('index', { title: "iCalGen.js" }); } else { //res.setHeader('Content-Type', 'text/calendar'); //res.setHeader('Content-Disposition', 'attachment; filename="event.ics"'); res.send(item.ics_string); } }); }); };
/* * GET home page. */ var mongo = require('mongodb'); var appconf = require('konphyg')(__dirname + '/../config')('conf'); exports.byid = function(req, res){ var event_id = req.params.id; var mongo_client = require('mongodb').MongoClient; var mongoUri = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || appconf.mongodb_url; mongo_client.connect(mongoUri, function (err, db) { var collection = db.collection('events'); collection.findOne({event_id: event_id}, function(err, item) { if(err) { console.log(err); res.render('index', { title: "iCalGen.js" }); } else { res.setHeader('Content-Type', 'text/calendar'); res.setHeader('Content-Disposition', 'attachment; filename="event.ics"'); res.send(item.ics_string); } }); }); };
Return dispatch in the try block.
import {createAction} from 'redux-actions'; import axios from 'axios'; export const FETCH_APP_REQUEST = 'FETCH_APP_REQUEST'; export const FETCH_APP_SUCCESS = 'FETCH_APP_SUCCESS'; export const FETCH_APP_FAILURE = 'FETCH_APP_FAILURE'; export const RESET_STORE_AT_KEY = 'RESET_STORE_AT_KEY'; const fetchIndexRequest = createAction(FETCH_APP_REQUEST); const fetchIndexSuccess = createAction(FETCH_APP_SUCCESS); const fetchIndexFailure = createAction(FETCH_APP_FAILURE); export const fetchApp = () => async (dispatch) => { dispatch(fetchIndexRequest()); try { const {data} = await axios.get('v1/index'); return dispatch(fetchIndexSuccess(data)); } catch (err) { const reducedAction = (err instanceof Error) ? fetchIndexFailure(err) : fetchIndexFailure(err.response); return dispatch(reducedAction); } }; export const resetStoreAtKey = (key, initialState) => (dispatch) => { const resetStoreAtKeyAction = createAction(RESET_STORE_AT_KEY); return dispatch(resetStoreAtKeyAction({key, initialState})); };
import {createAction} from 'redux-actions'; import axios from 'axios'; export const FETCH_APP_REQUEST = 'FETCH_APP_REQUEST'; export const FETCH_APP_SUCCESS = 'FETCH_APP_SUCCESS'; export const FETCH_APP_FAILURE = 'FETCH_APP_FAILURE'; export const RESET_STORE_AT_KEY = 'RESET_STORE_AT_KEY'; const fetchIndexRequest = createAction(FETCH_APP_REQUEST); const fetchIndexSuccess = createAction(FETCH_APP_SUCCESS); const fetchIndexFailure = createAction(FETCH_APP_FAILURE); export const fetchApp = () => async (dispatch) => { dispatch(fetchIndexRequest()); let response; try { response = await axios.get('v1/index'); } catch (err) { const reducedAction = (err instanceof Error) ? fetchIndexFailure(err) : fetchIndexFailure(err.response); return dispatch(reducedAction); } return dispatch(fetchIndexSuccess(response.data)); }; export const resetStoreAtKey = (key, initialState) => (dispatch) => { const resetStoreAtKeyAction = createAction(RESET_STORE_AT_KEY); return dispatch(resetStoreAtKeyAction({key, initialState})); };
Handle empty path to configuration default to PORT = 4444 if `config.db.PORT` is not a valid path
const command = { command: "serve", description: "Start Truffle's GraphQL UI playground", builder: {}, help: { usage: "truffle db serve", options: [] }, /* This command does starts an express derived server that invokes * `process.exit()` on SIGINT. As a result there is no need to invoke * truffle's own `process.exit()` which is triggered by invoking the `done` * callback. * * Todo: blacklist this command for REPLs */ run: async function(argv) { const Config = require("@truffle/config"); const { playgroundServer } = require("truffle-db"); const config = Config.detect(argv); const port = (config.db && config.db.PORT) || 4444; const { url } = await playgroundServer(config).listen({ port }); console.log(`🚀 Playground listening at ${url}`); console.log(`ℹ Press Ctrl-C to exit`); } }; module.exports = command;
const command = { command: "serve", description: "Start Truffle's GraphQL UI playground", builder: {}, help: { usage: "truffle db serve", options: [] }, /* This command does starts an express derived server that invokes * `process.exit()` on SIGINT. As a result there is no need to invoke * truffle's own `process.exit()` which is triggered by invoking the `done` * callback. * * Todo: blacklist this command for REPLs */ run: async function(argv) { const Config = require("@truffle/config"); const { playgroundServer } = require("truffle-db"); const config = Config.detect(argv); const port = config.db.PORT || 4444; const { url } = await playgroundServer(config).listen({ port }); console.log(`🚀 Playground listening at ${url}`); console.log(`ℹ Press Ctrl-C to exit`); } }; module.exports = command;
QS-907: Fix error in conflicted merge
import { fetchUser, fetchThreads, fetchRecommendation, fetchUserArray, fetchProfile, fetchStats, postLikeUser, deleteLikeUser, fetchMatching, fetchSimilarity } from '../utils/APIUtils'; export function getUser(login, url = `users/${login}`) { return fetchUser(url); } export function getProfile(login, url = `users/${login}/profile`) { return fetchProfile(url); } export function getStats(login, url = `users/${login}/stats`) { return fetchStats(url); } export function getThreads(login, url = `users/${login}/threads`){ return fetchThreads(url); } export function getRecommendation(threadId, url = `threads/${threadId}/recommendation`){ return fetchRecommendation(url); } export function setLikeUser(from, to, url = `users/${from}/likes/${to}`){ return postLikeUser(url); } export function unsetLikeUser(from, to, url = `users/${from}/likes/${to}`) { return deleteLikeUser(url); } export function getMatching(userId1, userId2, url = `users/${userId1}/matching/${userId2}`){ return fetchMatching(url); } export function getSimilarity(userId1, userId2, url = `users/${userId1}/similarity/${userId2}`){ return fetchSimilarity(url); }
import { fetchUser, fetchThreads, fetchRecommendation, fetchUserArray, fetchProfile, fetchStats, postLikeUser, deleteLikeUser, fetchMatching, fetchSimilarity } from '../utils/APIUtils'; export function getUser(login, url = `users/${login}`) { return fetchUser(url); } export function getProfile(login, url = `users/${login}/profile`) { return fetchProfile(url); } export function getStats(login, url = `users/${login}/stats`) { return fetchStats(url); } export function getThreads(login, url = `users/${login}/threads`){ return fetchThreads(url); } export function getRecommendation(threadId, url = `threads/${threadId}/recommendation`){ return fetchRecommendation(url); } export function setLikeUser(from, to, url = `users/${from}/likes/${to}`){ return postLikeUser(url); } export function unsetLikeUser(from, to, url = `users/${from}/likes/${to}`){ return deleteLikeUser(url); export function getMatching(userId1, userId2, url = `users/${userId1}/matching/${userId2}`){ return fetchMatching(url); } export function getSimilarity(userId1, userId2, url = `users/${userId1}/similarity/${userId2}`){ return fetchSimilarity(url); }
Revert "Use port for protocol when none is provided" This reverts commit b8c2f03b8e26cee0eb36153def9be41ee5adb79b.
var websocket = require('websocket-stream'); var URL = require('url'); function buildBuilder(client, opts) { var host = opts.hostname || 'localhost' , port = opts.port || 80 , url = opts.protocol + '://' + host + ':' + port , ws = websocket(url, { protocol: 'mqttv3.1' }); return ws; } function buildBuilderBrowser(mqttClient, opts) { var parsed = URL.parse(document.URL); if (!opts.protocol) { if (parsed.protocol === 'https:') { opts.protocol = 'wss'; } else { opts.protocol = 'ws'; } } if (!opts.host) { opts.host = parsed.hostname; } if (!opts.port) { opts.port = parsed.port; } var host = opts.hostname || opts.host , port = opts.port , url = opts.protocol + '://' + host + ':' + opts.port return websocket(url); } if (process.title !== 'browser') { module.exports = buildBuilder; } else { module.exports = buildBuilderBrowser; }
var websocket = require('websocket-stream'); var URL = require('url'); function buildBuilder(client, opts) { var host = opts.hostname || 'localhost' , port = opts.port || 80 , url = opts.protocol + '://' + host + ':' + port , ws = websocket(url, { protocol: 'mqttv3.1' }); return ws; } function buildBuilderBrowser(mqttClient, opts) { var parsed = URL.parse(document.URL); if (!opts.protocol) { if (parsed.protocol === 'https:') { opts.protocol = 'wss'; } else { opts.protocol = 'ws'; } } if (!opts.host) { opts.host = parsed.hostname; } if (!opts.port) { if(opts.protocol === 'wss'){ opts.port = 443; } else if(opts.protocol === 'ws') { opts.port = 80; } else { opts.port = parsed.port; } } var host = opts.hostname || opts.host , port = opts.port , url = opts.protocol + '://' + host + ':' + opts.port return websocket(url); } if (process.title !== 'browser') { module.exports = buildBuilder; } else { module.exports = buildBuilderBrowser; }
Refactor Gulpfile for Gulp Watch
// gulpfile.js // Packages var gulp = require('gulp'); var rename = require('gulp-rename'); var uglify = require('gulp-uglify'); var browserify = require('browserify'); var babelify = require('babelify'); var source = require('vinyl-source-stream'); var buffer = require('vinyl-buffer'); // Tasks var bundleGames = function() { return gulp .src('resources/assets/js/games/index.js') //.pipe(rename('index.min.js')) .pipe(rename({suffix: '.min'})) .pipe(uglify()) .pipe(gulp.dest('public/js/games')); } var bundleUsers = function() { return browserify('resources/assets/js/users/index.js') .transform('babelify', {presets: ['es2015']}) .bundle() .pipe(source('user-bundle.min.js')) .pipe(buffer()) .pipe(uglify()) .pipe(gulp.dest('public/js/users')); } // Uglify gulp.task('games-js', function(){ return bundleUsers(); }); // Browserify & Babel gulp.task('users-js', function(){ return bundleUsers(); });
// gulpfile.js // Packages var gulp = require('gulp'); var rename = require('gulp-rename'); var uglify = require('gulp-uglify'); var browserify = require('browserify'); var babelify = require('babelify'); var source = require('vinyl-source-stream'); var buffer = require('vinyl-buffer'); // Tasks // Uglify gulp.task('games-js', function(){ return gulp .src('resources/assets/js/games/index.js') //.pipe(rename('index.min.js')) .pipe(rename({suffix: '.min'})) .pipe(uglify()) .pipe(gulp.dest('public/js/games')); }); // Browserify & Babel gulp.task('users-js', function(){ return browserify('resources/assets/js/users/index.js') .transform('babelify', {presets: ['es2015']}) .bundle() .pipe(source('user-bundle.min.js')) .pipe(buffer()) .pipe(uglify()) .pipe(gulp.dest('public/js/users')); });
Allow console log warn error
module.exports = { "env": { "browser": true, "node": true }, "globals": { "app": true, "angular": true, "_": true }, "extends": "eslint:recommended", "rules": { "no-console": [ "error", { allow: ["log", "warn", "error"] } ], "indent": [ "error", 2 ], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "single" ], "semi": [ "error", "always" ] } };
module.exports = { "env": { "browser": true, "node": true }, "globals": { "app": true, "angular": true, "_": true }, "extends": "eslint:recommended", "rules": { "indent": [ "error", 2 ], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "single" ], "semi": [ "error", "always" ] } };
Make request header optional in authentication middleware.
export default (config) => { if ( ! config.enabled) return (req, res, next) => { next() } var verifyHeader = ( !! config.header) var header = (config.header || '').toLowerCase() var tokenLength = 32 var tokenRegExp = new RegExp(`^Token ([a-zA-Z0-9]{${tokenLength}})$`) return (req, res, next) => { var err req.auth = {} if (verifyHeader) { var value = req.auth.header = req.headers[header] if ( ! value) { err = new Error(`Missing ${config.header} header.`) err.statusCode = 401 return next(err) } if (config.byToken) { var token = value.replace(tokenRegExp, '$1') if (token.length !== tokenLength) { err = new Error('Invalid token.') err.statusCode = 401 return next(err) } req.auth.token = token } } if ( ! config.method) return next() config.method(req, config, req.data, (err, user) => { if (err) { err = new Error(err) err.statusCode = 401 return next(err) } req.user = user next() }) } }
export default (config) => { if ( ! config.enabled) return (req, res, next) => { next() } var header = (config.header || 'Authorization').toLowerCase() var tokenLength = 32 var tokenRegExp = new RegExp(`^Token ([a-zA-Z0-9]{${tokenLength}})$`) return (req, res, next) => { var value = req.headers[header] var err req.auth = { header: value } if ( ! req.auth.header) { err = new Error(`Missing ${config.header} header.`) err.statusCode = 401 return next(err) } if (config.byToken) { var token = value.replace(tokenRegExp, '$1') if (token.length !== tokenLength) { err = new Error('Invalid token.') err.statusCode = 401 return next(err) } req.auth.token = token } if ( ! config.method) return next() config.method(req, config, req.data, (err, user) => { if (err) { err = new Error(err) err.statusCode = 401 return next(err) } req.user = user next() }) } }
Add xls & ppt support
// Avoid recursive frame insertion... var extensionOrigin = 'chrome-extension://' + chrome.runtime.id; if (!location.ancestorOrigins.contains(extensionOrigin)) { // Supported File Types var fileTypes = ['.pdf', '.doc', '.xls', '.ppt']; var links = document.getElementsByTagName('a'); var pdfLinks = []; Object.keys(links).forEach(function (id) { var link = links[id]; fileTypes.some(function (ext) { if (link.href.indexOf(ext) > -1) { pdfLinks.push(link); return true; } }); }); pdfLinks.forEach(function (link) { var iframe = document.createElement('iframe'); // Must be declared at web_accessible_resources in manifest.json iframe.src = chrome.runtime.getURL('frame.html') + '?url=' + link.href; // Basic Style iframe.style.cssText = 'display:block;height:600px;width:664px;z-index:99999;border:none;margin-top:10px;margin-bottom:10px;'; // Insert after Link to include in Google doc viewer link.parentNode.insertBefore(iframe, link.nextSibling) }); }
// Avoid recursive frame insertion... var extensionOrigin = 'chrome-extension://' + chrome.runtime.id; if (!location.ancestorOrigins.contains(extensionOrigin)) { var links = document.getElementsByTagName('a'); var pdfLinks = []; Object.keys(links).forEach(function (id) { var link = links[id]; if (link.href.indexOf('.pdf') > -1 || link.href.indexOf('.doc') > -1) { pdfLinks.push(link); } }); pdfLinks.forEach(function (link) { var iframe = document.createElement('iframe'); // Must be declared at web_accessible_resources in manifest.json iframe.src = chrome.runtime.getURL('frame.html') + '?url=' + link.href; // Basic Style iframe.style.cssText = 'display:block;height:600px;width:664px;z-index:99999;border:none;margin-top:10px;margin-bottom:10px;'; // Insert after Link to include in Google doc viewer link.parentNode.insertBefore(iframe, link.nextSibling) }); }
Send bbox for Point features
var mongoose = require('mongoose'), _ = require('cloneextend'), adHocModels = {}; var adHocModel = function(collectionName, Schema, options) { if (!adHocModels[collectionName]) { var options = options || {}; if (options.strict == undefined) { options.strict = false; } var Schema = Schema || new mongoose.Schema({}, options); adHocModels[collectionName] = mongoose.model( 'adhoc_' + new mongoose.Types.ObjectId().toString(), Schema, collectionName); } return adHocModels[collectionName]; }; /* Modifies the JSON object to be sent to the client as GeoJSON */ var toGeoJSON = function(obj) { delete obj.bounds2d; if (obj.bbox && !obj.bbox.length && obj.geometry.type == 'Point') { obj.bbox = [ obj.geometry.coordinates[0], obj.geometry.coordinates[1], obj.geometry.coordinates[0], obj.geometry.coordinates[1] ]; } return obj; }; module.exports = { adHocModel: adHocModel, toGeoJSON: toGeoJSON };
var mongoose = require('mongoose'), _ = require('cloneextend'), adHocModels = {}; var adHocModel = function(collectionName, Schema, options) { if (!adHocModels[collectionName]) { var options = options || {}; if (options.strict == undefined) { options.strict = false; } var Schema = Schema || new mongoose.Schema({}, options); adHocModels[collectionName] = mongoose.model( 'adhoc_' + new mongoose.Types.ObjectId().toString(), Schema, collectionName); } return adHocModels[collectionName]; }; /* Modifies the JSON object to be sent to the client as GeoJSON */ var toGeoJSON = function(obj) { delete obj.bounds2d; return obj; }; module.exports = { adHocModel: adHocModel, toGeoJSON: toGeoJSON };
Fix broken 'more' link after the post has been created
import Article from 'scripts/models/article'; import FormBehavior from 'scripts/views/behaviors/form'; import Session from 'scripts/facades/session'; import template from 'templates/articles/form'; export default class ArticlesFormView extends Marionette.ItemView { constructor(...args) { this.model = new Article(Session.currentUser().pick('avatar', 'name')); this.template = template; this.events = { 'submit form': 'onFormSubmit' }; this.bindings = { '[name="text"]': { observe: 'text', updateView: false, setOptions: { validate: true } }, '[name="title"]': { observe: 'title', updateView: false, setOptions: { validate: true } } }; this.behaviors = { form: { behaviorClass: FormBehavior, tooltip: { placement: 'left', trigger: 'focus' } } }; super(...args); } onFormSubmit(event) { event.preventDefault(); if (this.model.isValid(true)) { this.collection.create(this.model, { wait: true }); } } }
import Article from 'scripts/models/article'; import FormBehavior from 'scripts/views/behaviors/form'; import Session from 'scripts/facades/session'; import template from 'templates/articles/form'; export default class ArticlesFormView extends Marionette.ItemView { constructor(...args) { this.model = new Article(Session.currentUser().pick('avatar', 'name')); this.template = template; this.events = { 'submit form': 'onFormSubmit' }; this.bindings = { '[name="text"]': { observe: 'text', updateView: false, setOptions: { validate: true } }, '[name="title"]': { observe: 'title', updateView: false, setOptions: { validate: true } } }; this.behaviors = { form: { behaviorClass: FormBehavior, tooltip: { placement: 'left', trigger: 'focus' } } }; super(...args); } onFormSubmit(event) { event.preventDefault(); if (this.model.isValid(true)) { this.collection.create(this.model); } } }
Increase number of visualization params
package com.xmunch.atomspace.aux; public enum VisualizationParams { SIZE { @Override public String get() { return "size"; } }, COLOR { @Override public String get() { return "color"; } }, FONT_COLOR { @Override public String get() { return "fontcolor"; } }, SHAPE { @Override public String get() { return "shape"; } }, LABEL { @Override public String get() { return "label"; } }, ARROW { @Override public String get() { return "arrow"; } }, ARROW_POSITION { @Override public String get() { return "arrow_position"; } }, STROKE { @Override public String get() { return "stroke"; } }, STRENGTH { @Override public String get() { return "strength"; } }, WIDTH { @Override public String get() { return "width"; } }, SPHERE { @Override public String get() { return "sphere"; } }, CONE { @Override public String get() { return "cone"; } }, DASHED { @Override public String get() { return "dashed"; } }; public abstract String get(); }
package com.xmunch.atomspace.aux; public enum VisualizationParams { SIZE { @Override public String get() { return "size"; } }, COLOR { @Override public String get() { return "color"; } }, FONT_COLOR { @Override public String get() { return "fontcolor"; } }, SHAPE { @Override public String get() { return "shape"; } }, LABEL { @Override public String get() { return "label"; } }, ARROW { @Override public String get() { return "arrow"; } }, STROKE { @Override public String get() { return "stroke"; } }, WIDTH { @Override public String get() { return "width"; } }, SPHERE { @Override public String get() { return "sphere"; } }, CONE { @Override public String get() { return "cone"; } }, DASHED { @Override public String get() { return "dashed"; } }; public abstract String get(); }
Reduce internal token expiration time
package me.deftware.client.framework.MC_OAuth; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class StaticOAuth { private static String token = ""; static { Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new Runnable() { @Override public void run() { token = ""; } }, 0, 2, TimeUnit.MINUTES); } /** * Will always return a token * * @param callback */ public static void getToken(OAuthCodeHandler callback) { if (token.equals("")) { OAuth.oAuth((success, code, time) -> { token = code; callback.callback(token); }); } else { callback.callback(token); } } @FunctionalInterface public static interface OAuthCodeHandler { public void callback(String code); } }
package me.deftware.client.framework.MC_OAuth; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class StaticOAuth { private static String token = ""; static { Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new Runnable() { @Override public void run() { token = ""; } }, 0, 5, TimeUnit.MINUTES); } /** * Will always return a token * * @param callback */ public static void getToken(OAuthCodeHandler callback) { if (token.equals("")) { OAuth.oAuth((success, code, time) -> { token = code; callback.callback(token); }); } else { callback.callback(token); } } @FunctionalInterface public static interface OAuthCodeHandler { public void callback(String code); } }
Refactor so that next() takes the return value of gen.next()
// Coroutine function that returns a promise that resolves when the coroutine // is finished. Accepts a generator function, and assumes that everything // yielded from the generator function is a promise. module.exports = function coroutine(generatorFunction) { let gen = generatorFunction() return new Promise(resolve => { // Handle every single result yielded by the generator function. function next(result) { if (result.done) { // Generator is done, so resolve to its return value. resolve(result.value) } else { // Generator is not done, so result.value is a promise. let promise = result.value // When the promise is done, run this function again. promise.then(newValue => { let newResult = gen.next(newValue) next(newResult) }) } } next(gen.next()) }) }
// Coroutine function that returns a promise that resolves when the coroutine // is finished. Accepts a generator function, and assumes that everything // yielded from the generator function is a promise. module.exports = function coroutine(generatorFunction) { let gen = generatorFunction() return new Promise(resolve => { // Handle every single value yielded by the generator function. function step(value) { let result = gen.next(value) if (result.done) { // Generator is done, so handle its return value. resolve(result.value) } else { // Generator is not done, so result.value is a promise. let promise = result.value // When the promise is done, run this function again. promise.then(newValue => step(newValue)) } } step(undefined) }) }
Fix redeclared var & change to let
var selftest = require('../tool-testing/selftest.js'); var Sandbox = selftest.Sandbox; var files = require('../fs/files.js'); selftest.define("add cordova platforms", ["cordova"], function () { var s = new Sandbox(); let run; // Starting a run s.createApp("myapp", "package-tests"); s.cd("myapp"); run = s.run("run", "android"); run.matchErr("Please add the Android platform to your project first"); run.match("meteor add-platform android"); run.expectExit(1); run = s.run("add-platform", "android"); // Cordova may need to download cordova-android if it's not already // cached (in ~/.cordova). run.waitSecs(30); run.match("added platform"); run.expectExit(0); run = s.run("remove-platform", "foo"); run.matchErr("foo: platform is not"); run.expectExit(1); run = s.run("remove-platform", "android"); run.match("removed"); run = s.run("run", "android"); run.matchErr("Please add the Android platform to your project first"); run.match("meteor add-platform android"); run.expectExit(1); });
var selftest = require('../tool-testing/selftest.js'); var Sandbox = selftest.Sandbox; var files = require('../fs/files.js'); selftest.define("add cordova platforms", ["cordova"], function () { var s = new Sandbox(); var run; // Starting a run s.createApp("myapp", "package-tests"); s.cd("myapp"); run = s.run("run", "android"); run.matchErr("Please add the Android platform to your project first"); run.match("meteor add-platform android"); run.expectExit(1); var run = s.run("add-platform", "android"); // Cordova may need to download cordova-android if it's not already // cached (in ~/.cordova). run.waitSecs(30); run.match("added platform"); run.expectExit(0); run = s.run("remove-platform", "foo"); run.matchErr("foo: platform is not"); run.expectExit(1); run = s.run("remove-platform", "android"); run.match("removed"); run = s.run("run", "android"); run.matchErr("Please add the Android platform to your project first"); run.match("meteor add-platform android"); run.expectExit(1); });
Tweak tests bases on observations
package dk.ekot.misc; import org.junit.Test; import static org.junit.Assert.*; /* * 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. * */ public class GrowableLongArrayTest { /* @Test public void testTrivial() { GrowableByteArray la = new GrowableByteArray(); //la.set(0, 87); //la.set(12, 88); assertEquals("At index 0, the value should be correct", 87, la.get(0)); assertEquals("At index 12, the value should be correct", 88, la.get(12)); } @Test public void testHighIndex() { GrowableByteArray la = new GrowableByteArray(); final long index = Integer.MAX_VALUE*12L; //la.set(index, 89); assertEquals("At index " + index + " (> Integer.MAX_VALUE), the value should be correct", 89, la.get(index)); } */ }
package dk.ekot.misc; import org.junit.Test; import static org.junit.Assert.*; /* * 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. * */ public class GrowableLongArrayTest { /* @Test public void testTrivial() { GrowableByteArray la = new GrowableByteArray(); la.set(0, 87); la.set(12, 88); assertEquals("At index 0, the value should be correct", 87, la.get(0)); assertEquals("At index 12, the value should be correct", 88, la.get(12)); } @Test public void testHighIndex() { GrowableByteArray la = new GrowableByteArray(); final long index = Integer.MAX_VALUE*12L; la.set(index, 89); assertEquals("At index " + index + " (> Integer.MAX_VALUE), the value should be correct", 89, la.get(index)); } */ }
[Add] Add Topic landing page route
import React from 'react' import { Router, Route, IndexRoute, browserHistory } from 'react-router' import App from '../containers/App' import Article from '../containers/Article' import Blank from '../containers/Blank' import Category from '../containers/Category' import Home from '../containers/Home' import Photography from '../containers/Photography' import Search from '../containers/Search' import Tag from '../containers/Tag' import Topic from '../containers/Topic' import TopicLandingPage from '../containers/TopicLandingPage' export default function (history = browserHistory) { return ( <Router history={history} onUpdate={() => window.scrollTo(0, 0)}> <Route path="/topics/:slug" component={TopicLandingPage} /> <Route path="/" component={App}> <IndexRoute component={Home} /> <Route path="category/:category" component={Category}/> <Route path="topic/:topicId" component={Topic} /> <Route path="tag/:tagId" component={Tag} /> <Route path="photography" component={Photography}/> <Route path="search" component={Search}/> <Route path="check" component={Blank}/> <Route path="a/:slug" component={Article}/> </Route> </Router> ) }
import React from 'react' import { Router, Route, IndexRoute, browserHistory } from 'react-router' import App from '../containers/App' import Article from '../containers/Article' import Blank from '../containers/Blank' import Category from '../containers/Category' import Home from '../containers/Home' import Photography from '../containers/Photography' import Search from '../containers/Search' import Tag from '../containers/Tag' import Topic from '../containers/Topic' export default function (history = browserHistory) { return ( <Router history={history} onUpdate={() => window.scrollTo(0, 0)}> <Route path="/" component={App}> <IndexRoute component={Home} /> <Route path="category/:category" component={Category}/> <Route path="topic/:topicId" component={Topic} /> <Route path="tag/:tagId" component={Tag} /> <Route path="photography" component={Photography}/> <Route path="search" component={Search}/> <Route path="check" component={Blank}/> <Route path="a/:slug" component={Article}/> </Route> </Router> ) }
Fix Groovy console interpreter not being set properly
package de.prob2.ui.consoles.groovy; import java.io.IOException; import com.google.inject.Inject; import com.google.inject.Singleton; import de.prob2.ui.prob2fx.CurrentStage; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.stage.Stage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton public final class GroovyConsoleStage extends Stage { private static final Logger logger = LoggerFactory.getLogger(GroovyConsoleStage.class); @FXML private GroovyConsole groovyConsole; private final GroovyInterpreter interpreter; @Inject private GroovyConsoleStage(FXMLLoader loader, CurrentStage currentStage, GroovyInterpreter interpreter) { this.interpreter = interpreter; try { loader.setLocation(getClass().getResource("groovy_console_stage.fxml")); loader.setRoot(this); loader.setController(this); loader.load(); } catch (IOException e) { logger.error("loading fxml failed", e); } currentStage.register(this); } @FXML public void initialize() { groovyConsole.setInterpreter(interpreter); this.setOnCloseRequest(e -> groovyConsole.closeObjectStage()); } }
package de.prob2.ui.consoles.groovy; import java.io.IOException; import com.google.inject.Inject; import com.google.inject.Singleton; import de.prob2.ui.prob2fx.CurrentStage; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.stage.Stage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton public final class GroovyConsoleStage extends Stage { private static final Logger logger = LoggerFactory.getLogger(GroovyConsoleStage.class); @FXML private GroovyConsole groovyConsole; private final GroovyInterpreter interpreter; @Inject private GroovyConsoleStage(FXMLLoader loader, CurrentStage currentStage, GroovyInterpreter interpreter) { try { loader.setLocation(getClass().getResource("groovy_console_stage.fxml")); loader.setRoot(this); loader.setController(this); loader.load(); } catch (IOException e) { logger.error("loading fxml failed", e); } this.interpreter = interpreter; currentStage.register(this); } @FXML public void initialize() { groovyConsole.setInterpreter(interpreter); this.setOnCloseRequest(e -> groovyConsole.closeObjectStage()); } }
Update PubSub master when on Heroku.
<?php error_reporting(E_ALL); require dirname(__DIR__).'/vendor/autoload.php'; \SciActive\R::_('NymphConfig', [], function(){ return include __DIR__.'/config.php'; }); \SciActive\R::_('NymphPubSubConfig', [], function(){ $config = include dirname(__DIR__).'/vendor/sciactive/nymph-pubsub/conf/defaults.php'; // If we're on Heroku, the master is the pubsub demo. if (getenv('DATABASE_URL')) { $config->port['master'] = 'ws://nymph-pubsub-demo.herokuapp.com:80/'; } return $config; }); $NymphREST = new \Nymph\REST(); require 'employee/Employee.php'; require 'todo/Todo.php'; require 'sudoku/Game.php'; try { if (in_array($_SERVER['REQUEST_METHOD'], ['PUT', 'DELETE'])) { parse_str(file_get_contents("php://input"), $args); $NymphREST->run($_SERVER['REQUEST_METHOD'], $args['action'], $args['data']); } else { $NymphREST->run($_SERVER['REQUEST_METHOD'], $_REQUEST['action'], $_REQUEST['data']); } } catch (\Nymph\Exceptions\QueryFailedException $e) { echo $e->getMessage()."\n\n".$e->getQuery(); }
<?php error_reporting(E_ALL); require dirname(__DIR__).'/vendor/autoload.php'; \SciActive\R::_('NymphConfig', [], function(){ return include __DIR__.'/config.php'; }); \SciActive\R::_('NymphPubSubConfig', [], function(){ return include dirname(__DIR__).'/vendor/sciactive/nymph-pubsub/conf/defaults.php'; }); $NymphREST = new \Nymph\REST(); require 'employee/Employee.php'; require 'todo/Todo.php'; require 'sudoku/Game.php'; try { if (in_array($_SERVER['REQUEST_METHOD'], ['PUT', 'DELETE'])) { parse_str(file_get_contents("php://input"), $args); $NymphREST->run($_SERVER['REQUEST_METHOD'], $args['action'], $args['data']); } else { $NymphREST->run($_SERVER['REQUEST_METHOD'], $_REQUEST['action'], $_REQUEST['data']); } } catch (\Nymph\Exceptions\QueryFailedException $e) { echo $e->getMessage()."\n\n".$e->getQuery(); }
Fix base files identified as wrong variation
const parseVariations = require('../variations'); const createValidator = require('./validator'); const validate = createValidator({ variations: {type: 'array', minLen: 1}, // There can be a user of Mendel who does not want variation but faster build. allVariationDirs: {type: 'array', minLen: 0}, allDirs: {type: 'array', minLen: 1}, }); function VariationConfig(config) { const variations = parseVariations(config); const allVariationDirs = getAllDirs(variations); const baseVariation = { id: config.baseConfig.id, chain: [config.baseConfig.dir], }; // base variation must come first in order to variationMatches to work variations.unshift(baseVariation); const allDirs = getAllDirs(variations); const variationConfig = { variations, baseVariation, allDirs, allVariationDirs, }; validate(variationConfig); return variationConfig; } function getAllDirs(variationArray) { return variationArray.reduce((allDirs, variation) => { variation.chain.forEach(dir => { if (!allDirs.includes(dir)) allDirs.push(dir); }); return allDirs; }, []); } module.exports = VariationConfig;
const parseVariations = require('../variations'); const createValidator = require('./validator'); const validate = createValidator({ variations: {type: 'array', minLen: 1}, // There can be a user of Mendel who does not want variation but faster build. allVariationDirs: {type: 'array', minLen: 0}, allDirs: {type: 'array', minLen: 1}, }); function VariationConfig(config) { const variations = parseVariations(config); const allVariationDirs = getAllDirs(variations); const baseVariation = { id: config.baseConfig.id, chain: [config.baseConfig.dir], }; variations.push(baseVariation); const allDirs = getAllDirs(variations); const variationConfig = { variations, baseVariation, allDirs, allVariationDirs, }; validate(variationConfig); return variationConfig; } function getAllDirs(variationArray) { return variationArray.reduce((allDirs, variation) => { variation.chain.forEach(dir => { if (!allDirs.includes(dir)) allDirs.push(dir); }); return allDirs; }, []); } module.exports = VariationConfig;
Add vumi and klein to requirements
from setuptools import setup, find_packages setup( name="vxtwinio", version="0.0.1a", url="https://github.com/praekelt/vumi-twilio-api", license="BSD", description="Provides a REST API to Vumi that emulates the Twilio API", long_description=open("README.rst", "r").read(), author="Praekelt Foundation", author_email="dev@praekeltfoundation.org", packages=find_packages(), scripts=[], install_requires=[ 'vumi', 'klein', ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System :: Networking', ], )
from setuptools import setup, find_packages setup( name="vxtwinio", version="0.0.1a", url="https://github.com/praekelt/vumi-twilio-api", license="BSD", description="Provides a REST API to Vumi that emulates the Twilio API", long_description=open("README.rst", "r").read(), author="Praekelt Foundation", author_email="dev@praekeltfoundation.org", packages=find_packages(), scripts=[], install_requires=[], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System :: Networking', ], )
Add utility method to delete all documents of given resource
import json from os import environ from eve import Eve from eve.io.mongo import Validator from settings import API_NAME, URL_PREFIX class KeySchemaValidator(Validator): def _validate_keyschema(self, schema, field, dct): "Validate all keys of dictionary `dct` against schema `schema`." for key, value in dct.items(): self._validate_schema(schema, key, value) api = Eve(API_NAME, validator=KeySchemaValidator) def add_document(resource, document): "Add a new document to the given resource." return api.test_client().post('/' + URL_PREFIX + '/' + resource, data=json.dumps(document), content_type='application/json') def delete_resource(resource): "Delete all documents of the given resource." return api.test_client().delete('/' + URL_PREFIX + '/' + resource) if __name__ == '__main__': # Heroku support: bind to PORT if defined, otherwise default to 5000. if 'PORT' in environ: port = int(environ.get('PORT')) host = '0.0.0.0' else: port = 5000 host = '127.0.0.1' api.run(host=host, port=port)
import json from os import environ from eve import Eve from eve.io.mongo import Validator from settings import API_NAME, URL_PREFIX class KeySchemaValidator(Validator): def _validate_keyschema(self, schema, field, dct): "Validate all keys of dictionary `dct` against schema `schema`." for key, value in dct.items(): self._validate_schema(schema, key, value) api = Eve(API_NAME, validator=KeySchemaValidator) def add_document(resource, document): "Add a new document to the given resource." return api.test_client().post('/' + URL_PREFIX + '/' + resource, data=json.dumps(document), content_type='application/json') if __name__ == '__main__': # Heroku support: bind to PORT if defined, otherwise default to 5000. if 'PORT' in environ: port = int(environ.get('PORT')) host = '0.0.0.0' else: port = 5000 host = '127.0.0.1' api.run(host=host, port=port)
Add basic JS runtime error notification
/** * Copyright (c) 2014, Tidepool Project * * This program is free software; you can redistribute it and/or modify it under * the terms of the associated License, which is identical to the BSD 2-Clause * License as published by the Open Source Initiative at opensource.org. * * This program 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 License for more details. * * You should have received a copy of the License along with this program; if * not, you can obtain one from Tidepool Project at tidepool.org. */ /* global app */ window.onerror = function myErrorHandler(errorMessage, fileUrl, lineNumber) { var text = [ 'Sorry! Something went wrong. It\'s our fault, not yours.', 'We\'re going to go investigate.', 'For the time being, try refreshing your browser?', 'Original error message:', '"' + errorMessage + '"', '(' + fileUrl + ' at line ' + lineNumber + ')' ].join(' '); var style = [ 'position: fixed;', 'top: 0;', 'left: 0;', 'right: 0;', 'padding: 20px;', 'text-align: center;', 'background: #ff8b7c;', 'color: #fff;' ].join(' '); var el = document.createElement('div'); el.textContent = text; el.setAttribute('style', style); document.body.appendChild(el); // Let default handler run return false; }; app.start();
/** * Copyright (c) 2014, Tidepool Project * * This program is free software; you can redistribute it and/or modify it under * the terms of the associated License, which is identical to the BSD 2-Clause * License as published by the Open Source Initiative at opensource.org. * * This program 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 License for more details. * * You should have received a copy of the License along with this program; if * not, you can obtain one from Tidepool Project at tidepool.org. */ /* global app */ try { app.start(); } catch (e) { var error = [ 'Could not start app,', 'please check if source was compiled successfully', '(Browserify, React JSX Transform).' ].join(' '); throw new Error(error + ' Original error: ' + e.message); }
Change the method of generating content of GUID element
# -*- coding: utf-8 -*- # Copyright: 2011, Grigoriy Petukhov # Author: Grigoriy Petukhov (http://lorien.name) # License: BSD from django.contrib.syndication.views import Feed from django.conf import settings from feedzilla.models import Post class PostFeed(Feed): title_template = 'feedzilla/feed/post_title.html' description_template = 'feedzilla/feed/post_description.html' title = settings.FEEDZILLA_SITE_TITLE description = settings.FEEDZILLA_SITE_DESCRIPTION link = '/' def items(self, obj): return Post.active_objects.all()\ .order_by('-created')[:settings.FEEDZILLA_PAGE_SIZE] #def item_title(self, item): #return item.name #def item_description(self, item): #return item.description def item_pubdate(self, item): return item.created def item_guid(self, item): return item.link
# -*- coding: utf-8 -*- # Copyright: 2011, Grigoriy Petukhov # Author: Grigoriy Petukhov (http://lorien.name) # License: BSD from django.contrib.syndication.views import Feed from django.conf import settings from feedzilla.models import Post class PostFeed(Feed): title_template = 'feedzilla/feed/post_title.html' description_template = 'feedzilla/feed/post_description.html' title = settings.FEEDZILLA_SITE_TITLE description = settings.FEEDZILLA_SITE_DESCRIPTION link = '/' def items(self, obj): return Post.active_objects.all()\ .order_by('-created')[:settings.FEEDZILLA_PAGE_SIZE] #def item_title(self, item): #return item.name #def item_description(self, item): #return item.description def item_pubdate(self, item): return item.created def item_guid(self, item): return str(item.guid)
Use Google symbol in the example.
"use strict"; var assert = require("assert"), finance = require("../lib/finance"); var params = {}; params.prods = ["IBM", "GOOGL", "MSFT"]; params.referenceDate = "Sat Aug 06 2011 12:00:00"; params.targetReturn = undefined; params.lows = [0, 0, 0]; params.highs = [-1, -1, -1]; finance.portfolio.getOptimalPortfolio(params, function (err, res) { var i; if (!err) { console.log("Portfolio assets are the following: " + params.prods); for (i = 0; i < params.prods.length; i += 1) { console.log("Optimal weight for " + params.prods[i] + " is " + res.optim.solution[i]); } assert.equal(0.50229, res.optim.solution[0].toFixed(5)); assert.equal(0.01593, res.optim.solution[1].toFixed(5)); assert.equal(0.48179, res.optim.solution[2].toFixed(5)); } else { console.log(err); } });
"use strict"; var assert = require("assert"), finance = require("../lib/finance"); var params = {}; params.prods = ["IBM", "YHOO", "MSFT"]; params.referenceDate = "Sat Aug 06 2011 12:00:00"; params.targetReturn = undefined; params.lows = [0, 0, 0]; params.highs = [-1, -1, -1]; finance.portfolio.getOptimalPortfolio(params, function (err, res) { var i; if (!err) { console.log("Portfolio assets are the following: " + params.prods); for (i = 0; i < params.prods.length; i += 1) { console.log("Optimal weight for " + params.prods[i] + " is " + res.optim.solution[i]); } assert.equal(0.25689, res.optim.solution[0].toFixed(5)); assert.equal(0.24762, res.optim.solution[1].toFixed(5)); assert.equal(0.49549, res.optim.solution[2].toFixed(5)); } else { console.log(err); } });
Add the Unit Test as a Library to the EAR prior to deployment.
/* * This file is part of COMPASS. It is subject to the license terms in * the LICENSE file found in the top-level directory of this distribution. * (Also available at http://www.apache.org/licenses/LICENSE-2.0.txt) * You may not use this file except in compliance with the License. */ package de.dfki.asr.compass.test.integration; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.testng.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; public class DeploymentDeployTest extends Arquillian { public static final String ARTIFACT = "de.dfki.asr.compass:compass-deployment:ear:?"; @Deployment public static EnterpriseArchive getCoreCompassDeployment() { JavaArchive testWar = ShrinkWrap .create(JavaArchive.class) .addClass(DeploymentDeployTest.class); EnterpriseArchive compass = Maven.configureResolverViaPlugin() .resolve(ARTIFACT) .withoutTransitivity() .asSingle(EnterpriseArchive.class); compass.addAsLibrary(testWar); return compass; } @Test public void itWorked() { assertTrue(true); } }
/* * This file is part of COMPASS. It is subject to the license terms in * the LICENSE file found in the top-level directory of this distribution. * (Also available at http://www.apache.org/licenses/LICENSE-2.0.txt) * You may not use this file except in compliance with the License. */ package de.dfki.asr.compass.test.integration; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.testng.Arquillian; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; public class DeploymentDeployTest extends Arquillian { public static final String ARTIFACT = "de.dfki.asr.compass:compass-deployment:ear:?"; @Deployment public static EnterpriseArchive getCoreCompassDeployment() { return Maven.configureResolverViaPlugin() .resolve(ARTIFACT) .withoutTransitivity() .asSingle(EnterpriseArchive.class); } @Test public void itWorked() { assertTrue(true); } }
Fix bug with travis CI
import fs from 'fs'; import path from 'path'; import Sequelize from 'sequelize'; import configs from '../config/config.json'; const basename = path.basename(module.filename); const env = process.env.NODE_ENV || 'test'; const config = configs[env]; const db = {}; let sequelize; if (config.use_env_variable) { sequelize = new Sequelize(process.env[config.use_env_variable]); } else { sequelize = new Sequelize(config.database, config.username, config.password, config); } fs .readdirSync(__dirname) .filter((file) => { const fileName = (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js'); return fileName; }) .forEach((file) => { const model = sequelize.import(path.join(__dirname, file)); db[model.name] = model; }); Object.keys(db).forEach((modelName) => { if (db[modelName].associate) { db[modelName].associate(db); } }); db.sequelize = sequelize; db.Sequelize = Sequelize; module.exports = db;
import fs from 'fs'; import path from 'path'; import Sequelize from 'sequelize'; import configs from '../config/config.json'; const basename = path.basename(module.filename); const env = process.env.NODE_ENV || 'development'; const config = configs[env]; const db = {}; let sequelize; if (config.use_env_variable) { sequelize = new Sequelize(process.env[config.use_env_variable]); } else { sequelize = new Sequelize(config.database, config.username, config.password, config); } fs .readdirSync(__dirname) .filter((file) => { const fileName = (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js'); return fileName; }) .forEach((file) => { const model = sequelize.import(path.join(__dirname, file)); db[model.name] = model; }); Object.keys(db).forEach((modelName) => { if (db[modelName].associate) { db[modelName].associate(db); } }); db.sequelize = sequelize; db.Sequelize = Sequelize; module.exports = db;
Change credential check to not fetch credential to check existence
package com.google.step.coffee.servlets; import com.google.api.client.auth.oauth2.Credential; import com.google.step.coffee.JsonServlet; import com.google.step.coffee.JsonServletRequest; import com.google.step.coffee.OAuthService; import com.google.step.coffee.UserManager; import java.io.IOException; import javax.servlet.annotation.WebServlet; /** * Manage and check user authorisation for scopes for Google Calendar API in * <code>OAuthService</code> */ @WebServlet("/api/auth/calendar") public class AuthCalendarServlet extends JsonServlet { /** Response object for fetching authorisation status of user. */ private static class CalAuthResponse { private boolean authorised; private String authLink; CalAuthResponse(boolean authorised) { this.authorised = authorised; } CalAuthResponse(boolean authorised, String authLink) { this(authorised); this.authLink = authLink; } } @Override public Object get(JsonServletRequest request) throws IOException { CalAuthResponse responseData; if (OAuthService.userHasAuthorised(UserManager.getCurrentUserId())) { responseData = new CalAuthResponse(false, OAuthService.getAuthURL(request)); } else { responseData = new CalAuthResponse(true); } return responseData; } }
package com.google.step.coffee.servlets; import com.google.api.client.auth.oauth2.Credential; import com.google.step.coffee.JsonServlet; import com.google.step.coffee.JsonServletRequest; import com.google.step.coffee.OAuthService; import com.google.step.coffee.UserManager; import java.io.IOException; import javax.servlet.annotation.WebServlet; /** * Manage and check user authorisation for scopes for Google Calendar API in * <code>OAuthService</code> */ @WebServlet("/api/auth/calendar") public class AuthCalendarServlet extends JsonServlet { /** Response object for fetching authorisation status of user. */ private static class CalAuthResponse { private boolean authorised; private String authLink; CalAuthResponse(boolean authorised) { this.authorised = authorised; } CalAuthResponse(boolean authorised, String authLink) { this(authorised); this.authLink = authLink; } } @Override public Object get(JsonServletRequest request) throws IOException { CalAuthResponse responseData; Credential credentials = OAuthService.getCredentials(UserManager.getCurrentUserId()); if (credentials != null) { responseData = new CalAuthResponse(true); } else { responseData = new CalAuthResponse(false, OAuthService.getAuthURL(request)); } return responseData; } }
Add help_text for time_from and time_until
from django.db import models from django.core.urlresolvers import reverse class Chart(models.Model): title = models.CharField(max_length=50) url = models.CharField(max_length=1024) def __unicode__(self): return self.title class Page(models.Model): title = models.CharField(max_length=50) slug = models.SlugField() charts = models.ManyToManyField(Chart) time_from = models.CharField( max_length=50, default=u"-24h", help_text=u"The default 'from' parameter to use for all charts on this page. Can be overridden via GET param when viewing the Page.", ) time_until = models.CharField( max_length=50, default=u"", blank=True, help_text=u"The default 'until' parameter to use for all charts on this page. Can be overridden via GET param when viewing this Page.", ) image_width = models.PositiveIntegerField(default=1200) image_height = models.PositiveIntegerField(default=400) def __unicode__(self): return self.title def get_absolute_url(self): return reverse('page_detail', kwargs={'slug': self.slug})
from django.db import models from django.core.urlresolvers import reverse class Chart(models.Model): title = models.CharField(max_length=50) url = models.CharField(max_length=1024) def __unicode__(self): return self.title class Page(models.Model): title = models.CharField(max_length=50) slug = models.SlugField() charts = models.ManyToManyField(Chart) time_from = models.CharField(max_length=50, default=u"-24h") time_until = models.CharField(max_length=50, default=u"", blank=True) image_width = models.PositiveIntegerField(default=1200) image_height = models.PositiveIntegerField(default=400) def __unicode__(self): return self.title def get_absolute_url(self): return reverse('page_detail', kwargs={'slug': self.slug})
Change so original input does not change.
""" Proto type that does the following: input:Excel file in language A output 1:Copy of input file, with original strings replaced with serial numbers output 2:Single xlsx file that contains serial numbers and original texts from input file. """ import shutil from openpyxl import load_workbook, Workbook #point to the file to be read. Intuitive. wb2 = load_workbook('sample-input-fortest.xlsx') #convince your self that sheet names are retireved. sheet_names = wb2.get_sheet_names() print sheet_names #work book is simply a list of sheets sheet = wb2[sheet_names[0]] print sheet #go trhough the excel file, extract strings & replace with number. string_list = list() string_list.append(("sequence_number","original language")) seq_no = 1 for sheet in wb2: for row in sheet.rows: for cell in row: if None!=cell.value: string_list.append((seq_no,cell.value)) cell.value=str(seq_no) seq_no+=1 #save the file containing numbers that replaced the string. wb2.save('sample-input-fortest-out.xlsx') #save the extracted strings wb_out = Workbook(write_only=True) ws = wb_out.create_sheet() for string in string_list: ws.append(string) wb_out.save('new_big_file.xlsx')
""" Proto type that does the following: input:Excel file in language A output 1:Copy of input file, with original strings replaced with serial numbers output 2:Single xlsx file that contains serial numbers and original texts from input file. """ import shutil from openpyxl import load_workbook, Workbook shutil.copyfile('sample-input-fortest.xlsx','sample-input-fortest-out.xlsx') #point to the file to be read. Intuitive. wb2 = load_workbook('sample-input-fortest.xlsx') #convince your self that sheet names are retireved. sheet_names = wb2.get_sheet_names() print sheet_names #work book is simply a list of sheets sheet = wb2[sheet_names[0]] print sheet print "can iterate sheets, rows and columns intuitively" string_list = list() string_list.append(("sequence_number","original language")) seq_no = 1 for sheet in wb2: for row in sheet.rows: for cell in row: if None!=cell.value: string_list.append((seq_no,cell.value)) seq_no+=1 wb_out = Workbook(write_only=True) ws = wb_out.create_sheet() for string in string_list: ws.append(string) wb_out.save('new_big_file.xlsx')
Use path.join for link prefixing
import { config } from 'config' import invariant from 'invariant' import isString from 'lodash/isString' import path from 'path' function isDataURL (s) { // Regex from https://gist.github.com/bgrins/6194623#gistcomment-1671744 // eslint-disable-next-line max-len const regex = /^\s*data:([a-z]+\/[a-z0-9\-\+]+(;[a-z\-]+=[a-z0-9\-]+)?)?(;base64)?,[a-z0-9!\$&',\(\)\*\+,;=\-\._~:@\/\?%\s]*\s*$/i return !!s.match(regex) } // Function to add prefix to links. const prefixLink = (_link) => { if ( (typeof __PREFIX_LINKS__ !== 'undefined' && __PREFIX_LINKS__ !== null) && __PREFIX_LINKS__ && (config.linkPrefix !== null )) { const invariantMessage = ` You're trying to build your site with links prefixed but you haven't set 'linkPrefix' in your config.toml. ` invariant(isString(config.linkPrefix), invariantMessage) return isDataURL(_link) ? _link : path.join(config.linkPrefix, _link) } else { return _link } } module.exports = { prefixLink, }
import { config } from 'config' import invariant from 'invariant' import isString from 'lodash/isString' function isDataURL (s) { // Regex from https://gist.github.com/bgrins/6194623#gistcomment-1671744 // eslint-disable-next-line max-len const regex = /^\s*data:([a-z]+\/[a-z0-9\-\+]+(;[a-z\-]+=[a-z0-9\-]+)?)?(;base64)?,[a-z0-9!\$&',\(\)\*\+,;=\-\._~:@\/\?%\s]*\s*$/i return !!s.match(regex) } // Function to add prefix to links. const prefixLink = (_link) => { if ( (typeof __PREFIX_LINKS__ !== 'undefined' && __PREFIX_LINKS__ !== null) && __PREFIX_LINKS__ && (config.linkPrefix !== null )) { const invariantMessage = ` You're trying to build your site with links prefixed but you haven't set 'linkPrefix' in your config.toml. ` invariant(isString(config.linkPrefix), invariantMessage) return isDataURL(_link) ? _link : config.linkPrefix + _link } else { return _link } } module.exports = { prefixLink, }
[1.8] Remove an error message logged when FBTrace is not installed. http://code.google.com/p/fbug/source/detail?r=10890
/* See license.txt for terms of usage */ // ************************************************************************************************ // Constants const Cc = Components.classes; const Ci = Components.interfaces; const Cr = Components.results; var EXPORTED_SYMBOLS = ["traceConsoleService"]; // ************************************************************************************************ // Service implementation /** * This implementation serves as a proxy to the FBTrace extension. All logs are forwarded * to the FBTrace service. */ try { Components.utils["import"]("resource://fbtrace/firebug-trace-service.js"); } catch (err) { var traceConsoleService = { getTracer: function(prefDomain) { var TraceAPI = ["dump", "sysout", "setScope", "matchesNode", "time", "timeEnd"]; var TraceObj = {}; for (var i=0; i<TraceAPI.length; i++) TraceObj[TraceAPI[i]] = function() {}; return TraceObj; } }; }
/* See license.txt for terms of usage */ // ************************************************************************************************ // Constants const Cc = Components.classes; const Ci = Components.interfaces; const Cr = Components.results; var EXPORTED_SYMBOLS = ["traceConsoleService"]; // ************************************************************************************************ // Service implementation /** * This implementation serves as a proxy to the FBTrace extension. All logs are forwarded * to the FBTrace service. */ try { Components.utils["import"]("resource://fbtrace/firebug-trace-service.js"); } catch (err) { dump("FBTrace is not installed, use default (empty) implementation.\n"); var traceConsoleService = { getTracer: function(prefDomain) { var TraceAPI = ["dump", "sysout", "setScope", "matchesNode", "time", "timeEnd"]; var TraceObj = {}; for (var i=0; i<TraceAPI.length; i++) TraceObj[TraceAPI[i]] = function() {}; return TraceObj; } }; }
Add sorting for gridfield in modeladmin
<?php class StaffAdmin extends ModelAdmin { private static $managed_models = array( 'Staff', 'StaffCategory' ); private static $url_segment = 'staff'; private static $menu_title = 'Staff'; private static $menu_icon = 'staff/images/staffadmin-file.png'; public function canCreate($Member = null) { return true; } public function canEdit($Member = null) { return true; } public function canView($Member = null) { return true; } public function canDelete($Member = null) { return true; } public function getEditForm($id = null, $fields = null) { $form=parent::getEditForm($id, $fields); if ($this->modelClass=='Staff' && $gridField=$form->Fields()->dataFieldByName($this->sanitiseClassName($this->modelClass))) { } if($gridField instanceof GridField) { $gridField->getConfig()->addComponent(new GridFieldSortableRows('SortOrder')); } return $form; } }
<?php class StaffAdmin extends ModelAdmin { private static $managed_models = array( 'Staff', 'StaffCategory' ); private static $url_segment = 'staff'; private static $menu_title = 'Staff'; private static $menu_icon = 'staff/images/staffadmin-file.png'; public function canCreate($Member = null) { return true; } public function canEdit($Member = null) { return true; } public function canView($Member = null) { return true; } public function canDelete($Member = null) { return true; } public function getEditForm($id = null, $fields = null) { $form=parent::getEditForm($id, $fields); if ($this->modelClass=='Staff' && $gridField=$form->Fields()->dataFieldByName($this->sanitiseClassName($this->modelClass))) { } return $form; } }
Remove error handling for cases that never occur with benchmark data
package ingraph.bulkloader.csv.loader.cellprocessor; import org.supercsv.cellprocessor.CellProcessorAdaptor; import org.supercsv.cellprocessor.ift.StringCellProcessor; import org.supercsv.util.CsvContext; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.TimeZone; abstract public class AbstractParseEpoch extends CellProcessorAdaptor implements StringCellProcessor { protected final DateFormat formatter; public AbstractParseEpoch(final String dateTimeFormat) { super(); formatter = new SimpleDateFormat(dateTimeFormat); formatter.setTimeZone(TimeZone.getTimeZone("GMT")); } public Object execute(final Object value, final CsvContext context) { validateInputNotNull(value, context); long epoch = Long.parseLong(value.toString()); long result = Long.valueOf(formatter.format(new java.util.Date(epoch))); return next.execute(result, context); } }
package ingraph.bulkloader.csv.loader.cellprocessor; import org.supercsv.cellprocessor.CellProcessorAdaptor; import org.supercsv.cellprocessor.ift.StringCellProcessor; import org.supercsv.exception.SuperCsvCellProcessorException; import org.supercsv.util.CsvContext; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.TimeZone; abstract public class AbstractParseEpoch extends CellProcessorAdaptor implements StringCellProcessor { protected final DateFormat formatter; public AbstractParseEpoch(final String dateTimeFormat) { super(); formatter = new SimpleDateFormat(dateTimeFormat); formatter.setTimeZone(TimeZone.getTimeZone("GMT")); } public Object execute(final Object value, final CsvContext context) { validateInputNotNull(value, context); if (!(value instanceof String)) { throw new SuperCsvCellProcessorException(String.class, value, context, this); } long epoch = Long.parseLong(value.toString()); long result = Long.valueOf(formatter.format(new java.util.Date(epoch))); return next.execute(result, context); } }
tracking: Add Mixpanel event on Control clicks We'd like to gain some insight on how controls are used.
import React from 'react'; import { connect } from 'react-redux'; import { trackMixpanelEvent } from '../../utils/tracking-utils'; import { doControl } from '../../actions/app-actions'; class NodeDetailsControlButton extends React.Component { constructor(props, context) { super(props, context); this.handleClick = this.handleClick.bind(this); } render() { let className = `node-control-button fa ${this.props.control.icon}`; if (this.props.pending) { className += ' node-control-button-pending'; } return ( <span className={className} title={this.props.control.human} onClick={this.handleClick} /> ); } handleClick(ev) { ev.preventDefault(); const { id, human } = this.props.control; trackMixpanelEvent('scope.node.control.click', { id, title: human }); this.props.dispatch(doControl(this.props.nodeId, this.props.control)); } } // Using this instead of PureComponent because of props.dispatch export default connect()(NodeDetailsControlButton);
import React from 'react'; import { connect } from 'react-redux'; import { doControl } from '../../actions/app-actions'; class NodeDetailsControlButton extends React.Component { constructor(props, context) { super(props, context); this.handleClick = this.handleClick.bind(this); } render() { let className = `node-control-button fa ${this.props.control.icon}`; if (this.props.pending) { className += ' node-control-button-pending'; } return ( <span className={className} title={this.props.control.human} onClick={this.handleClick} /> ); } handleClick(ev) { ev.preventDefault(); this.props.dispatch(doControl(this.props.nodeId, this.props.control)); } } // Using this instead of PureComponent because of props.dispatch export default connect()(NodeDetailsControlButton);
Create a method that generates a concatenated list of Bootstrap CSS col-*-* classes suitable for thumbnails.
<?php /** * Class GalleryImageExtension * * @property Image|GalleryImageExtension $owner */ class GalleryImageExtension extends DataExtension { private static $db = array( 'Caption' => 'Text', ); private static $belongs_many_many = array( 'GalleryPage' => 'GalleryPage', ); public function updateCMSFields(FieldList $fields) { $fields->addFieldToTab('Root.Main', new TextField('Caption', 'Kuvateksti'), 'Title'); $fields->removeFieldsFromTab('Root.Main', array('Title','Name','OwnerID','ParentID')); } public function GalleryThumbnail() { return $this->owner->Fit($this->GalleryThumbnailWidth(), $this->GalleryThumbnailHeight()); } public function GalleryThumbnailWidth() { return (int) GalleryImage::config()->get('thumbnail_width'); } public function GalleryThumbnailHeight() { return (int) GalleryImage::config()->get('thumbnail_height'); } public function BootstrapCSSColumnClasses() { $columns = GalleryImage::config()->get('thumbnail_cols'); $result = ''; foreach ($columns as $type => $size) { if ($result) $result .= ' '; $result .= "col-$type-$size"; //For example: col-md-12 } return $result; } }
<?php /** * Class GalleryImageExtension * * @property Image|GalleryImageExtension $owner */ class GalleryImageExtension extends DataExtension { private static $db = array( 'Caption' => 'Text', ); private static $belongs_many_many = array( 'GalleryPage' => 'GalleryPage', ); public function updateCMSFields(FieldList $fields) { $fields->addFieldToTab('Root.Main', new TextField('Caption', 'Kuvateksti'), 'Title'); $fields->removeFieldsFromTab('Root.Main', array('Title','Name','OwnerID','ParentID')); } public function GalleryThumbnail() { return $this->owner->Fit($this->GalleryThumbnailWidth(), $this->GalleryThumbnailHeight()); } public function GalleryThumbnailWidth() { return (int) GalleryImage::config()->get('thumbnail_width'); } public function GalleryThumbnailHeight() { return (int) GalleryImage::config()->get('thumbnail_height'); } }
Add class for preventing overlay only if not already set
(function () { 'use strict'; // Hide overlay when ESC is pressed document.addEventListener('keyup', function (event) { var hash = window.location.hash.replace('#', ''); // If hash is not set if (hash === '' || hash === '!') { return; } // If key ESC is pressed if (event.keyCode === 27) { window.location.hash = '!'; } }, false); // When showing overlay, prevent background from scrolling window.addEventListener('hashchange', function () { var hash = window.location.hash.replace('#', ''); // If hash is set if (hash !== '' && hash !== '!') { // And has-overlay is not set yet if (!document.body.className.match(/has-overlay/)) { document.body.className += ' has-overlay'; } } else { document.body.className = document.body.className.replace(' has-overlay', ''); } }, false); }());
(function () { 'use strict'; // Hide overlay when ESC is pressed document.addEventListener('keyup', function (event) { var hash = window.location.hash.replace('#', ''); // If hash is not set if (hash === '' || hash === '!') { return; } // If key ESC is pressed if (event.keyCode === 27) { window.location.hash = '!'; } }, false); // When showing overlay, prevent background from scrolling window.addEventListener('hashchange', function () { var hash = window.location.hash.replace('#', ''); // If hash is set if (hash !== '' && hash !== '!') { document.body.className += ' has-overlay'; } else { document.body.className = document.body.className.replace(' has-overlay', ''); } }, false); }());
Fix flipped open/closed status for Diviner atoms in search index Summary: Fixes T12258. I think these constants are just flipped. Test Plan: Kinda winged it. Reviewers: chad Reviewed By: chad Maniphest Tasks: T12258 Differential Revision: https://secure.phabricator.com/D17346
<?php final class DivinerLiveSymbolFulltextEngine extends PhabricatorFulltextEngine { protected function buildAbstractDocument( PhabricatorSearchAbstractDocument $document, $object) { $atom = $object; $book = $atom->getBook(); $document ->setDocumentTitle($atom->getTitle()) ->setDocumentCreated($book->getDateCreated()) ->setDocumentModified($book->getDateModified()); $document->addField( PhabricatorSearchDocumentFieldType::FIELD_BODY, $atom->getSummary()); $document->addRelationship( PhabricatorSearchRelationship::RELATIONSHIP_BOOK, $atom->getBookPHID(), DivinerBookPHIDType::TYPECONST, PhabricatorTime::getNow()); $document->addRelationship( PhabricatorSearchRelationship::RELATIONSHIP_REPOSITORY, $atom->getRepositoryPHID(), PhabricatorRepositoryRepositoryPHIDType::TYPECONST, PhabricatorTime::getNow()); $document->addRelationship( $atom->getGraphHash() ? PhabricatorSearchRelationship::RELATIONSHIP_OPEN : PhabricatorSearchRelationship::RELATIONSHIP_CLOSED, $atom->getBookPHID(), DivinerBookPHIDType::TYPECONST, PhabricatorTime::getNow()); } }
<?php final class DivinerLiveSymbolFulltextEngine extends PhabricatorFulltextEngine { protected function buildAbstractDocument( PhabricatorSearchAbstractDocument $document, $object) { $atom = $object; $book = $atom->getBook(); $document ->setDocumentTitle($atom->getTitle()) ->setDocumentCreated($book->getDateCreated()) ->setDocumentModified($book->getDateModified()); $document->addField( PhabricatorSearchDocumentFieldType::FIELD_BODY, $atom->getSummary()); $document->addRelationship( PhabricatorSearchRelationship::RELATIONSHIP_BOOK, $atom->getBookPHID(), DivinerBookPHIDType::TYPECONST, PhabricatorTime::getNow()); $document->addRelationship( PhabricatorSearchRelationship::RELATIONSHIP_REPOSITORY, $atom->getRepositoryPHID(), PhabricatorRepositoryRepositoryPHIDType::TYPECONST, PhabricatorTime::getNow()); $document->addRelationship( $atom->getGraphHash() ? PhabricatorSearchRelationship::RELATIONSHIP_CLOSED : PhabricatorSearchRelationship::RELATIONSHIP_OPEN, $atom->getBookPHID(), DivinerBookPHIDType::TYPECONST, PhabricatorTime::getNow()); } }
Create checkWinner Function that alerts when a player has reached the finish line
function Game(){ this.$track = $('#racetrack'); this.finishLine = this.$track.width() - 54; } function Player(id){ this.player = $('.player')[id - 1]; this.position = 10; } Player.prototype.move = function(){ this.position += 20; }; Player.prototype.updatePosition = function(){ $player = $(this.player); $player.css('margin-left', this.position); }; function checkWinner(player, game){ if( player.position > game.finishLine ){ alert("somebody won!"); } } $(document).ready(function() { var game = new Game(); var player1 = new Player(1); var player2 = new Player(2); $(document).on('keyup', function(keyPress){ if(keyPress.keyCode === 80) { player1.move(); player1.updatePosition(); } else if (keyPress.keyCode === 81) { player2.move(); player2.updatePosition(); } }); });
function Game(){ this.$track = $('#racetrack'); this.finishLine = this.$track.width() - 54; } function Player(id){ this.player = $('.player')[id - 1]; this.position = 10; } Player.prototype.move = function(){ this.position += 20; }; Player.prototype.updatePosition = function(){ $player = $(this.player); $player.css('margin-left', this.position); }; Player.prototype.checkWinner = function(){ }; $(document).ready(function() { var game = new Game(); var player1 = new Player(1); var player2 = new Player(2); $(document).on('keyup', function(keyPress){ if(keyPress.keyCode === 80) { player1.move(); player1.updatePosition(); } else if (keyPress.keyCode === 81) { player2.move(); player2.updatePosition(); } }); });
Add underscore dependency to data loader
"use strict"; var $ = require('jquery'); var _ = require('underscore'); var DataLoader = function() { return { get: function(uniprotID) { return $.ajax('http://ves-ebi-ca:8082/us/rest/features/' + uniprotID, { //return $.ajax('data/features.json', { params: { //put things in here if we need } }).done(function(d) { return processData(d); }).fail(function(e){ return(e); }); } }; } (); var processData = function(d) { var consecutive = 1; _.each(d, function(datum) { if (datum.features) { _.each(datum.features, function(feature) { feature.internalId = "ft_" + consecutive; consecutive++; }); } }); d.totalFeatureCount = consecutive; return d; }; module.exports = DataLoader;
"use strict"; var $ = require('jquery'); var DataLoader = function() { return { get: function(uniprotID) { return $.ajax('http://ves-ebi-ca:8082/us/rest/features/' + uniprotID, { params: { //put things in here if we need } }).done(function(d) { return processData(d); }).fail(function(e){ return(e); }); } }; } (); var processData = function(d) { var consecutive = 1; _.each(d, function(datum) { if (datum.features) { _.each(datum.features, function(feature) { feature.internalId = "ft_" + consecutive; consecutive++; }); } }); d.totalFeatureCount = consecutive; return d; }; module.exports = DataLoader;
Fix race with in-memory store
package imagestore import ( "errors" "io" "io/ioutil" "strings" "sync" ) type InMemoryImageStore struct { files map[string]string // name -> contents rw sync.Mutex } func NewInMemoryImageStore() *InMemoryImageStore { return &InMemoryImageStore{ files: make(map[string]string), rw: sync.Mutex{}, } } func (this *InMemoryImageStore) Exists(obj *StoreObject) (bool, error) { this.rw.Lock() _, ok := this.files[obj.Name] this.rw.Unlock() return ok, nil } func (this *InMemoryImageStore) Save(src io.Reader, obj *StoreObject) (*StoreObject, error) { data, err := ioutil.ReadAll(src) if err != nil { return nil, err } this.rw.Lock() this.files[obj.Name] = string(data) this.rw.Unlock() return obj, nil } func (this *InMemoryImageStore) Get(obj *StoreObject) (io.Reader, error) { this.rw.Lock() data, ok := this.files[obj.Name] this.rw.Unlock() if !ok { return nil, errors.New("File doesn't exist") } return strings.NewReader(data), nil }
package imagestore import ( "errors" "io" "io/ioutil" "strings" ) type InMemoryImageStore struct { files map[string]string // name -> contents } func NewInMemoryImageStore() *InMemoryImageStore { return &InMemoryImageStore{ files: make(map[string]string), } } func (this *InMemoryImageStore) Exists(obj *StoreObject) (bool, error) { _, ok := this.files[obj.Name] return ok, nil } func (this *InMemoryImageStore) Save(src io.Reader, obj *StoreObject) (*StoreObject, error) { data, err := ioutil.ReadAll(src) if err != nil { return nil, err } this.files[obj.Name] = string(data) return obj, nil } func (this *InMemoryImageStore) Get(obj *StoreObject) (io.Reader, error) { data, ok := this.files[obj.Name] if !ok { return nil, errors.New("File doesn't exist") } return strings.NewReader(data), nil }
Fix path of jquery-ui effects.
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require jquery-ui/effects/effect-highlight //= require twitter/bootstrap // require turbolinks //= require gmaps/google //= require jquery-readyselector //= require jquery-fileupload/basic //= require switchery //= require moment //= require bootstrap-datetimepicker //= require vue //= require vue-router //= require_tree . Vue.use( VueRouter ); Vue.filter( 'padding', function( value, length, character ) { var strlen = ( value + '' ).length; for ( strlen; strlen < length; strlen++ ) { value = ( character ).concat( value ); } return value; } );
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require jquery-ui/effect-highlight //= require twitter/bootstrap // require turbolinks //= require gmaps/google //= require jquery-readyselector //= require jquery-fileupload/basic //= require switchery //= require moment //= require bootstrap-datetimepicker //= require vue //= require vue-router //= require_tree . Vue.use( VueRouter ); Vue.filter( 'padding', function( value, length, character ) { var strlen = ( value + '' ).length; for ( strlen; strlen < length; strlen++ ) { value = ( character ).concat( value ); } return value; } );
Delete blank line at end of file
# Copyright (c) 2012-2013, Itzik Kotler # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # * Neither the name of the author nor the names of its contributors may # be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Copyright (c) 2012-2013, Itzik Kotler # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # * Neither the name of the author nor the names of its contributors may # be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Remove the 1 in the Development status classifier
from setuptools import setup, find_packages setup( name="django-salmonella", version="0.4.1", author='Lincoln Loop: Seth Buntin, Yann Malet', author_email='info@lincolnloop.com', description=("raw_id_fields widget replacement that handles display of an object's " "string value on change and can be overridden via a template."), packages=find_packages(), package_data={'salmonella': ['static/*.js', 'templates/salmonella/*.html', 'templates/salmonella/admin/widgets/*.html']}, url="http://github.com/lincolnloop/django-salmonella/", install_requires=['setuptools'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
from setuptools import setup, find_packages setup( name="django-salmonella", version="0.4.1", author='Lincoln Loop: Seth Buntin, Yann Malet', author_email='info@lincolnloop.com', description=("raw_id_fields widget replacement that handles display of an object's " "string value on change and can be overridden via a template."), packages=find_packages(), package_data={'salmonella': ['static/*.js', 'templates/salmonella/*.html', 'templates/salmonella/admin/widgets/*.html']}, url="http://github.com/lincolnloop/django-salmonella/", install_requires=['setuptools'], classifiers=[ 'Development Status :: 4 - Beta1', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
Check for exit code > 0 instead of existence of stderr I'm about to make messages appear in the Sublime plugin. In order to do that, I need a channel to post them that won't mess up the end results being posted to stdout.
import sublime, sublime_plugin, subprocess, os importjs_path = os.path.expanduser('~/.rbenv/shims/import-js') class ImportJsCommand(sublime_plugin.TextCommand): def run(self, edit): entire_file_region = sublime.Region(0, self.view.size()) current_file_contents = self.view.substr(entire_file_region) environment = { 'LC_ALL': 'en_US.UTF-8', 'LC_CTYPE': 'UTF-8', 'LANG': 'en_US.UTF-8' } project_root = self.view.window().extract_variables()['folder'] proc = subprocess.Popen( importjs_path, shell=True, cwd=project_root, env=environment, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) result = proc.communicate(input=current_file_contents.encode('utf-8')) stderr = result[1].decode() if(proc.returncode > 0): sublime.error_message('Error when executing import-js: ' + stderr) return stdout = result[0].decode() self.view.replace(edit, entire_file_region, stdout)
import sublime, sublime_plugin, subprocess, os importjs_path = os.path.expanduser('~/.rbenv/shims/import-js') class ImportJsCommand(sublime_plugin.TextCommand): def run(self, edit): entire_file_region = sublime.Region(0, self.view.size()) current_file_contents = self.view.substr(entire_file_region) environment = { 'LC_ALL': 'en_US.UTF-8', 'LC_CTYPE': 'UTF-8', 'LANG': 'en_US.UTF-8' } project_root = self.view.window().extract_variables()['folder'] proc = subprocess.Popen( importjs_path, shell=True, cwd=project_root, env=environment, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) result = proc.communicate(input=current_file_contents.encode('utf-8')) stderr = result[1].decode() if(len(stderr) > 0): sublime.error_message('Error when executing import-js: ' + stderr) return stdout = result[0].decode() self.view.replace(edit, entire_file_region, stdout)
Improve db relations: - User->UserProfile is One to One - UserProfile <-> Teachers/Websites/EclassLessons are Many to Many
from cronos.teilar.models import Departments, Teachers, EclassLessons, Websites from django.contrib.auth.models import User from django.db import models class UserProfile(models.Model): user = models.OneToOneField(User, primary_key = True, unique = True) dionysos_username = models.CharField(max_length = 15, unique = True) dionysos_password = models.CharField(max_length = 30) eclass_username = models.CharField(max_length = 30, null = True, blank = True) eclass_password = models.CharField(max_length = 30, null = True, blank = True) eclass_lessons = models.ManyToManyField(EclassLessons) introduction_year = models.CharField(max_length = 5) registration_number = models.CharField(max_length = 8) school = models.ForeignKey(Departments) semester = models.CharField(max_length = 2) webmail_username = models.CharField(max_length = 30, null = True, blank = True) webmail_password = models.CharField(max_length = 30, null = True, blank = True) teacher_announcements = models.ManyToManyField(Teachers) other_announcements = models.ManyToManyField(Websites) declaration = models.TextField(null = True, blank = True) grades = models.TextField(null = True, blank = True) def __unicode__(self): return self.user.username
from cronos.teilar.models import Departments from django.contrib.auth.models import User from django.db import models class UserProfile(models.Model): user = models.ForeignKey(User, unique = True) dionysos_username = models.CharField(max_length = 15, unique = True) dionysos_password = models.CharField(max_length = 30) eclass_username = models.CharField(max_length = 30, null = True, blank = True) eclass_password = models.CharField(max_length = 30, null = True, blank = True) eclass_lessons = models.TextField(null = True, blank = True) introduction_year = models.CharField(max_length = 5) registration_number = models.CharField(max_length = 8) school = models.ForeignKey(Departments) semester = models.CharField(max_length = 2) webmail_username = models.CharField(max_length = 30, null = True, blank = True) webmail_password = models.CharField(max_length = 30, null = True, blank = True) teacher_announcements = models.TextField(null = True, blank = True) other_announcements = models.TextField(null = True, blank = True) declaration = models.TextField(null = True, blank = True) grades = models.TextField(null = True, blank = True) def __unicode__(self): return self.user.username
Use consistent CLI command names.
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. from st2client.models import core __all__ = [ 'ActionAlias' ] class ActionAlias(core.Resource): _alias = 'Action-Alias' _display_name = 'Action Alias' _plural = 'ActionAliases' _plural_display_name = 'Runners' _url_path = 'actionalias' _repr_attributes = ['name', 'pack', 'action_ref']
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. from st2client.models import core __all__ = [ 'ActionAlias' ] class ActionAlias(core.Resource): _alias = 'ActionAlias' _display_name = 'Action Alias' _plural = 'ActionAliases' _plural_display_name = 'Runners' _url_path = 'actionalias' _repr_attributes = ['name', 'pack', 'action_ref']
Allow reading and writing from a specified Path
package io.github.likcoras.asuka; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.pircbotx.User; import lombok.Cleanup; public class IgnoreManager { private Set<String> ignored; public IgnoreManager() { ignored = Collections.synchronizedSet(new HashSet<String>()); } public void addIgnored(User user) { addIgnored(BotUtil.getId(user)); } public void addIgnored(String user) { ignored.add(user); } public void removeIgnored(User user) { removeIgnored(BotUtil.getId(user)); } public void removeIgnored(String user) { ignored.remove(user); } public boolean isIgnored(User user) { return ignored.contains(BotUtil.getId(user)); } public void readFile(Path ignoreFile) throws IOException { @Cleanup BufferedReader read = Files.newBufferedReader(ignoreFile); synchronized (ignored) { String line; while ((line = read.readLine()) != null) ignored.add(line); } } public void writeFile(Path ignoreFile) throws IOException { @Cleanup BufferedWriter write = Files.newBufferedWriter(ignoreFile); synchronized (ignored) { for (String user : ignored) write.write(user + "\n"); } write.flush(); } }
package io.github.likcoras.asuka; import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.pircbotx.User; import lombok.Cleanup; public class IgnoreManager { private Set<String> ignored; private Path ignoreFile; public IgnoreManager() { ignored = Collections.synchronizedSet(new HashSet<String>()); ignoreFile = Paths.get("ignore.txt"); } public void addIgnored(User user) { addIgnored(BotUtil.getId(user)); } public void addIgnored(String user) { ignored.add(user); } public void removeIgnored(User user) { removeIgnored(BotUtil.getId(user)); } public void removeIgnored(String user) { ignored.remove(user); } public boolean isIgnored(User user) { return ignored.contains(BotUtil.getId(user)); } public void writeFile() throws IOException { @Cleanup BufferedWriter write = Files.newBufferedWriter(ignoreFile); synchronized(ignored) { for (String user : ignored) write.write(user + "\n"); } write.flush(); } }
Fix inserting the redux stats
import Helmet from 'react-helmet'; export default function buildPage($doc, html, appState) { const { htmlAttributes, ...headChildren } = Helmet.rewind(); const $html = $doc.find('html'); for (const attributeName of Object.keys(htmlAttributes)) { $html.attr(attributeName, htmlAttributes[attributeName]); } const $head = $doc.find('head'); const { title, base, ...appendableTags } = headChildren; replace($head, 'title', title.toString()); replace($head, 'base', base.toString()); // TODO replace meta tags ? for (const tagName of Object.keys(appendableTags)) { const tag = appendableTags[tagName]; $head.append(tag.toString()); } // Insert App HTML $doc.find('#app').append(`<div>${html}</div>`); // Insert Redux State $doc.find('script').last().before(`<script>window.__PRELOADED_STATE__ = ${JSON.stringify(appState)}</script>`); } function replace($head, tagName, newTag) { const tag = $head.find(tagName); if (tag.length > 0) { tag.replaceWith(newTag); } else { $head.append(newTag); } }
import Helmet from 'react-helmet'; export default function buildPage($doc, html, appState) { const { htmlAttributes, ...headChildren } = Helmet.rewind(); const $html = $doc.find('html'); for (const attributeName of Object.keys(htmlAttributes)) { $html.attr(attributeName, htmlAttributes[attributeName]); } const $head = $doc.find('head'); const { title, base, ...appendableTags } = headChildren; replace($head, 'title', title.toString()); replace($head, 'base', base.toString()); // TODO replace meta tags ? for (const tagName of Object.keys(appendableTags)) { const tag = appendableTags[tagName]; $head.append(tag.toString()); } // Insert App HTML $doc.find('#app').append(`<div>${html}</div>`); // Insert Redux State $doc.find('script').last().before(`<script>window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState)}</script>`); } function replace($head, tagName, newTag) { const tag = $head.find(tagName); if (tag.length > 0) { tag.replaceWith(newTag); } else { $head.append(newTag); } }
Add a main function (more support for the api in the legacy virtualenv).
from __future__ import absolute_import, division, print_function from virtualenv.__about__ import ( __author__, __copyright__, __email__, __license__, __summary__, __title__, __uri__, __version__ ) # some support for old api in legacy virtualenv from virtualenv.core import create from virtualenv.__main__ import main # flake8: noqa __all__ = [ "__title__", "__summary__", "__uri__", "__version__", "__author__", "__email__", "__license__", "__copyright__", "create", "create_environment", "main", ] def create_environment( home_dir, site_packages=False, clear=False, unzip_setuptools=False, prompt=None, search_dirs=None, never_download=False, no_setuptools=False, no_pip=False, symlink=True ): # flake8: noqa create( home_dir, system_site_packages=site_packages, clear=clear, prompt=prompt or "", extra_search_dirs=search_dirs, setuptools=not no_setuptools, pip=not no_pip )
from __future__ import absolute_import, division, print_function from virtualenv.__about__ import ( __author__, __copyright__, __email__, __license__, __summary__, __title__, __uri__, __version__ ) from virtualenv.core import create def create_environment( home_dir, site_packages=False, clear=False, unzip_setuptools=False, prompt=None, search_dirs=None, never_download=False, no_setuptools=False, no_pip=False, symlink=True ): create( home_dir, system_site_packages=site_packages, clear=clear, prompt=prompt or "", extra_search_dirs=search_dirs, setuptools=not no_setuptools, pip=not no_pip ) __all__ = [ "__title__", "__summary__", "__uri__", "__version__", "__author__", "__email__", "__license__", "__copyright__", "create", ]
Use private constructor instead of enum to prevent instances
package com.devinci.lib.util; import android.os.Build; /** * Utility methods to check Android version. */ public class Versions { private Versions() { } /** * Checks if the device is at least Marshmallow 6.0 API23. * * @return true if the device is API >= 23, false otherwise */ public static boolean isMarshmallow() { //TODO t.rozbicki 31.08.15 replace with Marshmallow version code return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M; } /** * Checks if the device is at least Lollipop 5.1 API22. * * @return true if the device is API >= 22, false otherwise */ public static boolean isLollipopMR1() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1; } /** * Checks if the device is at least Lollipop 5.0 API21. * * @return true if the device is API >= 21, false otherwise */ public static boolean isLollipop() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP; } }
package com.devinci.lib.util; import android.os.Build; /** * Utility methods to check Android version. */ public enum Versions { ; /** * Checks if the device is at least Marshmallow 6.0 API23. * * @return true if the device is API >= 23, false otherwise */ public static boolean isMarshmallow() { //TODO t.rozbicki 31.08.15 replace with Marshmallow version code return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M; } /** * Checks if the device is at least Lollipop 5.1 API22. * * @return true if the device is API >= 22, false otherwise */ public static boolean isLollipopMR1() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1; } /** * Checks if the device is at least Lollipop 5.0 API21. * * @return true if the device is API >= 21, false otherwise */ public static boolean isLollipop() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP; } }
Change import path in tests to reflect new name Signed-off-by: Kevin Conway <3473c1f185ca03eadc40ad288d84425b54fd7d57@gmail.com>
import os import sys # Modify the sys.path to allow tests to be run without # installing the module. test_path = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(1, test_path + '/../') import require import pytest def test_patch_replaces_and_restores(): i = __import__ require.patch_import() assert i is not __import__ require.unpatch_import() assert i is __import__ def test_require_gets_local(): t1_import_test = require.require('import_test') assert '.pymodules' in repr(t1_import_test) def test_require_uses_module_cache(): t2_import_test = require.require('import_test') t3_import_test = require.require('import_test') assert t2_import_test is t3_import_test def test_require_not_conflict_with_import(): setuptools = require.require('setuptools') import setuptools as setuptools2 assert setuptools2 is not setuptools @pytest.mark.xfail def test_BUG_require_cannot_override_standard_lib(): re2 = require.require('re') assert '.pymodules' in repr(re2)
import os import sys # Modify the sys.path to allow tests to be run without # installing the module. test_path = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(1, test_path + '/../') import pypm import pytest def test_patch_replaces_and_restores(): i = __import__ pypm.patch_import() assert i is not __import__ pypm.unpatch_import() assert i is __import__ def test_require_gets_local(): t1_import_test = pypm.require('import_test') assert '.pymodules' in repr(t1_import_test) def test_require_uses_module_cache(): t2_import_test = pypm.require('import_test') t3_import_test = pypm.require('import_test') assert t2_import_test is t3_import_test def test_require_not_conflict_with_import(): setuptools = pypm.require('setuptools') import setuptools as setuptools2 assert setuptools2 is not setuptools @pytest.mark.xfail def test_BUG_require_cannot_override_standard_lib(): re2 = pypm.require('re') assert '.pymodules' in repr(re2)
Add email field to User model
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var bcrypt = require('bcrypt'); var SALT_WORK_FACTOR = 10; var UserSchema = new Schema({ "email": { type: String, required: true }, "username": { type: String, unique: true, required: true }, "password": { type: String, required: true }, "comments": [{ type: Schema.Types.ObjectId, ref: 'Comment' }], "followers": [{ type: Schema.Types.ObjectId, ref: 'User' }] }); UserSchema.pre('save', function(next) { var user = this; if (!user.isModified('password')) return next(); bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) { if (err) return next(err); bcrypt.hash(user.password, salt, function(err, hash) { if (err) return next(err); user.password = hash; next(); }); }); }); UserSchema.methods.comparePassword = function(candidatePassword, callback) { bcrypt.compare(candidatePassword, this.password, function(err, isMatch) { if (err) return callback(err); callback(null, isMatch); }); }; mongoose.model('User', UserSchema);
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var bcrypt = require('bcrypt'); var SALT_WORK_FACTOR = 10; var UserSchema = new Schema({ "username": { type: String, unique: true, required: true }, "password": { type: String, required: true }, "comments": [{ type: Schema.Types.ObjectId, ref: 'Comment' }], "followers": [{ type: Schema.Types.ObjectId, ref: 'User' }] }); UserSchema.pre('save', function(next) { var user = this; if (!user.isModified('password')) return next(); bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) { if (err) return next(err); bcrypt.hash(user.password, salt, function(err, hash) { if (err) return next(err); user.password = hash; next(); }); }); }); UserSchema.methods.comparePassword = function(candidatePassword, callback) { bcrypt.compare(candidatePassword, this.password, function(err, isMatch) { if (err) return callback(err); callback(null, isMatch); }); }; mongoose.model('User', UserSchema);
Change to use 'shutil.rmtree' instead of 'os.rmdir'
# -*- coding: utf-8 -*- import os import shutil from hycc.util import hycc_main def clean(): for path in os.listdir("tests/resources"): if path not in ["hello.hy", "__init__.py"]: path = os.path.join("tests/resources", path) if os.path.isdir(path): shutil.rmtree(path) else: os.remove(path) def test_build_executable(): hycc_main("tests/resources/hello.hy".split()) assert os.path.exists("tests/resources/hello") clean() def test_shared_library(): hycc_main("tests/resources/hello.hy --shared".split()) from tests.resources.hello import hello assert hello() == "hello" clean()
# -*- coding: utf-8 -*- import os from hycc.util import hycc_main def clean(): for path in os.listdir("tests/resources"): if path not in ["hello.hy", "__init__.py"]: path = os.path.join("tests/resources", path) if os.path.isdir(path): os.rmdir(path) else: os.remove(path) def test_build_executable(): hycc_main("tests/resources/hello.hy".split()) assert os.path.exists("tests/resources/hello") clean() def test_shared_library(): hycc_main("tests/resources/hello.hy --shared".split()) from tests.resources.hello import hello assert hello() == "hello" clean()
Support enabling tsan and ubsan from Xcode UI Xcode won't let you enable ubsan from the UI as it requires a 'Compile Sources' phase with (Objective-)C(++) sources, but if you manually edit the scheme and enable it or equivalently add the phase with a dummy file, enable it from the UI, and then remove the phase, ubsan will work. PiperOrigin-RevId: 196831918
# Copyright 2017 The Tulsi Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Logic to translate Xcode options to Bazel options.""" class BazelOptions(object): """Converts Xcode features into Bazel command line flags.""" def __init__(self, xcode_env): """Creates a new BazelOptions object. Args: xcode_env: A dictionary of Xcode environment variables. Returns: A BazelOptions instance. """ self.xcode_env = xcode_env def bazel_feature_flags(self): """Returns a list of bazel flags for the current Xcode env configuration.""" flags = [] if self.xcode_env.get('ENABLE_ADDRESS_SANITIZER') == 'YES': flags.append('--features=asan') if self.xcode_env.get('ENABLE_THREAD_SANITIZER') == 'YES': flags.append('--features=tsan') if self.xcode_env.get('ENABLE_UNDEFINED_BEHAVIOR_SANITIZER') == 'YES': flags.append('--features=ubsan') return flags
# Copyright 2017 The Tulsi Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Logic to translate Xcode options to Bazel options.""" class BazelOptions(object): """Converts Xcode features into Bazel command line flags.""" def __init__(self, xcode_env): """Creates a new BazelOptions object. Args: xcode_env: A dictionary of Xcode environment variables. Returns: A BazelOptions instance. """ self.xcode_env = xcode_env def bazel_feature_flags(self): """Returns a list of bazel flags for the current Xcode env configuration.""" flags = [] if self.xcode_env.get('ENABLE_ADDRESS_SANITIZER') == 'YES': flags.extend([ '--features=asan', ]) return flags
Update minimum supported browser versions
/** * Copyright (c) 2017 * Thomas Müller <thomas.mueller@tmit.eu> * * This file is licensed under the Affero General Public License version 3 or later. * See the COPYING-README file. */ $(document).ready(function() { // You can Customize here window.$buoop = { vs: { i: 10, f: 54, o: 0, s: 9, c: 60 }, reminder: 0, // after how many hours should the message reappear test: false, // true = always show the bar (for testing) newwindow: true, // open link in new window/tab url: null, // the url to go to after clicking the notification noclose:true // Do not show the "ignore" button to close the notification }; var path = OC.filePath('core','vendor','browser-update/browser-update.js'); $.getScript(path); });
/** * Copyright (c) 2017 * Thomas Müller <thomas.mueller@tmit.eu> * * This file is licensed under the Affero General Public License version 3 or later. * See the COPYING-README file. */ $(document).ready(function() { // You can Customize here window.$buoop = { vs: { i: 10, f: 45, o: 0, s: 8, c: 45 }, reminder: 0, // after how many hours should the message reappear test: false, // true = always show the bar (for testing) newwindow: true, // open link in new window/tab url: null, // the url to go to after clicking the notification noclose:true // Do not show the "ignore" button to close the notification }; var path = OC.filePath('core','vendor','browser-update/browser-update.js'); $.getScript(path); });
Remove sensitive information from the example
# -*-coding:utf8 -*- import json import requests import time import uuid import datetime import time ids = ["18576635456", "13512345432"] url1 = "http://127.0.0.1:8059/federation/1.0/inference" for i in range(2): request_data_tmp = { "head": { "serviceId": "test_model_service", "applyId": "209090900991", }, "body": { "featureData": { "phone_num": ids[i], }, "sendToRemoteFeatureData": { "device_type": "imei", "phone_num": ids[i], "encrypt_type": "raw" } } } headers = {"Content-Type": "application/json"} response = requests.post(url1, json=request_data_tmp, headers=headers) print("url地址:", url1) print("请求信息:\n", request_data_tmp) print() print("响应信息:\n", response.text) print() #time.sleep(0.1)
# -*-coding:utf8 -*- import json import requests import time import uuid import datetime import time ids = ["18576635456", "13512345432"] url1 = "http://172.16.153.71:8059/federation/1.0/inference" for i in range(2): request_data_tmp = { "head": { "serviceId": "test_model_service", "applyId": "209090900991", }, "body": { "featureData": { "phone_num": ids[i], }, "sendToRemoteFeatureData": { "device_type": "imei", "phone_num": ids[i], "encrypt_type": "raw" } } } headers = {"Content-Type": "application/json"} response = requests.post(url1, json=request_data_tmp, headers=headers) print("url地址:", url1) print("请求信息:\n", request_data_tmp) print() print("响应信息:\n", response.text) print() #time.sleep(0.1)
Rename param to be consistent
import Command from './Command.js'; /** * Table Command */ export default class TableCommand extends Command { /** * @inheritDoc */ execute() { const figure = this.editor.document.createElement('figure'); const table = this.editor.document.createElement('table'); const figcaption = this.editor.document.createElement('figcaption'); figure.classList.add('table'); figure.appendChild(table); figure.appendChild(figcaption); ['thead', 'tbody', 'tfoot'].forEach(section => { const item = this.editor.document.createElement(section); const tr = this.editor.document.createElement('tr'); table.appendChild(item); item.appendChild(tr); for (let i = 0; i < 2; ++i) { let cell = this.editor.document.createElement(section === 'thead' ? 'th' : 'td'); tr.appendChild(cell); } }); this.editor.insert(figure); } }
import Command from './Command.js'; /** * Table Command */ export default class TableCommand extends Command { /** * @inheritDoc */ execute() { const figure = this.editor.document.createElement('figure'); const table = this.editor.document.createElement('table'); const figcaption = this.editor.document.createElement('figcaption'); figure.classList.add('table'); figure.appendChild(table); figure.appendChild(figcaption); ['thead', 'tbody', 'tfoot'].forEach(part => { const item = this.editor.document.createElement(part); const tr = this.editor.document.createElement('tr'); table.appendChild(item); item.appendChild(tr); for (let i = 0; i < 2; ++i) { let cell = this.editor.document.createElement(part === 'thead' ? 'th' : 'td'); tr.appendChild(cell); } }); this.editor.insert(figure); } }
Use the basic mixin object directly
/** @class <p>A basic filter score function, which mathces a filter and applies a weight.</p> @name ejs.FilterScoreFunction @ejs scorefunction @borrows ejs.ScoreFunctionMixin.filter as filter @borrows ejs.ScoreFunctionMixin.weight as weight @borrows ejs.ScoreFunctionMixin._type as _type @borrows ejs.ScoreFunctionMixin.toJSON as toJSON @desc <p>Randomly score documents.</p> */ ejs.FilterScoreFunction = function (filter, weight) { var _common = ejs.ScoreFunctionMixin(); if (filter == null || weight == null) { throw new Error("Filter and weight is required"); } _common.filter(filter); _common.weight(weight); return _common; };
/** @class <p>A basic filter score function, which mathces a filter and applies a weight.</p> @name ejs.FilterScoreFunction @ejs scorefunction @borrows ejs.ScoreFunctionMixin.filter as filter @borrows ejs.ScoreFunctionMixin.weight as weight @borrows ejs.ScoreFunctionMixin._type as _type @borrows ejs.ScoreFunctionMixin.toJSON as toJSON @desc <p>Randomly score documents.</p> */ ejs.FilterScoreFunction = function (filter, weight) { var _common = ejs.ScoreFunctionMixin(), func = _common.toJSON(); if ((filter == null || !isFilter(filter)) || weight == null) { throw new Error("filter must be a Filter and weight must be a Number"); } func.filter = filter; func.weight = weight; return extend(_common, {}); };
[python] Mark get_test_binary as not being a test get_test_binary is a helper method, not a test, make sure nosetests doesn't pick it up as a test. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@153173 91177308-0d34-0410-b5e6-96231b3b80d8
import os.path import unittest POSSIBLE_TEST_BINARIES = [ 'libreadline.so.5', 'libreadline.so.6', ] POSSIBLE_TEST_BINARY_PATHS = [ '/lib', '/usr/lib', '/usr/local/lib', ] class TestBase(unittest.TestCase): def get_test_binary(self): """Helper to obtain a test binary for object file testing. FIXME Support additional, highly-likely targets or create one ourselves. """ for d in POSSIBLE_TEST_BINARY_PATHS: for lib in POSSIBLE_TEST_BINARIES: path = os.path.join(d, lib) if os.path.exists(path): return path raise Exception('No suitable test binaries available!') get_test_binary.__test__ = False
import os.path import unittest POSSIBLE_TEST_BINARIES = [ 'libreadline.so.5', 'libreadline.so.6', ] POSSIBLE_TEST_BINARY_PATHS = [ '/lib', '/usr/lib', '/usr/local/lib', ] class TestBase(unittest.TestCase): def get_test_binary(self): """Helper to obtain a test binary for object file testing. FIXME Support additional, highly-likely targets or create one ourselves. """ for d in POSSIBLE_TEST_BINARY_PATHS: for lib in POSSIBLE_TEST_BINARIES: path = os.path.join(d, lib) if os.path.exists(path): return path raise Exception('No suitable test binaries available!')
Change PolygonSet to not inherit from array.
var clipper = require('../lib/clipper'); var SCALE = 100; var PolygonSet = function(polygons) { this.polygons = polygons; }; PolygonSet.prototype.constructor = PolygonSet; // Merges the polygons in the polygon set. PolygonSet.prototype.merge = function() { var cpr = new clipper.Clipper(), solutionPaths = []; var subjectPaths = this.polygons.map(function(polygon) { var path = polygon.map(function(vertex) { return {X: vertex[0], Y: vertex[1]}; }); clipper.JS.ScaleUpPath(path, SCALE); return path; }); cpr.AddPaths(subjectPaths, clipper.PolyType.ptSubject, true); cpr.Execute(clipper.ClipType.ctUnion, solutionPaths, clipper.PolyFillType.pftNonZero, clipper.PolyFillType.pftNonZero); return solutionPaths.map(function(path) { clipper.JS.ScaleDownPath(path, SCALE); return path.map(function(point) { return [point.X, point.Y]; }); })[0]; }; module.exports = PolygonSet;
var clipper = require('../lib/clipper'); var SCALE = 100; var PolygonSet = function(polygons) { polygons.__proto__ = PolygonSet.prototype; return polygons; }; PolygonSet.prototype = []; // Merges the polygons in the polygon set. PolygonSet.prototype.merge = function() { var cpr = new clipper.Clipper(), solutionPaths = []; var subjectPaths = this.map(function(polygon) { var path = polygon.map(function(vertex) { return {X: vertex[0], Y: vertex[1]}; }); clipper.JS.ScaleUpPath(path, SCALE); return path; }); cpr.AddPaths(subjectPaths, clipper.PolyType.ptSubject, true); cpr.Execute(clipper.ClipType.ctUnion, solutionPaths, clipper.PolyFillType.pftNonZero, clipper.PolyFillType.pftNonZero); return solutionPaths.map(function(path) { clipper.JS.ScaleDownPath(path, SCALE); return path.map(function(point) { return [point.X, point.Y]; }); })[0]; }; module.exports = PolygonSet;
Remove problematic not tool from the equation toolbar; \not is used in conjunction with other commands such as \equiv or \infty. Mathquill however does not support this and changes \not to \neg.
module.exports = [ { action: '\\sqrt', label: '\\sqrt{X}' }, { action: '^', label: 'x^{X}' }, { action: '\\frac', label: '\\frac{X}{X}' }, { action: '\\int', label: '\\int_{X}^{X}' }, { action: '\\lim_', label: '\\lim_{X}' }, { action: '\\overrightarrow', label: '\\overrightarrow{X}' }, { action: '_', label: 'x_X' }, { action: '\\nthroot', label: '\\sqrt[X]{X}' }, { action: '\\sum', label: '\\sum_{X}^{X}' }, { action: '\\binom', label: '\\binom{X}{X}' }, { action: '\\sin' }, { action: '\\cos' }, { action: '\\tan' }, { action: '\\arcsin' }, { action: '\\arccos' }, { action: '\\arctan' }, { action: '\\vec', label: '\\vec{X}' }, { action: '\\bar', label: '\\bar{X}' }, { action: '\\underline', label: '\\underline{X}' }, { action: '\\overleftarrow', label: '\\overleftarrow{X}' }, { action: '|', label: '|X|'}, { action: '(', label: '(X)'} ]
module.exports = [ { action: '\\sqrt', label: '\\sqrt{X}' }, { action: '^', label: 'x^{X}' }, { action: '\\frac', label: '\\frac{X}{X}' }, { action: '\\int', label: '\\int_{X}^{X}' }, { action: '\\lim_', label: '\\lim_{X}' }, { action: '\\overrightarrow', label: '\\overrightarrow{X}' }, { action: '_', label: 'x_X' }, { action: '\\nthroot', label: '\\sqrt[X]{X}' }, { action: '\\sum', label: '\\sum_{X}^{X}' }, { action: '\\binom', label: '\\binom{X}{X}' }, { action: '\\sin' }, { action: '\\cos' }, { action: '\\tan' }, { action: '\\arcsin' }, { action: '\\arccos' }, { action: '\\arctan' }, { action: '\\not' }, { action: '\\vec', label: '\\vec{X}' }, { action: '\\bar', label: '\\bar{X}' }, { action: '\\underline', label: '\\underline{X}' }, { action: '\\overleftarrow', label: '\\overleftarrow{X}' }, { action: '|', label: '|X|'}, { action: '(', label: '(X)'} ]
Add tangled to dev requirements Although `tangled.web[dev]` is already in the dev requirements and `tangled.web`'s dev requirememts include `tangled[dev]`, it seems that `tangled`'s dev requirements aren't being pulled in via `tangled.web`. Not sure if this intentional on the part of pip/setuptools or what.
from setuptools import setup setup( name='tangled.mako', version='0.1a4.dev0', description='Tangled Mako integration', long_description=open('README.rst').read(), url='http://tangledframework.org/', download_url='https://github.com/TangledWeb/tangled.mako/tags', author='Wyatt Baldwin', author_email='self@wyattbaldwin.com', include_package_data=True, packages=[ 'tangled', 'tangled.mako', 'tangled.mako.tests', ], install_requires=[ 'tangled.web>=0.1a10', 'Mako>=1.0', ], extras_require={ 'dev': [ 'tangled[dev]>=0.1a9', 'tangled.web[dev]>=0.1a10', ], }, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], )
from setuptools import setup setup( name='tangled.mako', version='0.1a4.dev0', description='Tangled Mako integration', long_description=open('README.rst').read(), url='http://tangledframework.org/', download_url='https://github.com/TangledWeb/tangled.mako/tags', author='Wyatt Baldwin', author_email='self@wyattbaldwin.com', include_package_data=True, packages=[ 'tangled', 'tangled.mako', 'tangled.mako.tests', ], install_requires=[ 'tangled.web>=0.1a10', 'Mako>=1.0', ], extras_require={ 'dev': [ 'tangled.web[dev]>=0.1a10', ], }, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], )
Fix location updates in controller
const mongoose = require('mongoose') const Store = mongoose.model('Store') exports.addStore = (req, res) => res.render('edit', { title: 'Add Store' }) exports.createStore = async (req, res) => { const store = await (new Store(req.body)).save() req.flash('success', `Successfully created ${store.name}. Please leave a review!`) res.redirect(`/store/${store.slug}`) } exports.getStores = async (req, res) => res.render('stores', { title: 'Stores', stores: await Store.find() }) exports.editStore = async (req, res) => { const store = await Store.findOne({ _id: req.params.id }) // TODO: confirm they are the owner of the store res.render('edit', { title: `Edit ${store.name}`, store }) } exports.updateStore = async (req, res) => { req.body.location.type = 'Point' // fix location updates const store = await Store.findOneAndUpdate( { _id: req.params.id }, req.body, { new: true, runValidators: true } ).exec() req.flash('success', `Successfully updated <strong>${store.name}</strong>! <a href="/stores/${store.slug}">View Store</a>`) res.redirect(`/stores/${store._id}/edit`) }
const mongoose = require('mongoose') const Store = mongoose.model('Store') exports.addStore = (req, res) => res.render('edit', { title: 'Add Store' }) exports.createStore = async (req, res) => { const store = await (new Store(req.body)).save() req.flash('success', `Successfully created ${store.name}. Please leave a review!`) res.redirect(`/store/${store.slug}`) } exports.getStores = async (req, res) => res.render('stores', { title: 'Stores', stores: await Store.find() }) exports.editStore = async (req, res) => { const store = await Store.findOne({ _id: req.params.id }) // TODO: confirm they are the owner of the store res.render('edit', { title: `Edit ${store.name}`, store }) } exports.updateStore = async (req, res) => { const store = await Store.findOneAndUpdate( { _id: req.params.id }, req.body, { new: true, runValidators: true } ).exec() req.flash('success', `Successfully updated <strong>${store.name}</strong>! <a href="/stores/${store.slug}">View Store</a>`) res.redirect(`/stores/${store._id}/edit`) }
Remove versioning from URL scheme
"""uclapi URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^dashboard/', include('dashboard.urls')), url(r'^roombookings/', include('roombookings.urls')), ]
"""uclapi URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^dashboard/', include('dashboard.urls')), url(r'^v0/roombookings/', include('roombookings.urls')), ]