text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add debug access to webpack modules.
import { ErrorPage } from './ErrorPage'; import { LoginPage } from './LoginPage'; import { App } from './actions'; import { Root } from './router'; (function () { if (!history.pushState) { return; // see old.js } if (typeof __webpack_require__ !== 'undefined') { Votr.webpackRequire = __webpack_require__; } var query = Votr.settings.destination; if (query !== undefined && (query == '' || query.substring(0, 1) == '?')) { try { history.replaceState(null, '', Votr.settings.url_root + query); } catch (e) { console.error(e); } } Votr.setDebug = function (enabled) { document.cookie = enabled ? 'votr_debug=true' : 'votr_debug='; location.reload(); } var root = Votr.settings.servers ? <LoginPage /> : Votr.settings.error ? <ErrorPage /> : <Root app={App} />; Votr.appRoot = React.render(root, document.getElementById('votr')); })();
import { ErrorPage } from './ErrorPage'; import { LoginPage } from './LoginPage'; import { App } from './actions'; import { Root } from './router'; (function () { if (!history.pushState) { return; // see old.js } var query = Votr.settings.destination; if (query !== undefined && (query == '' || query.substring(0, 1) == '?')) { try { history.replaceState(null, '', Votr.settings.url_root + query); } catch (e) { console.error(e); } } Votr.setDebug = function (enabled) { document.cookie = enabled ? 'votr_debug=true' : 'votr_debug='; location.reload(); } var root = Votr.settings.servers ? <LoginPage /> : Votr.settings.error ? <ErrorPage /> : <Root app={App} />; Votr.appRoot = React.render(root, document.getElementById('votr')); })();
Store empty queries in history
package fr.neamar.kiss.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; class DB extends SQLiteOpenHelper { private final static int DB_VERSION = 1; private final static String DB_NAME = "kiss.s3db"; public DB(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase database) { database.execSQL("CREATE TABLE history ( _id INTEGER PRIMARY KEY AUTOINCREMENT, query TEXT, record TEXT NOT NULL)"); } @Override public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) { // See // http://www.drdobbs.com/database/using-sqlite-on-android/232900584 } }
package fr.neamar.kiss.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; class DB extends SQLiteOpenHelper { private final static int DB_VERSION = 1; private final static String DB_NAME = "summon.s3db"; public DB(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase database) { database.execSQL("CREATE TABLE history ( _id INTEGER PRIMARY KEY AUTOINCREMENT, query TEXT NOT NULL, record TEXT NOT NULL)"); } @Override public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) { // See // http://www.drdobbs.com/database/using-sqlite-on-android/232900584 } }
Revert "Use BlobBuilder (supported by Chrome for Android)" This reverts commit 844d4d4410b9fd73cb49a01ab1c975c3bb84d017.
// Based on http://www.html5rocks.com/en/tutorials/workers/basics/ define(function() { var URL = window.URL || window.webkitURL if (URL && Worker && Blob) { var blobUrl = URL.createObjectURL(new Blob( ['self.onmessage = function(event) { setInterval(function() { self.postMessage({}) }, event.data.interval) }'], {type: 'text/javascript'} )) return function(callback, interval) { var worker = new Worker(blobUrl) worker.addEventListener('message', callback) worker.postMessage({interval: interval}) } } console.warn("Worker or Blob not available, falling back to setInterval()") return setInterval })
// Based on http://www.html5rocks.com/en/tutorials/workers/basics/ define(function() { var URL = window.URL || window.webkitURL // BlobBuilder is deprecated but Chrome for Android fails with an "Illegal constructor" // instantiating the Blob directly var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder if (URL && Worker && Blob && BlobBuilder) { var blobBuilder = new BlobBuilder blobBuilder.append('self.onmessage = function(event) { setInterval(function() { self.postMessage({}) }, event.data.interval) }') var blob = blobBuilder.getBlob('text/javascript') var blobUrl = URL.createObjectURL(blob) return function(callback, interval) { var worker = new Worker(blobUrl) worker.addEventListener('message', callback) worker.postMessage({interval: interval}) } } console.warn("Worker or Blob not available, falling back to setInterval()") return setInterval })
Add dot product function to math module.
// Math Library for ISAAC Physics. // addVector function. // Takes in two vectors, returns a new vector made by adding // the inputs together. If the two input vectors don't have the same // length, the first input vector will be returned. function addVector (vectorA, vectorB) { if(vectorA.length === vectorB.length) { var newVector = new Array(); for(position in vectorA) { newVector[position] = vectorA[position] + vectorB[position]; } return newVector; } else { return vectorA; } } // scaleVector function. // Takes in a vector and a scalar, returns a new vector made by // multiplying the scalar through the vector. function scaleVector (vector, scalar) { var newVector = new Array(); for(position in vector) { newVector[position] = vector[position] * scalar; } return newVector; } // subtractVector function. // Takes in two vectors, returns a new vector made by subtracting the // second vector from the first. If the two input vectors don't have the same // length, the first input vector will be returned. function subtractVector (vectorA, vectorB) { return addVector(vectorA, scaleVector(vectorB, -1)); } // dotProduct function. // Takes in two vectors, returns the dot product of the two. If the two input vectors // don't have the same length, -1 will be returned. function dotProduct (vectorA, vectorB) { if(vectorA.length === vectorB.length) { var sum = 0; for (position in vectorA) { sum += vectorA[position] * vectorB[position]; } return sum; } else { return -1; } }
// Math Library for ISAAC Physics. // addVector function. // Takes in two vectors, returns a new vector made by adding // the inputs together. If the two input vectors don't have the same // length, the first input vector will be returned. function addVector (vectorA, vectorB) { if(vectorA.length === vectorB.length) { var newVector = new Array(); for(position in vectorA) { newVector[position] = vectorA[position] + vectorB[position]; } return newVector; } else { return vectorA; } } // scaleVector function. // Takes in a vector and a scalar, returns a new vector made by // multiplying the scalar through the vector. function scaleVector (vector, scalar) { var newVector = new Array(); for(position in vector) { newVector[position] = vector[position] * scalar; } return newVector; } // subtractVector function. // Takes in two vectors, returns a new vector made by subtracting the // second vector from the first. If the two input vectors don't have the same // length, the first input vector will be returned. function subtractVector (vectorA, vectorB) { return addVector(vectorA, scaleVector(vectorB, -1)); }
Fix dependencies with new package ldap3 Old package 'python3_ldap' is now called 'ldap3'. And 'python3_ldap' version 0.9.5.3 is no more available on pypi
from setuptools import setup, find_packages from django_python3_ldap import __version__ version_str = ".".join(str(n) for n in __version__) setup( name = "django-python3-ldap", version = version_str, license = "BSD", description = "Django LDAP user authentication backend for Python 3.", author = "Dave Hall", author_email = "dave@etianen.com", url = "https://github.com/etianen/django-python3-ldap", packages = find_packages(), install_requires = [ "django>=1.7", "ldap3==0.9.8.2", ], classifiers = [ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Framework :: Django", ], )
from setuptools import setup, find_packages from django_python3_ldap import __version__ version_str = ".".join(str(n) for n in __version__) setup( name = "django-python3-ldap", version = version_str, license = "BSD", description = "Django LDAP user authentication backend for Python 3.", author = "Dave Hall", author_email = "dave@etianen.com", url = "https://github.com/etianen/django-python3-ldap", packages = find_packages(), install_requires = [ "django>=1.7", "python3-ldap==0.9.5.3", ], classifiers = [ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Framework :: Django", ], )
Chore: Remove unused function from the form deletion feature
$(function(){ let elements = $('.vich-image, .cropper'); if(!elements.length) return; $.get('/wearejust/sonata_theme/delete_dialog', (html) => { elements.each(function(index,item){ new imageRemove($(item), html); }); }); }); class imageRemove { constructor(item, html) { this.item = item; this.dialog = $(html); this.checkbox = this.item.find('input[type="checkbox"]'); this.item.append(this.dialog); this.checkbox.on('change', this.change.bind(this)); this.item.find('.js-delete-cancel').on('click', this.cancel.bind(this)); } change() { this.item.find('input, img, .checkbox, .cropper-local').toggleClass('accessibility'); this.dialog.toggleClass('is-active'); } cancel(e) { e.preventDefault(); this.change(); this.checkbox.attr('checked', false); } }
$(function(){ let elements = $('.vich-image, .cropper'); if(!elements.length) return; $.get('/wearejust/sonata_theme/delete_dialog', (html) => { elements.each(function(index,item){ new imageRemove($(item), html); }); }); }); class imageRemove { constructor(item, html) { this.item = item; this.dialog = $(html); this.checkbox = this.item.find('input[type="checkbox"]'); this.item.append(this.dialog); this.checkbox.on('change', this.change.bind(this)); this.item.find('.js-delete-cancel').on('click', this.cancel.bind(this)); } change() { this.item.find('input, img, .checkbox, .cropper-local').toggleClass('accessibility'); this.dialog.toggleClass('is-active'); } remove(e) { e.preventDefault(); } cancel(e) { e.preventDefault(); this.change(); this.checkbox.attr('checked', false); } }
Add log to check sound
const player = require('play-sound')( opts = {} ); const Random = require('random-js'); const sounds_path = './node_modules/kaamelott-soundboard'; const sound_connect = []; const sounds_start = [ 'en_garde_espece_de_vieille_pute_degarnie', 'en_garde_ma_mignone', ]; const sounds_win = [ 'putain_il_est_fort_ce_con', 'wooouuuhouhouhou_c_est_mortel' ]; const sounds_winless = [ 'petite_pucelle', 'sortez-est_vous_les_doigts_du_cul' ]; const get_random_sound = (songs = []) => { if (songs.length !== 0) { const index = Random.integer(0,songs.length); return songs[index]; } return null; }; const play_sound = (sound) => { console.log('playing', sound); player.play(`${sounds_path}/${sound}.mp3`, err => { if(err) console.error(err); }); }; const play = (sounds) => { play_sound(get_random_sound(sounds)); }; module.exports = { connect: () => { }, start: () => { play(sounds_start); }, win: (winner, score) => { play(sounds_win); }, winless: () => { play(sounds_winless); } };
const player = require('play-sound')( opts = {} ); const Random = require('random-js'); const sounds_path = './node_modules/kaamelott-soundboard'; const sound_connect = []; const sounds_start = [ 'en_garde_espece_de_vieille_pute_degarnie', 'en_garde_ma_mignone', ]; const sounds_win = [ 'putain_il_est_fort_ce_con', 'wooouuuhouhouhou_c_est_mortel' ]; const sounds_winless = [ 'petite_pucelle', 'sortez-est_vous_les_doigts_du_cul' ]; const get_random_sound = (songs = []) => { if (songs.length !== 0) { const index = Random.integer(0,songs.length); return songs[index]; } return null; }; const play_sound = (sound) => { player.play(`${sounds_path}/${sound}.mp3`, err => { if(err) console.error(err); }); }; const play = (sounds) => { play_sound(get_random_sound(sounds)); }; module.exports = { connect: () => { }, start: () => { play(sounds_start); }, win: (winner, score) => { play(sounds_win); }, winless: () => { play(sounds_winless); } };
Add -h and -v option
package main import ( "fmt" "os" "os/exec" "strings" ) var version = "0.1.0" var helpMsg = `NAME: ext - An interface for command extensions USAGE: ext commands... ` func main() { if len(os.Args) < 2 { fmt.Println(helpMsg) os.Exit(1) } switch os.Args[1] { case "-h", "--help": fmt.Println(helpMsg) os.Exit(0) case "-v", "--version": fmt.Println(version) os.Exit(0) } extArgs, err := LookupExtCmd(os.Args[1:]) if err != nil { fmt.Println(err) } extCmd := exec.Command(extArgs[0], extArgs[1:]...) extCmd.Stdin = os.Stdin extCmd.Stdout = os.Stdout extCmd.Stderr = os.Stderr extCmd.Run() } func LookupExtCmd(args []string) ([]string, error) { var err error for i := len(args); i > 0; i-- { extCmd := strings.Join(args[0:i], "-") bin, err := exec.LookPath(extCmd) if err == nil { extArgs := []string{bin} extArgs = append(extArgs, args[i:]...) return extArgs, nil } } return nil, err }
package main import ( "fmt" "os" "os/exec" "strings" ) func main() { extArgs, err := LookupExtCmd(os.Args[1:]) if err != nil { fmt.Println(err) } extCmd := exec.Command(extArgs[0], extArgs[1:]...) extCmd.Stdin = os.Stdin extCmd.Stdout = os.Stdout extCmd.Stderr = os.Stderr extCmd.Run() } func LookupExtCmd(args []string) ([]string, error) { var err error for i := len(args); i > 0; i-- { extCmd := strings.Join(args[0:i], "-") bin, err := exec.LookPath(extCmd) if err == nil { extArgs := []string{bin} extArgs = append(extArgs, args[i:]...) return extArgs, nil } } return nil, err }
Add GET request for page with form to add new emoticon
const express = require('express'), router = express.Router({mergeParams: true}), db = require('../models'); router.get('/', function(req, res, next) { db.Emoticon.find({}).then(function(emoticons) { res.render('emoticons/index', {emoticons}); }).catch(function(err) { console.log(err); }); }); router.get('/new', function(req, res, next) { res.render('emoticons/new', {user: req.params.username}); }); router.post('/collection/add', function(req, res, next) { Emoticon.create(req.body.emoticon, function(err, newEmoticon) { if (err) { res.render('error'); } else { res.redirect('/collection'); } }); }); router.delete('/collection/:id', function(req, res, next) { }); module.exports = router;
const express = require('express'), router = express.Router({mergeParams: true}), db = require('../models'); router.get('/', function(req, res, next) { db.Emoticon.find({}).then(function(emoticons) { res.render('emoticons/index', {emoticons}); }).catch(function(err) { console.log(err); }); }); router.get('/collection', function(req, res, next) { Emoticon.find({}, function(err, emoticons) { if (err) { console.log('Error'); } else { res.render('index', {emoticons}); } }); }); router.post('/collection/add', function(req, res, next) { Emoticon.create(req.body.emoticon, function(err, newEmoticon) { if (err) { res.render('error'); } else { res.redirect('/collection'); } }); }); router.delete('/collection/:id', function(req, res, next) { }); module.exports = router;
Use new temporary access token for testing.
package com.uwetrottmann.getglue; import junit.framework.TestCase; import org.apache.oltu.oauth2.common.exception.OAuthProblemException; import org.apache.oltu.oauth2.common.exception.OAuthSystemException; import java.io.IOException; public abstract class BaseTestCase extends TestCase { protected static final String CLIENT_ID = "7FD930E5C9D030F696ACA631343EB3"; protected static final String CLIENT_SECRET = "EB4B93F673B95A5A2460CF983BB0A4"; private static final String TEMPORARY_ACCESS_TOKEN = "B341108A36B7499839648979D4739E"; /* Expires Feb. 20, 2014, 10:20 a.m. */ protected static final String REDIRECT_URI = "http://localhost"; private final GetGlue mManager = new GetGlue(); @Override protected void setUp() throws OAuthSystemException, IOException, OAuthProblemException { getManager().setIsDebug(true); getManager().setAccessToken(TEMPORARY_ACCESS_TOKEN); } protected final GetGlue getManager() { return mManager; } }
package com.uwetrottmann.getglue; import junit.framework.TestCase; import org.apache.oltu.oauth2.common.exception.OAuthProblemException; import org.apache.oltu.oauth2.common.exception.OAuthSystemException; import java.io.IOException; public abstract class BaseTestCase extends TestCase { protected static final String CLIENT_ID = "7FD930E5C9D030F696ACA631343EB3"; protected static final String CLIENT_SECRET = "EB4B93F673B95A5A2460CF983BB0A4"; private static final String TEMPORARY_ACCESS_TOKEN = "FA1429A2D4B3FA39EF57E15689A6B4"; /* Expires Dec. 21, 2013, 8:35 a.m. */ protected static final String REDIRECT_URI = "http://localhost"; private final GetGlue mManager = new GetGlue(); @Override protected void setUp() throws OAuthSystemException, IOException, OAuthProblemException { getManager().setIsDebug(true); getManager().setAccessToken(TEMPORARY_ACCESS_TOKEN); } protected final GetGlue getManager() { return mManager; } }
Move template directory string to constant
<?php namespace BNETDocs\Libraries; use \BNETDocs\Libraries\Exceptions\TemplateNotFoundException; use \BNETDocs\Libraries\Logger; use \SplObjectStorage; final class Template { const TEMPLATE_DIR = "/templates"; protected $additional_css; protected $context; protected $opengraph; protected $template; public function __construct(&$context, $template) { $this->additional_css = []; $this->opengraph = new SplObjectStorage(); $this->setContext($context); $this->setTemplate($template); } public function getContext() { return $this->context; } public function getTemplate() { return $this->template; } public function render() { $cwd = getcwd(); try { chdir($cwd . self::TEMPLATE_DIR); if (!file_exists($this->template)) { throw new TemplateNotFoundException($this); } require($this->template); } finally { chdir($cwd); } } public function setContext(&$context) { $this->context = $context; } public function setTemplate($template) { $this->template = "./" . $template . ".phtml"; Logger::logMetric("template", $template); } }
<?php namespace BNETDocs\Libraries; use \BNETDocs\Libraries\Exceptions\TemplateNotFoundException; use \BNETDocs\Libraries\Logger; use \SplObjectStorage; final class Template { protected $additional_css; protected $context; protected $opengraph; protected $template; public function __construct(&$context, $template) { $this->additional_css = []; $this->opengraph = new SplObjectStorage(); $this->setContext($context); $this->setTemplate($template); } public function getContext() { return $this->context; } public function getTemplate() { return $this->template; } public function render() { $cwd = getcwd(); try { chdir($cwd . "/templates"); if (!file_exists($this->template)) { throw new TemplateNotFoundException($this); } require($this->template); } finally { chdir($cwd); } } public function setContext(&$context) { $this->context = $context; } public function setTemplate($template) { $this->template = "./" . $template . ".phtml"; Logger::logMetric("template", $template); } }
Fix mob trigger infinite recursion
package com.elmakers.mine.bukkit.magic; import javax.annotation.Nonnull; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Creature; import org.bukkit.entity.Entity; import com.elmakers.mine.bukkit.api.magic.Mage; import com.elmakers.mine.bukkit.api.magic.MageController; public class MobTrigger extends CustomTrigger { boolean requiresTarget = false; public MobTrigger(@Nonnull MageController controller, @Nonnull String key, @Nonnull ConfigurationSection configuration) { super(controller, key, configuration); requiresTarget = configuration.getBoolean("requires_target"); } @Override public boolean isValid(Mage mage) { if (!super.isValid(mage)) return false; if (requiresTarget) { Entity entity = mage.getEntity(); if (entity instanceof Creature) { return ((Creature)entity).getTarget() != null; } } return true; } }
package com.elmakers.mine.bukkit.magic; import javax.annotation.Nonnull; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Creature; import org.bukkit.entity.Entity; import com.elmakers.mine.bukkit.api.magic.Mage; import com.elmakers.mine.bukkit.api.magic.MageController; public class MobTrigger extends CustomTrigger { boolean requiresTarget = false; public MobTrigger(@Nonnull MageController controller, @Nonnull String key, @Nonnull ConfigurationSection configuration) { super(controller, key, configuration); requiresTarget = configuration.getBoolean("requires_target"); } public boolean isValid(Mage mage) { if (!isValid(mage)) return false; if (requiresTarget) { Entity entity = mage.getEntity(); if (entity instanceof Creature) { return ((Creature)entity).getTarget() != null; } } return true; } }
Add an exception to throw when a document does have the expected structure
"""Extensions of standard exceptions for PyWXSB events. Yeah, I'd love this module to be named exceptions.py, but it can't because the standard library has one of those, and we need to reference it below. """ import exceptions class PyWXSBException (exceptions.Exception): """Base class for exceptions that indicate a problem that the user should fix.""" pass class SchemaValidationError (PyWXSBException): """Raised when the XML hierarchy does not appear to be valid for an XML schema.""" pass class BadTypeValueError (PyWXSBException): """Raised when a value in an XML attribute does not conform to the simple type.""" pass class NotInNamespaceError (PyWXSBException): '''Raised when a name is referenced that is not defined in the appropriate namespace.''' __namespace = None __ncName = None class BadPropertyError (PyWXSBException): """Raised when a schema component property is accessed on a component instance that does not define that property.""" pass class BadDocumentError (PyWXSBException): """Raised when processing document content and an error is encountered.""" pass class PyWXSBError (exceptions.Exception): """Base class for exceptions that indicate a problem that the user probably can't fix.""" pass class LogicError (PyWXSBError): """Raised when the code detects an implementation problem.""" class IncompleteImplementationError (LogicError): """Raised when a code branch is taken that has not yet been implemented."""
"""Extensions of standard exceptions for PyWXSB events. Yeah, I'd love this module to be named exceptions.py, but it can't because the standard library has one of those, and we need to reference it below. """ import exceptions class PyWXSBException (exceptions.Exception): """Base class for exceptions that indicate a problem that the user should fix.""" pass class SchemaValidationError (PyWXSBException): """Raised when the XML hierarchy does not appear to be valid for an XML schema.""" pass class BadTypeValueError (PyWXSBException): """Raised when a value in an XML attribute does not conform to the simple type.""" pass class NotInNamespaceError (PyWXSBException): '''Raised when a name is referenced that is not defined in the appropriate namespace.''' __namespace = None __ncName = None class BadPropertyError (PyWXSBException): """Raised when a schema component property is accessed on a component instance that does not define that property.""" pass class PyWXSBError (exceptions.Exception): """Base class for exceptions that indicate a problem that the user probably can't fix.""" pass class LogicError (PyWXSBError): """Raised when the code detects an implementation problem.""" class IncompleteImplementationError (LogicError): """Raised when a code branch is taken that has not yet been implemented."""
Add a verbose error reporting on Travis
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function from xml.etree.ElementTree import ParseError import xml.etree.ElementTree as ET import glob import sys def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def parse(): for infile in glob.glob('*.xml'): try: tree = ET.parse(infile) root = tree.getroot() if root.findall('.//FatalError'): element=root.findall('.//FatalError')[0] eprint("Error detected") print(infile) print(element.text) sys.exit(1) except ParseError: eprint("The file xml isn't correct. There were some mistakes in the tests ") sys.exit(1) def main(): parse() if __name__ == '__main__': main()
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function from xml.etree.ElementTree import ParseError import xml.etree.ElementTree as ET import glob import sys def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def parse(): for infile in glob.glob('*.xml'): try: tree = ET.parse(infile) root = tree.getroot() if root.findall('.//FatalError'): eprint("Error detected") print(infile) sys.exit(1) except ParseError: eprint("The file xml isn't correct. There were some mistakes in the tests ") sys.exit(1) def main(): parse() if __name__ == '__main__': main()
Update settings example for tpl directories and other stuff
import os PROJECT_DIR = os.path.abspath(os.path.dirname(__file__)) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', } } TIME_ZONE = 'Europe/Paris' LANGUAGE_CODE = 'en-us' # Make this unique, and don't share it with anybody. SECRET_KEY = 'DO-SOMETHING-FOR-FRAKS-SAKE' MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media') STATICFILES_DIRS = ( os.path.join(PROJECT_DIR, 'static'), ) TEMPLATE_DIRS = ( os.path.join(PROJECT_DIR, 'templates'), )
DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', } } TIME_ZONE = 'Europe/Paris' LANGUAGE_CODE = 'en-us' # Make this unique, and don't share it with anybody. SECRET_KEY = 'DO-SOMETHING-FOR-FRAKS-SAKE' MEDIA_ROOT = '/usr/local/www/LIIT/media' STATICFILES_DIRS = ( '/usr/local/www/LIIT/static', ) TEMPLATE_DIRS = ( '/usr/local/www/LIIT/templates', )
Change github url in WebView
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.tb.sundtektvinput; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.webkit.WebViewClient; /** * Fragment that shows a web page for Sample TV Input introduction. */ public class MainFragment extends Fragment { private static final String URL = "https://github.com/tam1m/androidtv-sample-inputs"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.main_fragment, null); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); WebView webView = (WebView) getView(); webView.setWebViewClient(new WebViewClient()); webView.loadUrl(URL); } }
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.tb.sundtektvinput; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.webkit.WebViewClient; /** * Fragment that shows a web page for Sample TV Input introduction. */ public class MainFragment extends Fragment { private static final String URL = "http://github.com/googlesamples/androidtv-sample-inputs/blob/master/README.md"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.main_fragment, null); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); WebView webView = (WebView) getView(); webView.setWebViewClient(new WebViewClient()); webView.loadUrl(URL); } }
Complete test for heading IDs
var mock = require('./mock'); describe('Page', function() { var book; before(function() { return mock.setupDefaultBook({ 'heading.md': '# Hello\n\n## World' }) .then(function(_book) { book = _book; return book.summary.load(); }); }); it('should add a default ID to headings', function() { var page = book.addPage('heading.md'); return page.parse() .then(function() { page.content.should.be.html({ 'h1#hello': { count: 1 }, 'h2#world': { count: 1 } }); }); }); });
var mock = require('./mock'); describe('Page', function() { var book; before(function() { return mock.setupDefaultBook({ 'heading.md': '# Hello\n\n## World' }) .then(function(_book) { book = _book; return book.summary.load(); }); }); it.only('should add a default ID to headings', function() { var page = book.addPage('heading.md'); return page.parse() .then(function() { console.log(page.content); }); }); });
Adjust test_person_made_works to keep consistency.
def test_team_has_members(fx_people, fx_teams): assert fx_teams.clamp.members == { fx_people.clamp_member_1, fx_people.clamp_member_2, fx_people.clamp_member_3, fx_people.clamp_member_4 } def test_person_has_awards(fx_people, fx_awards): assert fx_people.peter_jackson.awards == { fx_awards.hugo_award, fx_awards.nebula_award } def test_person_made_works(fx_people, fx_works): assert fx_people.clamp_member_1.credits == { fx_works.skura_member_asso_1 }
def test_team_has_members(fx_people, fx_teams): assert fx_teams.clamp.members == { fx_people.clamp_member_1, fx_people.clamp_member_2, fx_people.clamp_member_3, fx_people.clamp_member_4 } def test_person_has_awards(fx_people, fx_awards): assert fx_people.peter_jackson.awards == { fx_awards.hugo_award, fx_awards.nebula_award } def test_person_made_works(fx_people, fx_works): assert len(fx_people.clamp_member_1.credits) == 1 for asso in fx_people.clamp_member_1.credits: assert asso.person == fx_people.clamp_member_1 assert asso.work == fx_works.cardcaptor_sakura assert asso.role == 'Artist'
Use posixpath for paths in the cloud. Fixes build break on Windows. R=borenet@google.com Review URL: https://codereview.chromium.org/18074002 git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@9792 2bbb7eff-a529-9590-31e7-b0007b416f81
#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Download the image files needed to run skimage tool. """ from build_step import BuildStep from utils import gs_utils from utils import sync_bucket_subdir import posixpath import sys class DownloadSKImageFiles(BuildStep): def __init__(self, timeout=12800, no_output_timeout=9600, **kwargs): super (DownloadSKImageFiles, self).__init__( timeout=timeout, no_output_timeout=no_output_timeout, **kwargs) def _DownloadSKImagesFromStorage(self): """Copies over image files from Google Storage if the timestamps differ.""" dest_gsbase = (self._args.get('dest_gsbase') or sync_bucket_subdir.DEFAULT_PERFDATA_GS_BASE) print '\n\n========Downloading image files from Google Storage========\n\n' gs_relative_dir = posixpath.join('skimage', 'input') gs_utils.DownloadDirectoryContentsIfChanged( gs_base=dest_gsbase, gs_relative_dir=gs_relative_dir, local_dir=self._skimage_in_dir) def _Run(self): # Locally copy image files from GoogleStorage. self._DownloadSKImagesFromStorage() if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(DownloadSKImageFiles))
#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Download the image files needed to run skimage tool. """ from build_step import BuildStep from utils import gs_utils from utils import sync_bucket_subdir import os import sys class DownloadSKImageFiles(BuildStep): def __init__(self, timeout=12800, no_output_timeout=9600, **kwargs): super (DownloadSKImageFiles, self).__init__( timeout=timeout, no_output_timeout=no_output_timeout, **kwargs) def _DownloadSKImagesFromStorage(self): """Copies over image files from Google Storage if the timestamps differ.""" dest_gsbase = (self._args.get('dest_gsbase') or sync_bucket_subdir.DEFAULT_PERFDATA_GS_BASE) print '\n\n========Downloading image files from Google Storage========\n\n' gs_relative_dir = os.path.join('skimage', 'input') gs_utils.DownloadDirectoryContentsIfChanged( gs_base=dest_gsbase, gs_relative_dir=gs_relative_dir, local_dir=self._skimage_in_dir) def _Run(self): # Locally copy image files from GoogleStorage. self._DownloadSKImagesFromStorage() if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(DownloadSKImageFiles))
Add not equals test for version function
import shutil import tempfile from os import path import unittest from libs.qpanel.upgrader import __first_line as firstline, get_current_version class UpgradeTestClass(unittest.TestCase): def setUp(self): # Create a temporary directory self.test_dir = tempfile.mkdtemp() def tearDown(self): # Remove the directory after the test shutil.rmtree(self.test_dir) def test_first_line(self): content = 'a\n\b\t\b' self.assertEqual(firstline(content), 'a') self.assertNotEqual(firstline(content), 'ab') def test_version(self): version = '0.10' version_file = path.join(self.test_dir, 'VERSION') f = open(version_file, 'w') f.write(version) f.close() self.assertEqual(get_current_version(version_file), version) self.assertNotEqual(get_current_version(version_file), '0.11.0') # runs the unit tests if __name__ == '__main__': unittest.main()
import shutil import tempfile from os import path import unittest from libs.qpanel.upgrader import __first_line as firstline, get_current_version class UpgradeTestClass(unittest.TestCase): def setUp(self): # Create a temporary directory self.test_dir = tempfile.mkdtemp() def tearDown(self): # Remove the directory after the test shutil.rmtree(self.test_dir) def test_first_line(self): content = 'a\n\b\t\b' self.assertEqual(firstline(content), 'a') self.assertNotEqual(firstline(content), 'ab') def test_version(self): version = '0.10' version_file = path.join(self.test_dir, 'VERSION') f = open(version_file, 'w') f.write(version) f.close() self.assertEqual(get_current_version(version_file), version) # runs the unit tests if __name__ == '__main__': unittest.main()
Update Speed 'out of range or invalid' error
var HyperdeckCore = require("./hyperdeck-core.js"); var Hyperdeck = function(ip) { //Start by connecting to Hyperdeck via HypderdeckCore var Core = new HyperdeckCore(ip); Core.makeRequest("notify: remote: true"); Core.makeRequest("notify: transport: true"); Core.makeRequest("notify: slot: true"); Core.makeRequest("notify: configuration: true"); //Publicise functions from Core this.getNotifier = Core.getNotifier(); this.makeRequest = Core.makeRequest(); this.onConnected = Core.onConnected(); //make Easy Access commands this.play = function(speed) { var commandString; if (Math.abs(speed) <= 1600) { commandString = "play speed: " + speed; } else { if (speed) { throw new Error("Speed value invalid or out of range"); } else { commandString = "play"; } } return Core.makeRequest(commandString); }; this.stop = function() { return Core.makeRequest("stop"); }; this.record = function() { return Core.makeRequest("record"); }; this.goTo = function(timecode) { return Core.makeRequest("goto: timecode: " + timecode); }; }; module.exports = Hyperdeck;
var HyperdeckCore = require("./hyperdeck-core.js"); var Hyperdeck = function(ip) { //Start by connecting to Hyperdeck via HypderdeckCore var Core = new HyperdeckCore(ip); Core.makeRequest("notify: remote: true"); Core.makeRequest("notify: transport: true"); Core.makeRequest("notify: slot: true"); Core.makeRequest("notify: configuration: true"); //Publicise functions from Core this.getNotifier = Core.getNotifier(); this.makeRequest = Core.makeRequest(); this.onConnected = Core.onConnected(); //make Easy Access commands this.play = function(speed) { var commandString; if (Math.abs(speed) <= 1600) { commandString = "play speed: " + speed; } else { if (speed) { throw "Speed out of range"; } else { commandString = "play"; } } return Core.makeRequest(commandString); }; this.stop = function() { return Core.makeRequest("stop"); }; this.record = function() { return Core.makeRequest("record"); }; this.goTo = function(timecode) { return Core.makeRequest("goto: timecode: " + timecode); }; }; module.exports = Hyperdeck;
Remove toLowerCase so that the env var doesn't need to be set
const winston = require('winston'); const winstonError = require('winston-error'); const levels = { levels: { error: 0, warn: 1, info: 2, verbose: 3, debug: 4, silly: 5, database: 6, }, }; const consoleLogger = new (winston.Logger)({ levels: levels.levels }); if (process.env.NODE_ENV !== 'test') { consoleLogger.add(winston.transports.Console, { level: process.env.SDF_LOGLEVEL || 'database', exitOnError: false, handleExceptions: true, humanReadableUnhandledException: true, timestamp: true, colorize: process.env.SDF_COLORIZE_LOGS === 'true', }); } if (process.env.SDF_CATCH_UNHANDLED_REJECTIONS === 'true' && process.env.NODE_ENV !== 'test') { consoleLogger.info('Catching unhandled rejections.'); process.on('unhandledRejection', msg => consoleLogger.warn('Caught unhandled rejection:', msg)); } winstonError(consoleLogger); module.exports = consoleLogger;
const winston = require('winston'); const winstonError = require('winston-error'); const levels = { levels: { error: 0, warn: 1, info: 2, verbose: 3, debug: 4, silly: 5, database: 6, }, }; const consoleLogger = new (winston.Logger)({ levels: levels.levels }); if (process.env.NODE_ENV !== 'test') { consoleLogger.add(winston.transports.Console, { level: process.env.SDF_LOGLEVEL || 'database', exitOnError: false, handleExceptions: true, humanReadableUnhandledException: true, timestamp: true, colorize: process.env.SDF_COLORIZE_LOGS.toLowerCase() === 'true', }); } if (process.env.SDF_CATCH_UNHANDLED_REJECTIONS === 'true' && process.env.NODE_ENV !== 'test') { consoleLogger.info('Catching unhandled rejections.'); process.on('unhandledRejection', msg => consoleLogger.warn('Caught unhandled rejection:', msg)); } winstonError(consoleLogger); module.exports = consoleLogger;
Add support for relativedelta timespecs This uses the django-relativedeltafield formatter. We could copy the formatter into here but that's not great either. This can be improved once we have a pluggable JSON serializer.
import json import datetime from uuid import UUID from django.http import HttpResponse from .exceptions import BinderRequestError try: from dateutil.relativedelta import relativedelta from relativedeltafield import format_relativedelta except ImportError: class relativedelta: pass class BinderJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime.datetime): # FIXME: was .isoformat(), but that omits the microseconds if they # are 0, which upsets our front-end devs. This is ugly. # I hear .isoformat() might learn a timespec parameter in 3.6... tz = obj.strftime("%z") tz = tz if tz else '+0000' return obj.strftime("%Y-%m-%dT%H:%M:%S.%f") + tz elif isinstance(obj, datetime.date): return obj.isoformat() elif isinstance(obj, UUID): return str(obj) # Standard string notation elif isinstance(obj, set): return list(obj) elif isinstance(obj, relativedelta): return format_relativedelta(obj) return json.JSONEncoder.default(self, obj) def jsondumps(o, indent=None): return json.dumps(o, cls=BinderJSONEncoder, indent=indent) def jsonloads(data): try: return json.loads(data.decode()) except ValueError as e: raise BinderRequestError('JSON parse error: {}.'.format(str(e))) def JsonResponse(data): return HttpResponse(jsondumps(data), content_type='application/json')
import json import datetime from uuid import UUID from django.http import HttpResponse from .exceptions import BinderRequestError class BinderJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime.datetime): # FIXME: was .isoformat(), but that omits the microseconds if they # are 0, which upsets our front-end devs. This is ugly. # I hear .isoformat() might learn a timespec parameter in 3.6... tz = obj.strftime("%z") tz = tz if tz else '+0000' return obj.strftime("%Y-%m-%dT%H:%M:%S.%f") + tz elif isinstance(obj, datetime.date): return obj.isoformat() elif isinstance(obj, UUID): return str(obj) # Standard string notation elif isinstance(obj, set): return list(obj) return json.JSONEncoder.default(self, obj) def jsondumps(o, indent=None): return json.dumps(o, cls=BinderJSONEncoder, indent=indent) def jsonloads(data): try: return json.loads(data.decode()) except ValueError as e: raise BinderRequestError('JSON parse error: {}.'.format(str(e))) def JsonResponse(data): return HttpResponse(jsondumps(data), content_type='application/json')
Make sure the fetch date is only returned as date if there's a date
<?php namespace App\Model; use Carbon\Carbon; use Illuminate\Database\Eloquent\Model; class Endpoint extends Model { protected $fillable = [ 'url', 'name', 'description', ]; protected $casts = [ 'system' => 'array', ]; protected $dates = [ 'endpoint_fetched', ]; protected $hidden = [ 'id', 'created_at', 'updated_at', 'endpoint_fetched', ]; protected $appends = [ 'fetched' ]; public function bodies() { return $this->hasMany(EndpointBody::class, 'endpoint_id', 'id'); } public function getFetchedAttribute() { /** @var Carbon $fetched */ $fetched = $this->endpoint_fetched; if (!is_null($fetched)) { return $fetched->toIso8601String(); } return null; } }
<?php namespace App\Model; use Carbon\Carbon; use Illuminate\Database\Eloquent\Model; class Endpoint extends Model { protected $fillable = [ 'url', 'name', 'description', ]; protected $casts = [ 'system' => 'array', ]; protected $dates = [ 'endpoint_fetched', ]; protected $hidden = [ 'id', 'created_at', 'updated_at', 'endpoint_fetched', ]; protected $appends = [ 'fetched', ]; public function bodies() { return $this->hasMany(EndpointBody::class, 'endpoint_id', 'id'); } public function getFetchedAttribute() { /** @var Carbon $fetched */ $fetched = $this->endpoint_fetched; return $fetched->toIso8601String(); } }
Update stable builders to pull from 1.4 branch Review URL: https://codereview.chromium.org/295923003 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@271609 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.4', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.3', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
Fix bug for template controller
<?php namespace Butterfly\Plugin\TemplateRouter; use Butterfly\Adapter\Twig\IRenderer; use Butterfly\Component\DI\Container; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; /** * @author Marat Fakhertdinov <marat.fakhertdinov@gmail.com> */ class TemplateController { /** * @var IRenderer */ protected $render; /** * @var Container */ protected $container; /** * @param IRenderer $render * @param Container $container */ public function __construct(IRenderer $render, Container $container) { $this->container = $container; $this->render = $render; } /** * @param Request $request * @return string */ public function indexAction(Request $request) { $template = $request->attributes->get('template'); $parameters = array( 'container' => $this->container, 'data' => $this->container->getParameter('bfy_plugin.template_router.data_source'), 'request' => $request, ); $content = $this->render->render($template, $parameters); return new Response($content); } }
<?php namespace Butterfly\Plugin\TemplateRouter; use Butterfly\Adapter\Twig\IRenderer; use Butterfly\Component\DI\Container; use Symfony\Component\HttpFoundation\Request; /** * @author Marat Fakhertdinov <marat.fakhertdinov@gmail.com> */ class TemplateController { /** * @var IRenderer */ protected $render; /** * @var Container */ protected $container; /** * @param IRenderer $render * @param Container $container */ public function __construct(IRenderer $render, Container $container) { $this->container = $container; $this->render = $render; } /** * @param Request $request * @return string */ public function indexAction(Request $request) { $template = $request->attributes->get('template'); $parameters = array( 'container' => $this->container, 'data' => $this->container->getParameter('bfy_plugin.template_router.data_source'), 'request' => $request, ); return $this->render->render($template, $parameters); } }
Change "Development Status" to beta
from setuptools import setup import numpy from numpy.distutils.core import Extension import railgun from railgun import __author__, __version__, __license__ setup( name='railgun', version=__version__, packages=['railgun'], description=('ctypes utilities for faster and easier ' 'simulation programming in C and Python'), long_description=railgun.__doc__, author=__author__, author_email='aka.tkf@gmail.com', url='http://bitbucket.org/tkf/railgun/src', keywords='numerical simulation, research, ctypes, numpy, c', license=__license__, classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Science/Research", "Intended Audience :: Developers", "Operating System :: POSIX :: Linux", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Topic :: Scientific/Engineering", ], include_dirs = [numpy.get_include()], ext_modules=[ Extension( 'railgun.cstyle', sources=['src/cstylemodule.c'], extra_compile_args=["-fPIC", "-Wall"], ), ], )
from setuptools import setup import numpy from numpy.distutils.core import Extension import railgun from railgun import __author__, __version__, __license__ setup( name='railgun', version=__version__, packages=['railgun'], description=('ctypes utilities for faster and easier ' 'simulation programming in C and Python'), long_description=railgun.__doc__, author=__author__, author_email='aka.tkf@gmail.com', url='http://bitbucket.org/tkf/railgun/src', keywords='numerical simulation, research, ctypes, numpy, c', license=__license__, classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Science/Research", "Intended Audience :: Developers", "Operating System :: POSIX :: Linux", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Topic :: Scientific/Engineering", ], include_dirs = [numpy.get_include()], ext_modules=[ Extension( 'railgun.cstyle', sources=['src/cstylemodule.c'], extra_compile_args=["-fPIC", "-Wall"], ), ], )
Allow querysets to be jsonified
from datetime import timedelta from django.core.serializers.json import DjangoJSONEncoder from django.db.models.query import ValuesQuerySet from django.views.decorators.cache import cache_page from django.views.generic import View from django.http import JsonResponse, HttpResponse from django.conf import settings class DjangoJSONEncoder2(DjangoJSONEncoder): """A json encoder to deal with the python objects we may want to encode""" def default(self, obj): if isinstance(obj, timedelta): ARGS = ('days', 'seconds', 'microseconds') return {'__type__': 'datetime.timedelta', 'args': [getattr(obj, a) for a in ARGS]} if isinstance(obj, ValuesQuerySet): return [item for item in obj] return DjangoJSONEncoder.default(self, obj) class JsonView(View): """Quickly serve a python data structure as json""" cache_timeout = 5 * 60 * 60 * 24 def get_cache_timeout(self): return self.cache_timeout def dispatch(self, *args, **kwargs): def _dispatch(request, *args, **kwargs): context = self.get_context_data(**kwargs) return self.render_to_response(context) return cache_page(self.get_cache_timeout())(_dispatch)(*args, **kwargs) def render_to_response(self, context, **kwargs): return JsonResponse(context, encoder=DjangoJSONEncoder2)
from django.core.serializers.json import DjangoJSONEncoder from django.views.decorators.cache import cache_page from django.views.generic import View from django.http import JsonResponse, HttpResponse from django.conf import settings class DjangoJSONEncoder2(DjangoJSONEncoder): """A json encoder to deal with the python objects we may want to encode""" def default(self, obj): if isinstance(obj, timedelta): ARGS = ('days', 'seconds', 'microseconds') return {'__type__': 'datetime.timedelta', 'args': [getattr(obj, a) for a in ARGS]} return DjangoJSONEncoder.default(self, obj) class JsonView(View): """Quickly serve a python data structure as json""" cache_timeout = 5 * 60 * 60 * 24 def get_cache_timeout(self): return self.cache_timeout def dispatch(self, *args, **kwargs): def _dispatch(request, *args, **kwargs): context = self.get_context_data(**kwargs) return self.render_to_response(context) return cache_page(self.get_cache_timeout())(_dispatch)(*args, **kwargs) def render_to_response(self, context, **kwargs): return JsonResponse(context, encoder=DjangoJSONEncoder2)
TST: Update import location of TestPluginBase
# ---------------------------------------------------------------------------- # Copyright (c) 2016--, Ben Kaehler # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ---------------------------------------------------------------------------- import tempfile import shutil from qiime.plugin.testing import TestPluginBase class FeatureClassifierTestPluginBase(TestPluginBase): def setUp(self): try: from q2_feature_classifier.plugin_setup import plugin except ImportError: self.fail("Could not import plugin object.") self.plugin = plugin self.temp_dir = tempfile.TemporaryDirectory( prefix='q2-feature-classifier-test-temp-') def _setup_dir(self, filenames, dirfmt): for filename in filenames: filepath = self.get_data_path(filename) shutil.copy(filepath, self.temp_dir.name) return dirfmt(self.temp_dir.name, mode='r')
# ---------------------------------------------------------------------------- # Copyright (c) 2016--, Ben Kaehler # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ---------------------------------------------------------------------------- import tempfile import shutil from q2_types.testing import TestPluginBase class FeatureClassifierTestPluginBase(TestPluginBase): def setUp(self): try: from q2_feature_classifier.plugin_setup import plugin except ImportError: self.fail("Could not import plugin object.") self.plugin = plugin self.temp_dir = tempfile.TemporaryDirectory( prefix='q2-feature-classifier-test-temp-') def _setup_dir(self, filenames, dirfmt): for filename in filenames: filepath = self.get_data_path(filename) shutil.copy(filepath, self.temp_dir.name) return dirfmt(self.temp_dir.name, mode='r')
Improve alterItems: better null-check for the returned value
const errors = require('@feathersjs/errors'); const getItems = require('./get-items'); const replaceItems = require('./replace-items'); module.exports = function (func) { if (!func) { func = () => {}; } if (typeof func !== 'function') { throw new errors.BadRequest('Function required. (alter)'); } return context => { let items = getItems(context); const isArray = Array.isArray(items); (isArray ? items : [items]).forEach( (item, index) => { const result = func(item, context); if (typeof result === 'object' && result !== null) { if (isArray) { items[index] = result; } else { items = result; } } } ); const isDone = replaceItems(context, items); if (!isDone || typeof isDone.then !== 'function') { return context; } return isDone.then(() => context); }; };
const errors = require('@feathersjs/errors'); const getItems = require('./get-items'); const replaceItems = require('./replace-items'); module.exports = function (func) { if (!func) { func = () => {}; } if (typeof func !== 'function') { throw new errors.BadRequest('Function required. (alter)'); } return context => { let items = getItems(context); const isArray = Array.isArray(items); (isArray ? items : [items]).forEach( (item, index) => { const result = func(item, context); if (result != null) { if (isArray) { items[index] = result; } else { items = result; } } } ); const isDone = replaceItems(context, items); if (!isDone || typeof isDone.then !== 'function') { return context; } return isDone.then(() => context); }; };
Update README and fix typos
from setuptools import setup setup(name='mordecai', version='2.0.0a2', description='Full text geoparsing and event geocoding', url='http://github.com/openeventdata/mordecai/', author='Andy Halterman', author_email='ahalterman0@gmail.com', license='MIT', packages=['mordecai'], keywords = ['geoparsing', 'nlp', 'geocoding', 'toponym resolution'], include_package_data=True, package_data = {'data': ['admin1CodesASCII.json', 'countries.json', 'nat_df.csv', 'stopword_country_names.json'], 'models' : ['country_model.h5', 'rank_model.h5']} )
from setuptools import setup setup(name='mordecai', version='2.0.0a1', description='Full text geoparsing and event geocoding', url='http://github.com/openeventdata/mordecai/', author='Andy Halterman', author_email='ahalterman0@gmail.com', license='MIT', packages=['mordecai'], keywords = ['geoparsing', 'nlp', 'geocoding', 'toponym resolution'], include_package_data=True, package_data = {'data': ['admin1CodesASCII.json', 'countries.json', 'nat_df.csv', 'stopword_country_names.json'], 'models' : ['country_model.h5', 'rank_model.h5']} )
Set accepted status when successfully published.
package main import ( "net/http" "log" ) func Index(w http.ResponseWriter, r *http.Request) { body := NewRequest(r).GetBody() if config.FastPublish { if len(body) > 0 { servicesQueue.Publish(body) } return } service, err := NewService(body) response := NewResponse(w) if err != nil { response.Body.Error = true response.Body.Message = err.Error() response.Status = http.StatusUnprocessableEntity log.Printf(err.Error()) } else { err := validate.Struct(service) if err == nil { servicesQueue.Publish(body) response.Body.Message = http.StatusText(http.StatusAccepted) response.Status = http.StatusAccepted log.Printf("Accepted: %s", string(body)) } else { response.Body.Error = true response.Body.Message = err.Error() response.Status = http.StatusBadRequest log.Printf(err.Error()) } } response.Write() }
package main import ( "net/http" "log" ) func Index(w http.ResponseWriter, r *http.Request) { body := NewRequest(r).GetBody() if config.FastPublish { if len(body) > 0 { servicesQueue.Publish(body) } return } service, err := NewService(body) response := NewResponse(w) if err != nil { response.Body.Error = true response.Body.Message = err.Error() response.Status = http.StatusUnprocessableEntity log.Printf(err.Error()) } else { err := validate.Struct(service) if err == nil { servicesQueue.Publish(body) response.Body.Message = "Success" response.Status = http.StatusCreated log.Printf("Received: %s", string(body)) } else { response.Body.Error = true response.Body.Message = err.Error() response.Status = http.StatusBadRequest log.Printf(err.Error()) } } response.Write() }
Java: Move away from deprecated HTTP client API after libraries update.
package org.certificatetransparency.ctlog.comm; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import java.io.IOException; /** * Simple delegator to HttpClient, so it can be mocked */ public class HttpPostInvoker { /** * Make an HTTP POST method call to the given URL with the provided JSON payload. * @param url URL for POST method * @param jsonPayload Serialized JSON payload. * @return Server's response body. */ public String makePostRequest(String url, String jsonPayload) { try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { HttpPost post = new HttpPost(url); post.setEntity(new StringEntity(jsonPayload, "utf-8")); post.addHeader("Content-Type", "application/json; charset=utf-8"); return httpClient.execute(post, new BasicResponseHandler()); } catch (IOException e) { throw new LogCommunicationException("Error making POST request to " + url, e); } } }
package org.certificatetransparency.ctlog.comm; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import java.io.IOException; /** * Simple delegator to HttpClient, so it can be mocked */ public class HttpPostInvoker { /** * Make an HTTP POST method call to the given URL with the provided JSON payload. * @param url URL for POST method * @param jsonPayload Serialized JSON payload. * @return Server's response body. */ public String makePostRequest(String url, String jsonPayload) { HttpClient httpClient = new DefaultHttpClient(); try { HttpPost post = new HttpPost(url); post.setEntity(new StringEntity(jsonPayload, "utf-8")); post.addHeader("Content-Type", "application/json; charset=utf-8"); return httpClient.execute(post, new BasicResponseHandler()); } catch (IOException e) { throw new LogCommunicationException("Error making POST request to " + url, e); } finally { httpClient.getConnectionManager().shutdown(); } } }
[AC-9046] Add another constraint for the url
# Generated by Django 2.2.10 on 2021-11-05 12:29 from django.db import migrations from django.db.models.query_utils import Q def update_url_to_community(apps, schema_editor): people_url = ["/people", "/people"] mentor_url = "/directory" mentor_refinement_url = "/directory/?refinementList%5Bhome_program_family%5D%5B0%5D=Israel" community_url = "/community" community_refinement_url = "/community/?refinementList%5Bprogram_family_names%5D%5B0%5D=Israel" SiteRedirectPage = apps.get_model('accelerator', 'SiteRedirectPage') SiteRedirectPage.objects.filter( Q(new_url__in=people_url) | Q(new_url=mentor_url) ).update(new_url=community_url) if mentor_refinement_url: SiteRedirectPage.objects.filter( mentor_refinement_url ).update(community_refinement_url) class Migration(migrations.Migration): dependencies = [ ('accelerator', '0073_auto_20210909_1706'), ] operations = [ migrations.RunPython(update_url_to_community, migrations.RunPython.noop) ]
# Generated by Django 2.2.10 on 2021-11-05 12:29 from django.db import migrations from django.db.models.query_utils import Q def update_url_to_community(apps, schema_editor): people_url = "/people" mentor_url = "/directory" community_url = "/community" SiteRedirectPage = apps.get_model('accelerator', 'SiteRedirectPage') SiteRedirectPage.objects.filter( Q(new_url=people_url) | Q(new_url=mentor_url) ).update(new_url=community_url) class Migration(migrations.Migration): dependencies = [ ('accelerator', '0073_auto_20210909_1706'), ] operations = [ migrations.RunPython(update_url_to_community, migrations.RunPython.noop) ]
Fix coloring of earthquakes above sea level (blue -> red) [#130153315]
export const TRANSITION_TIME = 750 export function depthToColor(depth) { // Depth can be negative (earthquake above the sea level) - use 0-100km range color in this case. const depthRange = Math.max(0, Math.floor(depth / 100)) switch(depthRange) { case 0: // above the sea level or 0 - 100 return 0xFF0A00 case 1: // 100 - 200 return 0xFF7A00 case 2: // 200 - 300 return 0xFFF700 case 3: // 300 - 400 return 0x56AB00 case 4: // 400 - 500 return 0x00603F default: // > 500 return 0x0021BC } } export function magnitudeToRadius(magnitude) { return 0.9 * Math.pow(1.5, (magnitude - 1)) } // Generated using: // http://www.timotheegroleau.com/Flash/experiments/easing_function_generator.htm export function easeOutBounce(t) { let ts = t * t let tc = ts * t return 33 * tc * ts + -106 * ts * ts + 126 * tc + -67 * ts + 15 * t }
export const TRANSITION_TIME = 750 export function depthToColor(depth) { const depthRange = Math.floor(depth / 100) switch(depthRange) { case 0: // 0 - 100 return 0xFF0A00 case 1: // 100 - 200 return 0xFF7A00 case 2: // 200 - 300 return 0xFFF700 case 3: // 300 - 400 return 0x56AB00 case 4: // 400 - 500 return 0x00603F default: // > 500 return 0x0021BC } } export function magnitudeToRadius(magnitude) { return 0.9 * Math.pow(1.5, (magnitude - 1)) } // Generated using: // http://www.timotheegroleau.com/Flash/experiments/easing_function_generator.htm export function easeOutBounce(t) { let ts = t * t let tc = ts * t return 33 * tc * ts + -106 * ts * ts + 126 * tc + -67 * ts + 15 * t }
Add classifier for Python 3.3
#!/usr/bin/env python3 import sys from distutils.core import setup setup( name='pathlib', version=open('VERSION.txt').read().strip(), py_modules=['pathlib'], license='MIT License', description='Object-oriented filesystem paths', long_description=open('README.txt').read(), author='Antoine Pitrou', author_email='solipsis@pitrou.net', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Topic :: Software Development :: Libraries', 'Topic :: System :: Filesystems', ], download_url='https://pypi.python.org/pypi/pathlib/', url='http://readthedocs.org/docs/pathlib/', )
#!/usr/bin/env python3 import sys from distutils.core import setup setup( name='pathlib', version=open('VERSION.txt').read().strip(), py_modules=['pathlib'], license='MIT License', description='Object-oriented filesystem paths', long_description=open('README.txt').read(), author='Antoine Pitrou', author_email='solipsis@pitrou.net', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Topic :: Software Development :: Libraries', 'Topic :: System :: Filesystems', ], download_url='https://pypi.python.org/pypi/pathlib/', url='http://readthedocs.org/docs/pathlib/', )
Disable row rendering for embedded field sets.
<?php class FieldSetRenderer extends Renderer { use RenderableFields; public function __construct($field, $parent = null, $params = array()) { parent::__construct($field, $parent, $params); $this->setParam("row", false); } public function render() { return $this->getParam("tag") ? $this->tag( "fieldset", $this->renderLegend() . $this->renderErrors($this) . $this->renderFields(), $this->fieldParams() ) : $this->renderErrors($this) . $this->renderFields(); } protected function renderLegend() { return $this->getParam("legend") ? $this->tag("legend", $this->getParam("legend")) : ""; } }
<?php class FieldSetRenderer extends Renderer { use RenderableFields; public function render() { return $this->getParam("tag") ? $this->tag( "fieldset", $this->renderLegend() . $this->renderErrors($this) . $this->renderFields(), $this->fieldParams() ) : $this->renderErrors($this) . $this->renderFields(); } protected function renderLegend() { return $this->getParam("legend") ? $this->tag("legend", $this->getParam("legend")) : ""; } }
Return sample categories from API
<?php namespace Villermen\Soundboard\Model; use \JsonSerializable; class Sample implements JsonSerializable { protected $file; protected $name; protected $mtime; protected $categories; public function __construct($file, $mtime) { $this->file = $file; $this->mtime = $mtime; // Conjure a name out of the filename. $name = substr($this->file, strrpos($this->file, '/') + 1); $dotPosition = strrpos($name, '.'); if ($dotPosition) { $name = substr($name, 0, $dotPosition); } // Replace trailing numbers, to allow files to obtain the same name. $this->name = preg_replace('/([^\d])\d{0,2}$/', '\1', $name); // Create categories for each of the relative directories. $this->categories = array_slice(explode('/', $this->file), 1, -1); } public function jsonSerialize() { return [ 'file' => $this->file, 'name' => $this->name, 'id' => hash('crc32', $this->name), 'mtime' => $this->mtime, 'categories' => $this->categories ]; } }
<?php namespace Villermen\Soundboard\Model; use \JsonSerializable; class Sample implements JsonSerializable { protected $file; protected $name; protected $mtime; public function __construct($file, $mtime) { $this->file = $file; $this->mtime = $mtime; // Conjure a name out of the filename. $name = substr($this->file, strrpos($this->file, '/') + 1); $dotPosition = strrpos($name, '.'); if ($dotPosition) { $name = substr($name, 0, $dotPosition); } // Replace trailing numbers, to allow files to obtain the same name. $this->name = preg_replace('/([^\d])\d{0,2}$/', '\1', $name); } public function jsonSerialize() { return [ 'file' => $this->file, 'name' => $this->name, 'id' => hash('crc32', $this->name), 'mtime' => $this->mtime ]; } }
[r] Make must_fail fully compatible with nose Originally, whenever you run a must_fail test alone and directly with nose, you would get this error message: 'ValueError: no such test method in <test reference>: test_decorated'
from robber import BadExpectation from robber.matchers.base import Base expectation_count = 0 fail_count = 0 old_match = Base.match def new_match(self): global expectation_count expectation_count += 1 try: old_match(self) except BadExpectation: global fail_count fail_count += 1 def reset(): global expectation_count global fail_count Base.match = old_match expectation_count = 0 fail_count = 0 def must_fail(fn): """ This checks if every expectation in a test fails. """ def test_decorated(self, *args, **kwargs): Base.match = new_match fn(self, *args, **kwargs) message = 'The test has {expectation_count} expectations, only {fail_count} fails.'.format( expectation_count=expectation_count, fail_count=fail_count ) if fail_count < expectation_count: reset() raise BadExpectation(message) reset() test_decorated.__name__ = fn.__name__ return test_decorated
from robber import BadExpectation from robber.matchers.base import Base expectation_count = 0 fail_count = 0 old_match = Base.match def new_match(self): global expectation_count expectation_count += 1 try: old_match(self) except BadExpectation: global fail_count fail_count += 1 def reset(): global expectation_count global fail_count Base.match = old_match expectation_count = 0 fail_count = 0 def must_fail(fn): """ This checks if every expectation in a test fails. """ def test_decorated(self, *args, **kwargs): Base.match = new_match fn(self, *args, **kwargs) message = 'The test has {expectation_count} expectations, only {fail_count} fails.'.format( expectation_count=expectation_count, fail_count=fail_count ) if fail_count < expectation_count: reset() raise BadExpectation(message) reset() return test_decorated
Debug update continued: Removed the cost of mesh position to ints.
package net.piemaster.jario.systems; import net.piemaster.jario.components.CollisionMesh; import net.piemaster.jario.components.Transform; import com.artemis.ComponentMapper; import com.artemis.Entity; import com.artemis.EntityProcessingSystem; public class CollisionMeshSystem extends EntityProcessingSystem { private ComponentMapper<Transform> transformMapper; private ComponentMapper<CollisionMesh> meshMapper; @SuppressWarnings("unchecked") public CollisionMeshSystem() { super(Transform.class, CollisionMesh.class); } @Override public void initialize() { transformMapper = new ComponentMapper<Transform>(Transform.class, world.getEntityManager()); meshMapper = new ComponentMapper<CollisionMesh>(CollisionMesh.class, world.getEntityManager()); } @Override protected void process(Entity e) { CollisionMesh mesh = meshMapper.get(e); if(mesh != null) { Transform t = transformMapper.get(e); meshMapper.get(e).setLocation(t.getX(), t.getY()); } } }
package net.piemaster.jario.systems; import net.piemaster.jario.components.CollisionMesh; import net.piemaster.jario.components.Transform; import com.artemis.ComponentMapper; import com.artemis.Entity; import com.artemis.EntityProcessingSystem; public class CollisionMeshSystem extends EntityProcessingSystem { private ComponentMapper<Transform> transformMapper; private ComponentMapper<CollisionMesh> meshMapper; @SuppressWarnings("unchecked") public CollisionMeshSystem() { super(Transform.class, CollisionMesh.class); } @Override public void initialize() { transformMapper = new ComponentMapper<Transform>(Transform.class, world.getEntityManager()); meshMapper = new ComponentMapper<CollisionMesh>(CollisionMesh.class, world.getEntityManager()); } @Override protected void process(Entity e) { CollisionMesh mesh = meshMapper.get(e); if(mesh != null) { Transform t = transformMapper.get(e); meshMapper.get(e).setLocation((int)t.getX(), (int)t.getY()); } } }
Use proper clock if possible
# vim:fileencoding=utf-8:noet from functools import wraps try: # Python>=3.3, the only valid clock source for this job from time import monotonic as time except ImportError: # System time, is affected by clock updates. from time import time def default_cache_key(**kwargs): return frozenset(kwargs.items()) class memoize(object): '''Memoization decorator with timeout.''' def __init__(self, timeout, cache_key=default_cache_key, cache_reg_func=None): self.timeout = timeout self.cache_key = cache_key self.cache = {} self.cache_reg_func = cache_reg_func def __call__(self, func): @wraps(func) def decorated_function(**kwargs): if self.cache_reg_func: self.cache_reg_func(self.cache) self.cache_reg_func = None key = self.cache_key(**kwargs) try: cached = self.cache.get(key, None) except TypeError: return func(**kwargs) # Handle case when time() appears to be less then cached['time'] due # to clock updates. Not applicable for monotonic clock, but this # case is currently rare. if cached is None or not (cached['time'] < time() < cached['time'] + self.timeout): cached = self.cache[key] = { 'result': func(**kwargs), 'time': time(), } return cached['result'] return decorated_function
# vim:fileencoding=utf-8:noet from functools import wraps import time def default_cache_key(**kwargs): return frozenset(kwargs.items()) class memoize(object): '''Memoization decorator with timeout.''' def __init__(self, timeout, cache_key=default_cache_key, cache_reg_func=None): self.timeout = timeout self.cache_key = cache_key self.cache = {} self.cache_reg_func = cache_reg_func def __call__(self, func): @wraps(func) def decorated_function(**kwargs): if self.cache_reg_func: self.cache_reg_func(self.cache) self.cache_reg_func = None key = self.cache_key(**kwargs) try: cached = self.cache.get(key, None) except TypeError: return func(**kwargs) if cached is None or time.time() - cached['time'] > self.timeout: cached = self.cache[key] = { 'result': func(**kwargs), 'time': time.time(), } return cached['result'] return decorated_function
Change to use a stream() rather than parallelStream()
package uk.sky.cirrus; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Host; import uk.sky.cirrus.exception.ClusterUnhealthyException; import java.net.InetAddress; import java.util.List; import java.util.stream.Collectors; class ClusterHealth { private final Cluster cluster; ClusterHealth(Cluster cluster) { this.cluster = cluster; } void check() throws ClusterUnhealthyException{ final List<InetAddress> unhealthyHosts = cluster.getMetadata().getAllHosts() .stream() .filter(host -> !host.isUp()) .map(Host::getAddress) .collect(Collectors.toList()); if(!unhealthyHosts.isEmpty()){ throw new ClusterUnhealthyException("Cluster not healthy, the following hosts are down: " + unhealthyHosts); } if (!cluster.getMetadata().checkSchemaAgreement()) { throw new ClusterUnhealthyException("Cluster not healthy, schema not in agreement"); } } }
package uk.sky.cirrus; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Host; import uk.sky.cirrus.exception.ClusterUnhealthyException; import java.net.InetAddress; import java.util.List; import java.util.stream.Collectors; class ClusterHealth { private final Cluster cluster; ClusterHealth(Cluster cluster) { this.cluster = cluster; } void check() throws ClusterUnhealthyException{ final List<InetAddress> unhealthyHosts = cluster.getMetadata().getAllHosts() .parallelStream() .filter(host -> !host.isUp()) .map(Host::getAddress) .collect(Collectors.toList()); if(!unhealthyHosts.isEmpty()){ throw new ClusterUnhealthyException("Cluster not healthy, the following hosts are down: " + unhealthyHosts); } if (!cluster.getMetadata().checkSchemaAgreement()) { throw new ClusterUnhealthyException("Cluster not healthy, schema not in agreement"); } } }
Update package version to v1.1.0
from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open("README.md", "r") as fh: long_description = fh.read() setup( name='django-cra-helper', version='1.1.0', description='The missing piece of the Django + React puzzle', long_description=long_description, long_description_content_type="text/markdown", url='https://github.com/MasterKale/django-cra-helper', author='Matthew Miller', author_email='matthew@millerti.me', license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', ], keywords='django react create-react-app integrate', packages=find_packages(exclude=['contrib', 'docs', 'tests']), install_requires=[ 'bleach>=2' ], )
from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open("README.md", "r") as fh: long_description = fh.read() setup( name='django-cra-helper', version='1.0.2', description='The missing piece of the Django + React puzzle', long_description=long_description, long_description_content_type="text/markdown", url='https://github.com/MasterKale/django-cra-helper', author='Matthew Miller', author_email='matthew@millerti.me', license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', ], keywords='django react create-react-app integrate', packages=find_packages(exclude=['contrib', 'docs', 'tests']), install_requires=[ 'bleach>=2' ], )
Fix lint errors in Object.get
import * as changeCase from 'change-case' import pluralize from 'pluralize' export default { ...changeCase, pluralize, resourceize: function(string) { return pluralize(changeCase.camel(string)) } } Object.map = function(source, func) { return Object.keys(source).map(key => { let value = source[key] return func(key, value) }) } Object.get = function(source, keypath) { const keys = keypath.split('.') while (keys[1]) { let key = keys.shift() source = source[key] if (typeof source === 'undefined') return source } return source } Object.without = function(source, ...keys) { let copy = Object.assign({}, source) let i = keys.length while (i--) { let key = keys[i] copy[key] = undefined delete copy[key] } return copy } // eslint-disable-next-line Promise.prototype.log = function() { return this.then(function(data) { console.log(data) return data }) }
import * as changeCase from 'change-case' import pluralize from 'pluralize' export default { ...changeCase, pluralize, resourceize: function(string) { return pluralize(changeCase.camel(string)) } } Object.map = function(source, func) { return Object.keys(source).map(key => { let value = source[key] return func(key, value) }) } Object.get = function(source, keypath) { const keys = keypath.split('.') let key while (key = keys.shift()) { source = source[key] if (typeof source === 'undefined') return source } return source } Object.without = function(source, ...keys) { let copy = Object.assign({}, source) let i = keys.length while (i--) { let key = keys[i] copy[key] = undefined delete copy[key] } return copy } // eslint-disable-next-line Promise.prototype.log = function() { return this.then(function(data) { console.log(data) return data }) }
Fix code formatting for PSR-2 compatibility
<?php declare(strict_types=1); namespace Zubr; /** * (PHP 5 &gt;=5.5.0)<br/> * Return the values from a single column in the input array * @link http://www.php.net/manual/en/function.array-column.php * @param array $array <p>A multi-dimensional array (record set) from which to pull a column of values.</p> * @param mixed $column <p>The column of values to return. This value may be the integer key of the column you wish to * retrieve, or it may be the string key name for an associative array. It may also be NULL to return complete arrays * (useful together with index_key to reindex the array).</p> * @param mixed $index_key [optional] <p>The column to use as the index/keys for the returned array. This value may be * the integer key of the column, or it may be the string key name.</p> * @return array Returns an array of values representing a single column from the input array. * @since 5.5.0 */ function array_column(array $array, $column, $index_key = null): array { return \array_column($array, $column, $index_key); }
<?php declare(strict_types=1); namespace Zubr; /** * (PHP 5 &gt;=5.5.0)<br/> * Return the values from a single column in the input array * @link http://www.php.net/manual/en/function.array-column.php * @param array $array <p>A multi-dimensional array (record set) from which to pull a column of values.</p> * @param mixed $column <p>The column of values to return. This value may be the integer key of the column you wish to retrieve, or it may be the string key name for an associative array. It may also be NULL to return complete arrays (useful together with index_key to reindex the array).</p> * @param mixed $index_key [optional] <p>The column to use as the index/keys for the returned array. This value may be the integer key of the column, or it may be the string key name.</p> * @return array Returns an array of values representing a single column from the input array. * @since 5.5.0 */ function array_column(array $array, $column, $index_key = null): array { return \array_column($array, $column, $index_key); }
Fix pouchdb middleware to handle conflict and retry to update a document
import { getDocument, updateDocument } from '../services/pouchdbService'; import { isEqual } from 'lodash'; import { NEW_POUCHDB, LOAD_EBUDGIE, INITIAL_LOAD, } from '../constants/ActionTypes'; const applyChanges = async (nextState, prevState) => { try { const storedDocument = await getDocument(prevState.pouchdb.dbName); await updateDocument({ ...nextState.ebudgie, _rev: storedDocument._rev, }); } catch (e) { if (e.status === 409) { await applyChanges(nextState, prevState); } else { throw e; } } } const storage = store => next => async action => { const prevState = store.getState(); const result = next(action); const nextState = store.getState(); const isNotLoadAction = action.type !== NEW_POUCHDB && action.type !== LOAD_EBUDGIE; const documentHasChanged = !isEqual(prevState.ebudgie, nextState.ebudgie); if (isNotLoadAction && documentHasChanged) { try { if (action.type === INITIAL_LOAD) { await updateDocument({ ...nextState.ebudgie, }); } else { await applyChanges(nextState, prevState); } } catch (e) { } } return result; }; export default storage;
import { getDocument, updateDocument } from '../services/pouchdbService'; import { isEqual } from 'lodash'; import { NEW_POUCHDB, LOAD_EBUDGIE, INITIAL_LOAD, } from '../constants/ActionTypes'; const storage = store => next => async action => { const prevState = store.getState(); const result = next(action); const nextState = store.getState(); const isNotLoadAction = action.type !== NEW_POUCHDB && action.type !== LOAD_EBUDGIE; const documentHasChanged = !isEqual(prevState.ebudgie, nextState.ebudgie); if (isNotLoadAction && documentHasChanged) { try { if (action.type === INITIAL_LOAD) { await updateDocument({ ...nextState.ebudgie, }); } else { const storedDocument = await getDocument(prevState.pouchdb.dbName); await updateDocument({ ...nextState.ebudgie, _rev: storedDocument._rev, }); } } catch (e) { } } return result; }; export default storage;
Update regular expression for registration code
/* globals Stripe */ import Ember from 'ember'; var $ = Ember.$; function registrationDataFromUrl(url) { var matches = url.match(/\?code=([a-z0-9]+)/); if (matches && matches.length === 2) { return {registration_code: matches[1]}; } else { return {}; } } function initializeStripe(key) { Stripe.setPublishableKey(key); } function setupCsrfHeaders(token) { $.ajaxPrefilter(function(options, originalOptions, jqXHR) { return jqXHR.setRequestHeader('X-CSRF-Token', token); }); } export default Ember.Service.extend({ setup: function(url) { return $.get( '/training/api/sessions', registrationDataFromUrl(url) ).then(this.requestDidReturn); }, requestDidReturn: function(response) { setupCsrfHeaders(response.authenticity_token); initializeStripe(response.stripe_public_key); } });
/* globals Stripe */ import Ember from 'ember'; var $ = Ember.$; function registrationDataFromUrl(url) { var matches = url.match(/\?code=(\d+)/); if (matches && matches.length === 2) { return {registration_code: matches[1]}; } else { return {}; } } function initializeStripe(key) { Stripe.setPublishableKey(key); } function setupCsrfHeaders(token) { $.ajaxPrefilter(function(options, originalOptions, jqXHR) { return jqXHR.setRequestHeader('X-CSRF-Token', token); }); } export default Ember.Service.extend({ setup: function(url) { return $.get( '/training/api/sessions', registrationDataFromUrl(url) ).then(this.requestDidReturn); }, requestDidReturn: function(response) { setupCsrfHeaders(response.authenticity_token); initializeStripe(response.stripe_public_key); } });
Use utils to get config and add shebang
#!/usr/bin/env node var request = require('request'); var utils = require('./utils'); var instanceConfig = utils.getConfig().getActiveInstanceConfig(); function Action(actionPath, payload) { var actionPathBase = [ 'http://', instanceConfig.username + ':', instanceConfig.password + '@', instanceConfig.host + ':', instanceConfig.port + '/api/jsonws' ].join(''); this.actionPath = actionPathBase + actionPath; this.payload = payload; } Action.prototype.doAction = function(callback) { var payload = this.payload; try { if (!payload) { throw new Error('Missing payload object'); } if (!callback) { throw new Error('Missing callback function'); } request.post( { url: this.actionPath, form: payload }, function(error, response, body) { if (!error) { if (response.statusCode === 200) { callback(null, body); } else { var serverError = JSON.parse(response.body).error; console.log(''); utils.printJSON(serverError); console.log(''); } } else { console.error('ERROR: ', error); callback(error); } } ); } catch(e) { console.error(e); } } module.exports = Action;
var instanceConfig = require('./config').getActiveInstanceConfig(); var request = require('request'); var utils = require('./utils'); function Action(actionPath, payload) { var actionPathBase = [ 'http://', instanceConfig.username + ':', instanceConfig.password + '@', instanceConfig.host + ':', instanceConfig.port + '/api/jsonws' ].join(''); this.actionPath = actionPathBase + actionPath; this.payload = payload; } Action.prototype.doAction = function(callback) { var payload = this.payload; try { if (!payload) { throw new Error('Missing payload object'); } if (!callback) { throw new Error('Missing callback function'); } request.post( { url: this.actionPath, form: payload }, function(error, response, body) { if (!error) { if (response.statusCode === 200) { callback(null, body); } else { var serverError = JSON.parse(response.body).error; console.log(''); utils.printJSON(serverError); console.log(''); } } else { console.error('ERROR: ', error); callback(error); } } ); } catch(e) { console.error(e); } } module.exports = Action;
Add encrypt key list item jsx
'use strict'; import React, { Component } from 'react'; import ReactCSS from 'reactcss'; import { User } from '../common/index'; import colors from '../../styles/variables/colors'; import { spacing, sizing } from '../../styles/variables/utils'; class EncryptKeyListItem extends Component { classes() { return { 'default': { user: { padding: `${spacing.m}px ${spacing.m}px ${spacing.m}px`, display: 'flex', }, spaceLine: { borderBottom: `solid 1px ${colors.offBgLight}`, margin: `0px ${spacing.m}px 0px ${spacing.m + sizing.avatar + spacing.s}px`, item: 1, }, }, }; } render() { return <div> <div is="user"> <User name={ this.props.name } /> </div> <div is="spaceLine"/> </div>; } } export default ReactCSS(EncryptKeyListItem);
'use strict'; import React, { Component } from 'react'; import ReactCSS from 'reactcss'; import { User } from '../common/index'; import colors from '../../styles/variables/colors'; import { spacing, sizing } from '../../styles/variables/utils'; class EncryptKeyListItem extends Component { classes() { return { 'default': { user: { padding: `${spacing.m}px ${spacing.m}px ${spacing.m}px`, display: 'flex', }, spaceLine: { borderBottom: `solid 1px ${colors.offBgLight}`, margin: `0px ${spacing.m}px 0px ${spacing.m + sizing.avatar + spacing.s}px`, item: 1, }, }, }; } render() { return <div></div>; } } export default ReactCSS(EncryptKeyListItem);
Fix the doc-explorer-back button overflow.
<style> #content.pw-content{ padding: 0px; } #graphiql { height: 80vh; border-right: 1px solid #efefef; } #graphiql * { box-sizing: content-box; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; line-height: 1rem; } #graphiql .doc-explorer-title{ overflow: hidden; } #graphiql .graphiql-container .doc-explorer-back{ line-height: 0.85rem; } #graphiql .doc-explorer-contents{ padding: 5px 20px 15px; } #graphiql .graphiql-container .search-box{ margin: 5px 0px 8px 0; } #graphiql .graphiql-container .search-box:before{ top: 5px; } #graphiql .graphiql-container .search-box input{ padding: 6px 0px 8px 24px; width: 94%; background: none; } <?= $CSS ?> </style> <div id="graphiql">Loading...</div> <script> var GraphQLServerUrl = "<?= $GraphQLServerUrl ?>"; <?= $JavaScript ?> </script>
<style> #content.pw-content{ padding: 0px; } #content .pw-container, #content .container{ width: 100%; max-width: none; } #graphiql { height: 100vh; } #graphiql * { box-sizing: content-box; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; line-height: 1rem; } #graphiql .doc-explorer-title{ overflow: hidden; } #graphiql .doc-explorer-contents{ padding: 5px 20px 15px; } #graphiql .graphiql-container .search-box{ margin: 5px 0px 8px 0; } #graphiql .graphiql-container .search-box:before{ top: 5px; } #graphiql .graphiql-container .search-box input{ padding: 6px 0px 8px 24px; width: 94%; background: none; } <?= $CSS ?> </style> <div id="graphiql">Loading...</div> <script> var GraphQLServerUrl = "<?= $GraphQLServerUrl ?>"; <?= $JavaScript ?> </script>
Add some error handling in case there's no connection to the bit.ly servers.
/** * bit.ly access library code. */ var Shortener = new JS.Singleton('Shortener', { initialize: function() { this.extend({ CLIENT: BitlyClient || null, NAMESPACE: BitlyCB || null }); }, shorten: function() { var uri, callback; if (typeof arguments[0] == 'string') { uri = arguments[0]; callback = arguments[1]; } else { uri = window.location.href; callback = arguments[0]; } var name = this._registerCallback(callback); if (!(name && this.CLIENT)) return; this.CLIENT.call('shorten', { 'longUrl': uri }, 'BitlyCB.' + name); }, _dispatcher: function(callback, data) { var result; // Results are keyed by longUrl, so we need to grab the first one. for (var r in data.results) { result = data.results[r]; break; } callback(result, data); }, _registerCallback: function(callback) { if (!this.NAMESPACE) return false; var name = 'abbr' + this.callbackCount; this.callbackCount += 1; this.NAMESPACE[name] = function(data) { this._dispatcher(callback, data); }.bind(this); return name; }, callbackCount: 0 });
/** * bit.ly access library code. */ var Shortener = new JS.Singleton('Shortener', { shorten: function() { var uri, callback; if (typeof arguments[0] == 'string') { uri = arguments[0]; callback = arguments[1]; } else { uri = window.location.href; callback = arguments[0]; } var name = this._registerCallback(callback); this.CLIENT.call('shorten', { 'longUrl': uri }, 'BitlyCB.' + name); }, _dispatcher: function(callback, data) { var result; // Results are keyed by longUrl, so we need to grab the first one. for (var r in data.results) { result = data.results[r]; break; } callback(result, data); }, _registerCallback: function(callback) { var name = 'abbr' + this.callbackCount; this.callbackCount += 1; this.NAMESPACE[name] = function(data) { this._dispatcher(callback, data); }.bind(this); return name; }, callbackCount: 0, CLIENT: BitlyClient, NAMESPACE: BitlyCB });
Fix price calculator class names
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2017-02-16 07:39 from __future__ import unicode_literals from django.db import migrations def update_price_calculator(apps, schema_editor): ShippingMethod = apps.get_model("shipping", "ShippingMethod") for shipping_method in ShippingMethod.objects.filter(price_calculator="lfs.shipping.NetShippingMethodPriceCalculator"): shipping_method.price_calculator = "lfs.shipping.calculator.NetShippingMethodPriceCalculator" shipping_method.save() for shipping_method in ShippingMethod.objects.filter(price_calculator="lfs.shipping.GrossShippingMethodPriceCalculator"): shipping_method.price_calculator = "lfs.shipping.calculator.GrossShippingMethodPriceCalculator" shipping_method.save() class Migration(migrations.Migration): dependencies = [ ('shipping', '0001_initial'), ] operations = [ migrations.RunPython(update_price_calculator), ]
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2017-02-16 07:39 from __future__ import unicode_literals from django.db import migrations def update_price_calculator(apps, schema_editor): ShippingMethod = apps.get_model("shipping", "ShippingMethod") for shipping_method in ShippingMethod.objects.filter(price_calculator="lfs.shipping.NetShippingMethodPriceCalculator"): shipping_method.price_calculator = "lfs.shipping.calculator.NetPriceCalculator" shipping_method.save() for shipping_method in ShippingMethod.objects.filter(price_calculator="lfs.shipping.GrossShippingMethodPriceCalculator"): shipping_method.price_calculator = "lfs.shipping.calculator.GrossPriceCalculator" shipping_method.save() class Migration(migrations.Migration): dependencies = [ ('shipping', '0001_initial'), ] operations = [ migrations.RunPython(update_price_calculator), ]
web: Fix static path for production bundle
var path = require('path'), webpack = require('webpack'); module.exports = { cache: true, entry: './src/main.js', output: { path: path.join(__dirname, "build"), filename: "bundle.js", publicPath: "/static/" }, module: { loaders: [ {test: /\.js$/, loader: 'jsx-loader?harmony'}, {test: /\.css$/, loader: 'style!css'}, {test: /\.scss$/, loader: "style!css!sass"}, {test: /\.ttf$/, loader: "file-loader"}, {test: /\.svg$/, loader: "file-loader"}, {test: /\.eot$/, loader: "file-loader"}, {test: /\.woff$/, loader: "file-loader"} ] }, plugins: [ new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin() ] }
var path = require('path'), webpack = require('webpack'); module.exports = { cache: true, entry: './src/main.js', output: { path: path.join(__dirname, "build"), filename: "bundle.js" }, module: { loaders: [ {test: /\.js$/, loader: 'jsx-loader?harmony'}, {test: /\.css$/, loader: 'style!css'}, {test: /\.scss$/, loader: "style!css!sass"}, {test: /\.ttf$/, loader: "file-loader"}, {test: /\.svg$/, loader: "file-loader"}, {test: /\.eot$/, loader: "file-loader"}, {test: /\.woff$/, loader: "file-loader"} ] }, plugins: [ new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin() ] }
Add missing module event type hint
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @package Zend_ModuleManager */ namespace Zend\ModuleManager\Listener; use Zend\ModuleManager\ModuleEvent; /** * Module resolver listener * * @category Zend * @package Zend_ModuleManager * @subpackage Listener */ class ModuleResolverListener extends AbstractListener { /** * @param ModuleEvent $e * @return object|false False if module class does not exist */ public function __invoke(ModuleEvent $e) { $moduleName = $e->getModuleName(); $class = $moduleName . '\Module'; if (!class_exists($class)) { return false; } $module = new $class; return $module; } }
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @package Zend_ModuleManager */ namespace Zend\ModuleManager\Listener; /** * Module resolver listener * * @category Zend * @package Zend_ModuleManager * @subpackage Listener */ class ModuleResolverListener extends AbstractListener { /** * @param \Zend\EventManager\EventInterface $e * @return object */ public function __invoke($e) { $moduleName = $e->getModuleName(); $class = $moduleName . '\Module'; if (!class_exists($class)) { return false; } $module = new $class; return $module; } }
Add gRPC specific code to acceptance test
// +build acceptance package app import ( "os" "time" "github.com/DATA-DOG/godog" "github.com/goph/stdlib/net" "google.golang.org/grpc" ) func init() { runs = append(runs, func() int { format := "progress" for _, arg := range os.Args[1:] { // go test transforms -v option if arg == "-test.v=true" { format = "pretty" break } } return godog.RunWithOptions( "godog", FeatureContext, godog.Options{ Format: format, Paths: []string{"features"}, Randomize: time.Now().UTC().UnixNano(), // randomize scenario execution order }, ) }) } func FeatureContext(s *godog.Suite) { addr := net.ResolveVirtualAddr("pipe", "pipe") listener, dialer := net.PipeListen(addr) server := grpc.NewServer() client, _ := grpc.Dial("", grpc.WithInsecure(), grpc.WithDialer(func(s string, t time.Duration) (stdnet.Conn, error) { return dialer.Dial() })) // Add steps here go server.Serve(listener) }
// +build acceptance package app import ( "os" "time" "github.com/DATA-DOG/godog" ) func init() { runs = append(runs, func() int { format := "progress" for _, arg := range os.Args[1:] { // go test transforms -v option if arg == "-test.v=true" { format = "pretty" break } } return godog.RunWithOptions( "godog", FeatureContext, godog.Options{ Format: format, Paths: []string{"features"}, Randomize: time.Now().UTC().UnixNano(), // randomize scenario execution order }, ) }) } func FeatureContext(s *godog.Suite) { // Add steps here }
Disable Harmony Symbols & Proxies, they're completely broken
'use strict'; var findup = require('findup-sync'); var spawnSync = require('child_process').spawnSync; var gruntPath = findup('node_modules/{.,}bin/grunt', {cwd: __dirname}); process.title = 'grunth'; var harmonyFlags = [ '--harmony_scoping', // '--harmony_modules', // We have `require` and ES6 modules are still in flux // '--harmony_symbols', // `Symbol('s')` throws // '--harmony_proxies', // `new Proxy({}, {})` throws // '--harmony_collections', // `new Set([2, 3])` doesn't work '--harmony_generators', // '--harmony_iteration', // no `for-of`, the description must be wrong '--harmony_numeric_literals', '--harmony_strings', '--harmony_arrays', '--harmony_maths', ]; module.exports = function cli(params) { spawnSync('node', harmonyFlags.concat([gruntPath]).concat(params), { cwd: process.cwd(), stdio: 'inherit', } ); };
'use strict'; var findup = require('findup-sync'); var spawnSync = require('child_process').spawnSync; var gruntPath = findup('node_modules/{.,}bin/grunt', {cwd: __dirname}); process.title = 'grunth'; var harmonyFlags = [ '--harmony_scoping', // '--harmony_modules', // We have `require` and ES6 modules are still in flux '--harmony_symbols', '--harmony_proxies', // '--harmony_collections', // `new Set([2, 3])` doesn't work '--harmony_generators', // '--harmony_iteration', // no `for-of`, the description must be wrong '--harmony_numeric_literals', '--harmony_strings', '--harmony_arrays', '--harmony_maths', ]; module.exports = function cli(params) { spawnSync('node', harmonyFlags.concat([gruntPath]).concat(params), { cwd: process.cwd(), stdio: 'inherit', } ); };
Use the default buffer instead of current_buffer.
from prompt_toolkit.layout.toolbars import Toolbar from prompt_toolkit.layout.utils import TokenList from pygments.token import Token class PGToolbar(Toolbar): def __init__(self, token=None): token = token or Token.Toolbar.Status super(self.__class__, self).__init__(token=token) def get_tokens(self, cli, width): result = TokenList() result.append((self.token, ' ')) if cli.buffers['default'].completer.smart_completion: result.append((self.token.On, '[F2] Smart Completion: ON ')) else: result.append((self.token.Off, '[F2] Smart Completion: OFF ')) if cli.buffers['default'].always_multiline: result.append((self.token.On, '[F3] Multiline: ON')) else: result.append((self.token.Off, '[F3] Multiline: OFF')) if cli.buffers['default'].always_multiline: result.append((self.token, ' (Semi-colon [;] will end the line)')) return result
from prompt_toolkit.layout.toolbars import Toolbar from prompt_toolkit.layout.utils import TokenList from pygments.token import Token class PGToolbar(Toolbar): def __init__(self, token=None): token = token or Token.Toolbar.Status super(self.__class__, self).__init__(token=token) def get_tokens(self, cli, width): result = TokenList() result.append((self.token, ' ')) if cli.current_buffer.completer.smart_completion: result.append((self.token.On, '[F2] Smart Completion: ON ')) else: result.append((self.token.Off, '[F2] Smart Completion: OFF ')) if cli.current_buffer.always_multiline: result.append((self.token.On, '[F3] Multiline: ON')) else: result.append((self.token.Off, '[F3] Multiline: OFF')) if cli.current_buffer.always_multiline: result.append((self.token, ' (Semi-colon [;] will end the line)')) return result
Use email variable name where appropriate
from flask import Flask, jsonify, request from requests import codes app = Flask(__name__) @app.route('/login', methods=['POST']) def login(): email = request.form['email'] password = request.form['password'] response_content = {'email': email, 'password': password} return jsonify(response_content), codes.OK @app.route('/signup', methods=['POST']) def signup(): email = request.form['email'] password = request.form['password'] user = User(email=email, password=password) response_content = {'email': email, 'password': password} return jsonify(response_content), codes.CREATED if __name__ == '__main__': # Specifying 0.0.0.0 as the host tells the operating system to listen on # all public IPs. This makes the server visible externally. # See http://flask.pocoo.org/docs/0.10/quickstart/#a-minimal-application app.run(host='0.0.0.0', debug=True)
from flask import Flask, jsonify, request from requests import codes app = Flask(__name__) @app.route('/login', methods=['POST']) def login(): username = request.form['email'] password = request.form['password'] response_content = {'email': username, 'password': password} return jsonify(response_content), codes.OK @app.route('/signup', methods=['POST']) def signup(): username = request.form['email'] password = request.form['password'] response_content = {'email': username, 'password': password} return jsonify(response_content), codes.CREATED if __name__ == '__main__': # Specifying 0.0.0.0 as the host tells the operating system to listen on # all public IPs. This makes the server visible externally. # See http://flask.pocoo.org/docs/0.10/quickstart/#a-minimal-application app.run(host='0.0.0.0', debug=True)
Add a "New()" function that allows for custom conf Signed-off-by: Peter Olds <f516c8e349fcaee4098dbef1ab3f4b8dc00e321e@kyanicorp.com>
package logger import ( "os" "strconv" "github.com/Sirupsen/logrus" "github.com/polds/logrus/hooks/papertrail" ) var __l *logrus.Logger type Config struct { Appname string Host string Port int *logrus.Logger } // Logger returns an instance of // a logger or creates a new one. func Logger() *logrus.Logger { if __l == nil { __l = NewLogger() } return __l } // New creates a new instance of a // logger based on provided config data func New(config Config) Config { config.Logger = logrus.New() hook, err := logrus_papertrail.NewPapertrailHook(config.Host, config.Port, config.Appname) hook.UseHostname() // Register the PaperTrail hook if err == nil { config.Logger.Hooks.Add(hook) } return config } // DefaultConfig makes certain assumptions about your environment variables // and can be used to create a new basic instance. func DefaultConfig() Config { app := os.Getenv("APPNAME") if app == "" { app, _ = os.Hostname() os.Setenv("APPNAME", app) } port, _ := strconv.Atoi(os.Getenv("PAPERTRAIL_PORT")) return Config{ Appname: os.Getenv("APPNAME"), Host: os.Getenv("PAPERTRAIL_HOST"), Port: port, } } // @TODO polds deprecate this function func NewLogger() *logrus.Logger { return New(DefaultConfig()).Logger }
package logger import ( "os" "strconv" "github.com/Sirupsen/logrus" "github.com/polds/logrus/hooks/papertrail" ) var __l *logrus.Logger // Logger returns an instance of // a logger or creates a new one. func Logger() *logrus.Logger { if __l == nil { __l = NewLogger() } return __l } // NewLogger creates a new instances of a // logrus logger and returns the instance. func NewLogger() *logrus.Logger { app := os.Getenv("APPNAME") if app == "" { app, _ = os.Hostname() os.Setenv("APPNAME", app) } host := os.Getenv("PAPERTRAIL_HOST") port, _ := strconv.Atoi(os.Getenv("PAPERTRAIL_PORT")) log := logrus.New() hook, err := logrus_papertrail.NewPapertrailHook(host, port, app) hook.UseHostname() // Register the PaperTrail hook if err == nil { log.Hooks.Add(hook) } return log }
Update test (trying to fix Travis error)
var fs = require('fs') var assert = require('assert') var rmrf = require('rimraf') var Writer = require('../src/writer') describe('Writer', function() { this.timeout(10000) var tempPath = __dirname + '/../tmp' var filePath = tempPath + '/../tmp/test.txt' beforeEach(function() { rmrf.sync(tempPath) fs.mkdirSync(tempPath) }) it('always writes data from the latest call', function(done) { var writer = new Writer(filePath) // 1M characters var data = '' for (var i = 0; i <= 1000 * 1000; i++) { data += 'x' } for (var i = 0; i <= 1000 * 1000; i++) { writer.write(data + i) } setTimeout(function() { assert.equal(fs.readFileSync(filePath, 'utf-8'), data + (i - 1)) done() }, 1000) }) })
var fs = require('fs') var assert = require('assert') var rmrf = require('rimraf') var Writer = require('../src/writer') describe('Writer', function() { this.timeout(5000) var tempPath = __dirname + '/../tmp' var filePath = tempPath + '/../tmp/test.txt' beforeEach(function() { rmrf.sync(tempPath) fs.mkdirSync(tempPath) }) it('always writes data from the latest call', function(done) { var writer = new Writer(filePath) // 1M characters var data = '' for (var i = 0; i <= 1000 * 1000; i++) { data += 'x' } for (var i = 0; i <= 1000 * 1000; i++) { writer.write(data + i) } setTimeout(function() { assert.equal(fs.readFileSync(filePath, 'utf-8'), data + (i - 1)) done() }, 1000) }) })
Support configuring style include paths
const browser = require('browser-sync'); const config = require('../../config'); const gulp = require('gulp'); const handleError = require('../../utilities/handleError'); const path = require('path'); const sass = require('gulp-sass'); const sourcemaps = require('gulp-sourcemaps'); /** * HyperBolts ϟ (https://hyperbolts.io) * * Copyright © 2015-present Pace IT Systems Ltd. * All rights reserved. * * @author Pace IT Systems Ltd * @license MIT */ module.exports = paths => () => gulp.src(paths.src) // Compile .pipe(sourcemaps.init()) .pipe(sass({ includePaths: paths.includePaths || [ path.join(process.cwd(), 'node_modules'), process.cwd() ] })) .on('error', handleError) .pipe(sourcemaps.write()) // Output .pipe(gulp.dest( path.resolve(config.base, paths.dest) )) // Reload browser .pipe(browser.reload({ stream: true }));
const browser = require('browser-sync'); const config = require('../../config'); const gulp = require('gulp'); const handleError = require('../../utilities/handleError'); const path = require('path'); const sass = require('gulp-sass'); const sourcemaps = require('gulp-sourcemaps'); /** * HyperBolts ϟ (https://hyperbolts.io) * * Copyright © 2015-present Pace IT Systems Ltd. * All rights reserved. * * @author Pace IT Systems Ltd * @license MIT */ module.exports = paths => () => gulp.src(paths.src) // Compile .pipe(sourcemaps.init()) .pipe(sass({ includePaths: [ path.join(process.cwd(), 'node_modules'), process.cwd() ] })) .on('error', handleError) .pipe(sourcemaps.write()) // Output .pipe(gulp.dest( path.resolve(config.base, paths.dest) )) // Reload browser .pipe(browser.reload({ stream: true }));
Remove version number from Python shebang. On special request from someone trying to purge python2.2 from code indexed internally at Google. git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@7071 0039d316-1c4b-4281-b951-d872f2087c98
#!/usr/bin/python # Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import md5 """64-bit fingerprint support for strings. Usage: from extern import FP print 'Fingerprint is %ld' % FP.FingerPrint('Hello world!') """ def UnsignedFingerPrint(str, encoding='utf-8'): """Generate a 64-bit fingerprint by taking the first half of the md5 of the string.""" hex128 = md5.new(str).hexdigest() int64 = long(hex128[:16], 16) return int64 def FingerPrint(str, encoding='utf-8'): fp = UnsignedFingerPrint(str, encoding=encoding) # interpret fingerprint as signed longs if fp & 0x8000000000000000L: fp = - ((~fp & 0xFFFFFFFFFFFFFFFFL) + 1) return fp
#!/usr/bin/python2.2 # Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import md5 """64-bit fingerprint support for strings. Usage: from extern import FP print 'Fingerprint is %ld' % FP.FingerPrint('Hello world!') """ def UnsignedFingerPrint(str, encoding='utf-8'): """Generate a 64-bit fingerprint by taking the first half of the md5 of the string.""" hex128 = md5.new(str).hexdigest() int64 = long(hex128[:16], 16) return int64 def FingerPrint(str, encoding='utf-8'): fp = UnsignedFingerPrint(str, encoding=encoding) # interpret fingerprint as signed longs if fp & 0x8000000000000000L: fp = - ((~fp & 0xFFFFFFFFFFFFFFFFL) + 1) return fp
Add method to move a module on top of others
(function(app) { 'use strict'; var jCore = require('jcore'); var helper = app.helper || require('../helper.js'); var Module = app.Module || require('./module.js'); var ModuleContainer = helper.inherits(function(props) { ModuleContainer.super_.call(this); this.modules = this.prop([]); this.element = this.prop(props.element); this.deleter = ModuleContainer.prototype.deleter.bind(this); }, jCore.Component); ModuleContainer.prototype.loadModule = function(props) { props.deleter = this.deleter; var module = new Module(props); this.modules().push(module); module.parentElement(this.element()); module.redraw(); return module.loadComponent().then(function() { return module; }); }; ModuleContainer.prototype.toFront = function(module) { var modules = this.modules(); var index = modules.indexOf(module); if (index === -1) return; modules.splice(index, 1); modules.push(module); }; ModuleContainer.prototype.deleter = function(module) { var modules = this.modules(); var index = modules.indexOf(module); if (index === -1) return; modules.splice(index, 1); }; if (typeof module !== 'undefined' && module.exports) module.exports = ModuleContainer; else app.ModuleContainer = ModuleContainer; })(this.app || (this.app = {}));
(function(app) { 'use strict'; var jCore = require('jcore'); var helper = app.helper || require('../helper.js'); var Module = app.Module || require('./module.js'); var ModuleContainer = helper.inherits(function(props) { ModuleContainer.super_.call(this); this.modules = this.prop([]); this.element = this.prop(props.element); this.deleter = ModuleContainer.prototype.deleter.bind(this); }, jCore.Component); ModuleContainer.prototype.loadModule = function(props) { props.deleter = this.deleter; var module = new Module(props); this.modules().push(module); module.parentElement(this.element()); module.redraw(); return module.loadComponent().then(function() { return module; }); }; ModuleContainer.prototype.deleter = function(module) { var modules = this.modules(); var index = modules.indexOf(module); if (index === -1) return; modules.splice(index, 1); }; if (typeof module !== 'undefined' && module.exports) module.exports = ModuleContainer; else app.ModuleContainer = ModuleContainer; })(this.app || (this.app = {}));
Add target attribute to a.fancybox to prevent default theme's links following
'use strict'; var cheerio = require('cheerio'); var _ = require('underscore'); var multiline = require('multiline'); var template = _.template(multiline(function() { /* <a href="<%= url %>" title="<%= title %>" target="_self" class="fancybox"> <img src="<%= url %>" alt="<%= title %>"></img> </a> */ })); module.exports = { book: { assets: './assets', js: [ 'jquery.min.js', 'jquery.fancybox.pack.js', 'jquery.fancybox-buttons.js', 'plugin.js' ], css: [ 'jquery.fancybox.css', 'jquery.fancybox-buttons.css' ] }, hooks: { page: function(page) { var $ = cheerio.load(page.content); $('img').each(function(index, img) { var $img = $(img); $img.replaceWith(template({ url: $img.attr('src'), title: $img.attr('alt') })); }); page.content = $.html(); return page; } } };
'use strict'; var cheerio = require('cheerio'); var _ = require('underscore'); var multiline = require('multiline'); var template = _.template(multiline(function() { /* <a href="<%= url %>" title="<%= title %>" class="fancybox"> <img src="<%= url %>" alt="<%= title %>"></img> </a> */ })); module.exports = { book: { assets: './assets', js: [ 'jquery.min.js', 'jquery.fancybox.pack.js', 'jquery.fancybox-buttons.js', 'plugin.js' ], css: [ 'jquery.fancybox.css', 'jquery.fancybox-buttons.css' ] }, hooks: { page: function(page) { var $ = cheerio.load(page.content); $('img').each(function(index, img) { var $img = $(img); $img.replaceWith(template({ url: $img.attr('src'), title: $img.attr('alt') })); }); page.content = $.html(); return page; } } };
Clarify build name for SauceLabs dashboard
// this file is for use in CircleCI continuous integration environment module.exports = { seleniumServerURL: { hostname : 'ondemand.saucelabs.com', port : 80, }, driverCapabilities: { platform : 'Windows 7', 'tunnel-identifier' : 'circle-' + process.env.CIRCLE_BUILD_NUM + '-' + process.env.CIRCLE_NODE_INDEX, }, tags : [ 'circle-ci', '#' + process.env.CIRCLE_BUILD_NUM ], views : [ 'Verbose', 'SauceLabs' ], quit : 'always', // avoid wasting 90 seconds on SauceLabs bail : true, build : 'CircleCI-' + process.env.CIRCLE_PROJECT_USERNAME + '-' + process.env.CIRCLE_PROJECT_REPONAME +'#' + process.env.CIRCLE_BUILD_NUM, }
// this file is for use in CircleCI continuous integration environment module.exports = { seleniumServerURL: { hostname : 'ondemand.saucelabs.com', port : 80, }, driverCapabilities: { platform : 'Windows 7', 'tunnel-identifier' : 'circle-' + process.env.CIRCLE_BUILD_NUM + '-' + process.env.CIRCLE_NODE_INDEX, }, tags : [ 'circle-ci', '#' + process.env.CIRCLE_BUILD_NUM ], views : [ 'Verbose', 'SauceLabs' ], quit : 'always', // avoid wasting 90 seconds on SauceLabs bail : true, build : 'CircleCI#' + process.env.CIRCLE_BUILD_NUM, }
:art: Simplify nbsp replacing, yet again
'use babel' /* @flow */ import type { Message } from '../types' export function visitMessage(message: Message) { const messageFile = message.version === 1 ? message.filePath : message.location.file const messageRange = message.version === 1 ? message.range : message.location.position atom.workspace.open(messageFile, { searchAllPanes: true }).then(function() { const textEditor = atom.workspace.getActiveTextEditor() if (textEditor && textEditor.getPath() === messageFile) { textEditor.setCursorBufferPosition(messageRange.start) } }) } export function htmlToText(html: any) { const element = document.createElement('div') if (typeof html === 'string') { element.innerHTML = html } else { element.appendChild(html.cloneNode(true)) } // NOTE: Convert &nbsp; to regular whitespace return element.textContent.replace(/\u00A0/gu, ' ') }
'use babel' /* @flow */ import type { Message } from '../types' const nbsp = String.fromCodePoint(160) export function visitMessage(message: Message) { const messageFile = message.version === 1 ? message.filePath : message.location.file const messageRange = message.version === 1 ? message.range : message.location.position atom.workspace.open(messageFile, { searchAllPanes: true }).then(function() { const textEditor = atom.workspace.getActiveTextEditor() if (textEditor && textEditor.getPath() === messageFile) { textEditor.setCursorBufferPosition(messageRange.start) } }) } export function htmlToText(html: any) { const element = document.createElement('div') if (typeof html === 'string') { element.innerHTML = html } else { element.appendChild(html.cloneNode(true)) } // NOTE: Convert &nbsp; to regular whitespace return element.textContent.replace(new RegExp(nbsp, 'g'), ' ') }
Remove array wrapper on storage get() key
import {getJSON} from './fetch.js'; // Retrieve the raw user preferences without defaults merged in export function getRawPreferences() { return new Promise((resolve) => { chrome.storage.sync.get('preferences', (items) => { resolve(items.preferences); }); }); } // Retrieve the map of default values for user preferences export function getDefaultPreferences() { return getJSON('data/preferences/defaults.json'); } // Get the final preferences object (stored user data merged with defaults) export function getPreferences() { return Promise.all([ getDefaultPreferences(), getRawPreferences(), ]) .then(([defaultPrefs, rawPrefs]) => { return Object.assign({}, defaultPrefs, rawPrefs); }); } // Merge the given preferences into the persisted user preferences object export function setPreferences(prefsToUpdate) { return getPreferences() .then((currentPrefs) => { let newPrefs = Object.assign(currentPrefs, prefsToUpdate); return new Promise((resolve) => { chrome.storage.sync.set({preferences: newPrefs}, () => { resolve(newPrefs); }); }); }); }
import {getJSON} from './fetch.js'; // Retrieve the raw user preferences without defaults merged in export function getRawPreferences() { return new Promise((resolve) => { chrome.storage.sync.get(['preferences'], (items) => { resolve(items.preferences); }); }); } // Retrieve the map of default values for user preferences export function getDefaultPreferences() { return getJSON('data/preferences/defaults.json'); } // Get the final preferences object (stored user data merged with defaults) export function getPreferences() { return Promise.all([ getDefaultPreferences(), getRawPreferences(), ]) .then(([defaultPrefs, rawPrefs]) => { return Object.assign({}, defaultPrefs, rawPrefs); }); } // Merge the given preferences into the persisted user preferences object export function setPreferences(prefsToUpdate) { return getPreferences() .then((currentPrefs) => { let newPrefs = Object.assign(currentPrefs, prefsToUpdate); return new Promise((resolve) => { chrome.storage.sync.set({preferences: newPrefs}, () => { resolve(newPrefs); }); }); }); }
Fix license header violations in messagebus Change-Id: I3b5f5b3e96716552562498590988097c5d3c1308 Signed-off-by: Thanh Ha <09ea4d3a79c8bee41a16519f6a431f6bc0fd8d6f@linuxfoundation.org>
/* * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.messagebus.app.impl; import org.opendaylight.controller.md.sal.dom.api.DOMNotification; import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.TopicNotification; import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; import org.opendaylight.yangtools.yang.model.api.SchemaPath; public class TopicDOMNotification implements DOMNotification { private static final SchemaPath TOPIC_NOTIFICATION_ID = SchemaPath.create(true, TopicNotification.QNAME); private final ContainerNode body; public TopicDOMNotification(final ContainerNode body) { this.body = body; } @Override public SchemaPath getType() { return TOPIC_NOTIFICATION_ID; } @Override public ContainerNode getBody() { return body; } @Override public String toString() { return "TopicDOMNotification [body=" + body + "]"; } }
/* * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.messagebus.app.impl; import org.opendaylight.controller.md.sal.dom.api.DOMNotification; import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.TopicNotification; import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; import org.opendaylight.yangtools.yang.model.api.SchemaPath; public class TopicDOMNotification implements DOMNotification { private static final SchemaPath TOPIC_NOTIFICATION_ID = SchemaPath.create(true, TopicNotification.QNAME); private final ContainerNode body; public TopicDOMNotification(final ContainerNode body) { this.body = body; } @Override public SchemaPath getType() { return TOPIC_NOTIFICATION_ID; } @Override public ContainerNode getBody() { return body; } @Override public String toString() { return "TopicDOMNotification [body=" + body + "]"; } }
Handle case when YAML is empty.
""" ydf/templating ~~~~~~~~~~~~~~ Contains functions to be exported into the Jinja2 environment and accessible from templates. """ import jinja2 import os from ydf import instructions, __version__ DEFAULT_TEMPLATE_NAME = 'default.tpl' DEFAULT_TEMPLATE_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'templates') def render_vars(yaml_vars): """ Build a dict containing all variables accessible to a template during the rendering process. This is a merge of the YAML variables parsed from the file + build variables defined by :mod:`~ydf` itself. :param yaml_vars: Parsed from the parsed YAML file. :return: Dict of all variables available to template. """ return dict(ydf=dict(version=__version__), **(yaml_vars or {})) def environ(path=DEFAULT_TEMPLATE_PATH, **kwargs): """ Build a Jinja2 environment for the given template directory path and options. :param path: Path to search for Jinja2 template files :param kwargs: Options to configure the environment :return: :class:`~jinja2.Environment` instance """ kwargs.setdefault('trim_blocks', True) kwargs.setdefault('lstrip_blocks', True) env = jinja2.Environment(loader=jinja2.FileSystemLoader(path), **kwargs) env.globals[instructions.convert_instruction.__name__] = instructions.convert_instruction return env
""" ydf/templating ~~~~~~~~~~~~~~ Contains functions to be exported into the Jinja2 environment and accessible from templates. """ import jinja2 import os from ydf import instructions, __version__ DEFAULT_TEMPLATE_NAME = 'default.tpl' DEFAULT_TEMPLATE_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'templates') def render_vars(yaml_vars): """ Build a dict containing all variables accessible to a template during the rendering process. This is a merge of the YAML variables parsed from the file + build variables defined by :mod:`~ydf` itself. :param yaml_vars: Parsed from the parsed YAML file. :return: Dict of all variables available to template. """ return dict(ydf=dict(version=__version__), **yaml_vars) def environ(path=DEFAULT_TEMPLATE_PATH, **kwargs): """ Build a Jinja2 environment for the given template directory path and options. :param path: Path to search for Jinja2 template files :param kwargs: Options to configure the environment :return: :class:`~jinja2.Environment` instance """ kwargs.setdefault('trim_blocks', True) kwargs.setdefault('lstrip_blocks', True) env = jinja2.Environment(loader=jinja2.FileSystemLoader(path), **kwargs) env.globals[instructions.convert_instruction.__name__] = instructions.convert_instruction return env
Rename `Stop recording` to `Pause recording`
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import RecordIcon from 'react-icons/lib/md/fiber-manual-record'; import PauseIcon from 'react-icons/lib/md/pause-circle-filled'; import Button from '../Button'; import { pauseRecording } from '../../actions'; class RecordButton extends Component { static propTypes = { paused: PropTypes.bool, pauseRecording: PropTypes.func.isRequired }; shouldComponentUpdate(nextProps) { return nextProps.paused !== this.props.paused; } render() { return ( <Button Icon={this.props.paused ? RecordIcon : PauseIcon} onClick={this.props.pauseRecording} >{this.props.paused ? 'Start recording' : 'Pause recording'}</Button> ); } } function mapDispatchToProps(dispatch, ownProps) { return { pauseRecording: () => dispatch(pauseRecording(!ownProps.paused)) }; } export default connect(null, mapDispatchToProps)(RecordButton);
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import RecordIcon from 'react-icons/lib/md/fiber-manual-record'; import StopIcon from 'react-icons/lib/md/stop'; import Button from '../Button'; import { pauseRecording } from '../../actions'; class RecordButton extends Component { static propTypes = { paused: PropTypes.bool, pauseRecording: PropTypes.func.isRequired }; shouldComponentUpdate(nextProps) { return nextProps.paused !== this.props.paused; } render() { return ( <Button Icon={this.props.paused ? RecordIcon : StopIcon} onClick={this.props.pauseRecording} >{this.props.paused ? 'Start recording' : 'Stop recording'}</Button> ); } } function mapDispatchToProps(dispatch, ownProps) { return { pauseRecording: () => dispatch(pauseRecording(!ownProps.paused)) }; } export default connect(null, mapDispatchToProps)(RecordButton);
Make IRC handler a bit less verbose
/* eslint no-console: 0 */ 'use strict'; const irc = require('irc'); const server = process.env.IRC_SERVER; const user = process.env.IRC_USER; const channel = process.env.IRC_CHANNEL; const client = module.exports.client = new irc.Client(server, user, { autoConnect: false, autoRejoin: true, channels: [channel], showErrors: true, }); client.connect(5, function() { console.log(new Date(), '[IRC]', 'Connected!'); }); if (process.env.NODE_ENV !== 'testing') { client.on('registered', function clientOnRegisterd(message) { console.log(new Date(), '[IRC]', message.args[1]); }); } client.on('error', function clientOnError(error) { console.error(error); console.error('Shutting Down...'); process.exit(1); }); module.exports.notify = function ircPost(nodes, callback) { nodes.forEach(function nodesForEach(node) { // let name = `[${node.name}](${jenkins}/computer/${node.name})`; if (node.offline) { client.say(channel, `Jenkins slave ${node.name} is offline`); } else { client.say(channel, `Jenkins slave ${node.name} is online`); } }); callback(null); };
/* eslint no-console: 0 */ 'use strict'; const irc = require('irc'); const server = process.env.IRC_SERVER; const user = process.env.IRC_USER; const channel = process.env.IRC_CHANNEL; const client = module.exports.client = new irc.Client(server, user, { debug: true, autoConnect: false, autoRejoin: true, channels: [channel], showErrors: true, }); client.connect(5, function() { console.log(arguments); }); if (process.env.NODE_ENV !== 'testing') { client.on('registered', function clientOnRegisterd(message) { console.log(new Date(), '[IRC]', message.args[1]); }); } client.on('error', function clientOnError(error) { console.error(error); console.error('Shutting Down...'); process.exit(1); }); module.exports.notify = function ircPost(nodes, callback) { nodes.forEach(function nodesForEach(node) { // let name = `[${node.name}](${jenkins}/computer/${node.name})`; if (node.offline) { client.say(channel, `Jenkins slave ${node.name} is offline`); } else { client.say(channel, `Jenkins slave ${node.name} is online`); } }); callback(null); };
Use medieval font to the outcome text
package br.odb.menu; import android.app.Activity; import android.graphics.Typeface; import android.os.Bundle; import android.widget.TextView; import br.odb.knights.R; public class ShowOutcomeActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.outcome_layout); boolean outcomeIsGood = KnightsOfAlentejoSplashActivity.GameOutcome.valueOf( getIntent().getStringExtra( KnightsOfAlentejoSplashActivity.MAPKEY_SUCCESSFUL_LEVEL_OUTCOME) ) == KnightsOfAlentejoSplashActivity.GameOutcome.VICTORY; ((TextView) findViewById(R.id.tvOutcome)).setText( getString( outcomeIsGood ? R.string.outcome_good : R.string.outcome_bad ) ); ((TextView) findViewById(R.id.tvOutcome)).setTextColor(outcomeIsGood ? 0xFF00FF00 : 0xFFFF0000); Typeface font = Typeface.createFromAsset(getAssets(), "fonts/MedievalSharp.ttf"); ( (TextView)findViewById(R.id.tvOutcome) ).setTypeface( font ); } }
package br.odb.menu; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import br.odb.knights.R; public class ShowOutcomeActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.outcome_layout); boolean outcomeIsGood = KnightsOfAlentejoSplashActivity.GameOutcome.valueOf( getIntent().getStringExtra( KnightsOfAlentejoSplashActivity.MAPKEY_SUCCESSFUL_LEVEL_OUTCOME) ) == KnightsOfAlentejoSplashActivity.GameOutcome.VICTORY; ((TextView) findViewById(R.id.tvOutcome)).setText( getString( outcomeIsGood ? R.string.outcome_good : R.string.outcome_bad ) ); ((TextView) findViewById(R.id.tvOutcome)).setTextColor(outcomeIsGood ? 0xFF00FF00 : 0xFFFF0000); } }
Handle case where Status===inherit but no parent available
// const debug = require('debug')('W2:portal:instance/page/compute-document-status'); const Promise = require('bluebird'); function getParentStatus(statusConfig, persistence, entity, instance) { return Promise.resolve() .then(() => entity.getParentInstance(persistence, instance)) .then((parentInstances) => parentInstances.pop()) .then((parentInstance) => { if (parentInstance) { const parentStatus = parentInstance[statusConfig.property]; if (parentStatus === statusConfig.inheritance) { return Promise.resolve() .then(() => entity.getParentEntity(instance)) .then((parentEntity) => getParentStatus(statusConfig, persistence, parentEntity, parentInstance)) ; } else { return parentStatus; } } }) ; } module.exports = (statusConfig, persistence, entity, instance) => { const instanceStatus = instance[statusConfig.property]; return (instanceStatus === statusConfig.inheritance) ? getParentStatus(statusConfig, persistence, entity, instance) : instanceStatus ; };
// const debug = require('debug')('W2:portal:instance/page/compute-document-status'); const Promise = require('bluebird'); function getParentStatus(statusConfig, persistence, entity, instance) { return Promise.resolve() .then(() => entity.getParentInstance(persistence, instance)) .then((parentInstances) => parentInstances.pop()) .then((parentInstance) => { const parentStatus = parentInstance[statusConfig.property]; if (parentStatus === statusConfig.inheritance) { return Promise.resolve() .then(() => entity.getParentEntity(instance)) .then((parentEntity) => getParentStatus(statusConfig, persistence, parentEntity, parentInstance)) ; } else { return parentStatus; } }) ; } module.exports = (statusConfig, persistence, entity, instance) => { const instanceStatus = instance[statusConfig.property]; return (instanceStatus === statusConfig.inheritance) ? getParentStatus(statusConfig, persistence, entity, instance) : instanceStatus ; };
Use backend type instead of multiple flag
<?php namespace qnd; /** * Loader * * @param array $attr * @param array $item * * @return mixed */ function loader(array $attr, array $item) { $item[$attr['id']] = cast($attr, $item[$attr['id']] ?? null); $callback = fqn('loader_' . $attr['type']); if (is_callable($callback)) { return $callback($attr, $item); } // Temporary if ($attr['backend'] === 'json') { return loader_json($attr, $item); } return $item[$attr['id']]; } /** * JSON loader * * @param array $attr * @param array $item * * @return array */ function loader_json(array $attr, array $item): array { if (empty($item[$attr['id']])) { return []; } elseif (is_array($item[$attr['id']])) { return $item[$attr['id']]; } return json_decode($item[$attr['id']], true) ?: []; }
<?php namespace qnd; /** * Loader * * @param array $attr * @param array $item * * @return mixed */ function loader(array $attr, array $item) { $item[$attr['id']] = cast($attr, $item[$attr['id']] ?? null); $callback = fqn('loader_' . $attr['type']); if (is_callable($callback)) { return $callback($attr, $item); } // Temporary if ($attr['multiple']) { return loader_json($attr, $item); } return $item[$attr['id']]; } /** * JSON loader * * @param array $attr * @param array $item * * @return array */ function loader_json(array $attr, array $item): array { if (empty($item[$attr['id']])) { return []; } elseif (is_array($item[$attr['id']])) { return $item[$attr['id']]; } return json_decode($item[$attr['id']], true) ?: []; }
Add small message for forgotten link
@extends('layout.layout') @section('content') <div class="row"> <div class="eleven wide column"> <!-- TODO use trans()--> We will send you a mail containing your secret connection link. <form class="ui form"> <div class="field"> <label>Your email adress</label> <input type="text" name="email" placeholder="The email adress you used to create the ad"> </div> <div class="align-center"> <button class="ui red submit button" type="submit">Submit</button> </div> </form> </div> <div class="five wide column"> @include('ads.elements.notifications') </div> </div> @stop
@extends('layout.layout') @section('content') <div class="row"> <div class="eleven wide column"> <!-- TODO use trans()--> <form class="ui form"> <div class="field"> <label>Your email adress</label> <input type="text" name="email" placeholder="The email adress you used to create the ad"> </div> <div class="align-center"> <button class="ui red submit button" type="submit">Submit</button> </div> </form> </div> <div class="five wide column"> @include('ads.elements.notifications') </div> </div> @stop
Add the py.test coverage plugin package (pytest-cov) as an extra dependency.
#!/usr/bin/env python # -*- coding: utf8 -*- from setuptools import setup, find_packages setup( name="jawa", packages=find_packages(), version="1.0", description="Doing fun stuff with JVM ClassFiles.", author="Tyler Kennedy", author_email="tk@tkte.ch", url="http://github.com/TkTech/Jawa", keywords=["java", "disassembly", "disassembler"], classifiers=[ "Programming Language :: Python", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Topic :: Software Development :: Disassemblers" ], extras_require={ 'dev': [ 'pytest', 'pytest-cov' ] } )
#!/usr/bin/env python # -*- coding: utf8 -*- from setuptools import setup, find_packages setup( name="jawa", packages=find_packages(), version="1.0", description="Doing fun stuff with JVM ClassFiles.", author="Tyler Kennedy", author_email="tk@tkte.ch", url="http://github.com/TkTech/Jawa", keywords=["java", "disassembly", "disassembler"], classifiers=[ "Programming Language :: Python", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Topic :: Software Development :: Disassemblers" ], extras_require={ 'dev': [ 'pytest' ] } )
Add context when calling UserSerializer
from rest_framework.decorators import api_view from rest_framework.response import Response from .utils import absolute_reverse from api.users.serializers import UserSerializer @api_view(('GET',)) def root(request, format=None): if request.user and not request.user.is_anonymous(): user = request.user current_user = UserSerializer(user, context={'request': request}).data else: current_user = None return Response({ 'meta': { 'message': 'Welcome to the OSF API.', 'version': request.version, 'current_user': current_user, }, 'links': { 'nodes': absolute_reverse('nodes:node-list'), 'users': absolute_reverse('users:user-list'), } })
from rest_framework.decorators import api_view from rest_framework.response import Response from .utils import absolute_reverse from api.users.serializers import UserSerializer @api_view(('GET',)) def root(request, format=None): if request.user and not request.user.is_anonymous(): user = request.user current_user = UserSerializer(user).data else: current_user = None return Response({ 'meta': { 'message': 'Welcome to the OSF API.', 'version': request.version, 'current_user': current_user, }, 'links': { 'nodes': absolute_reverse('nodes:node-list'), 'users': absolute_reverse('users:user-list'), } })
Create a compatible ast.parse with PY3 Created a function compatible with both PY2 and PY3 equivalent to ast.parse.
from __future__ import print_function from __future__ import division import sys import types from ast import PyCF_ONLY_AST PY2 = sys.version_info[0] == 2 PYPY = hasattr(sys, 'pypy_translation_info') _identity = lambda x: x if not PY2: string_types = (str,) integer_types = (int,) long = int class_types = (type,) from io import StringIO import builtins def to_bytes(s): return s.encode() def to_str(b): return b.decode() else: string_types = (str, unicode) integer_types = (int, long) long = long class_types = (type, types.ClassType) from cStringIO import StringIO import __builtin__ as builtins to_bytes = _identity to_str = _identity def ast_parse(s): return compile(s, '<string>', 'exec', \ print_function.compiler_flag|division.compiler_flag|PyCF_ONLY_AST)
import sys import types PY2 = sys.version_info[0] == 2 PYPY = hasattr(sys, 'pypy_translation_info') _identity = lambda x: x if not PY2: string_types = (str,) integer_types = (int,) long = int class_types = (type,) from io import StringIO import builtins def to_bytes(s): return s.encode() def to_str(b): return b.decode() else: string_types = (str, unicode) integer_types = (int, long) long = long class_types = (type, types.ClassType) from cStringIO import StringIO import __builtin__ as builtins to_bytes = _identity to_str = _identity
Fix the Nick command help text
from twisted.plugin import IPlugin from heufybot.moduleinterface import IBotModule from heufybot.modules.commandinterface import BotCommand from zope.interface import implements class NickCommand(BotCommand): implements(IPlugin, IBotModule) name = "Nick" def triggers(self): return ["nick"] def load(self): self.help = "Commands: nick <newnick> | Change the nickname of the bot." self.commandHelp = {} def checkPermissions(self, server, source, user, command): return not self.bot.moduleHandler.runActionUntilFalse("checkadminpermission", server, source, user, "connection-control") def execute(self, server, source, command, params, data): if len(params) < 1: self.bot.servers[server].outputHandler.cmdPRIVMSG(source, "Change my nick to what?") else: self.bot.servers[server].outputHandler.cmdNICK(params[0]) nickCommand = NickCommand()
from twisted.plugin import IPlugin from heufybot.moduleinterface import IBotModule from heufybot.modules.commandinterface import BotCommand from zope.interface import implements class NickCommand(BotCommand): implements(IPlugin, IBotModule) name = "Nick" def triggers(self): return ["nick"] def load(self): self.help = "Commands: nick | Change the nickname of the bot." self.commandHelp = {} def checkPermissions(self, server, source, user, command): return not self.bot.moduleHandler.runActionUntilFalse("checkadminpermission", server, source, user, "connection-control") def execute(self, server, source, command, params, data): if len(params) < 1: self.bot.servers[server].outputHandler.cmdPRIVMSG(source, "Change my nick to what?") else: self.bot.servers[server].outputHandler.cmdNICK(params[0]) nickCommand = NickCommand()
Add empty result sql query message and move instruction to ErrorMsg
/* * Copyright 2015 Ryan Gilera. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.daytron.revworks.data; /** * Collection of exception messages. * * @author Ryan Gilera */ public enum ExceptionMsg { AUTHENTICATION_EXCEPTION_NO_USER("No such user found. Invalid credentials."), AUTHENTICATION_EXCEPTION_SYS_ERROR("System error occured "), NO_CURRENT_USER_EXCEPTION("No user is login"), WRONG_CURRENT_USER_TYPE_EXCEPTION("Wrong user type access."), EMPTY_SQL_RESULT("Empty SQL query result."); private final String msg; private ExceptionMsg(String msg) { this.msg = msg; } public String getMsg() { return msg; } }
/* * Copyright 2015 Ryan Gilera. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.daytron.revworks.data; /** * Collection of exception messages. * * @author Ryan Gilera */ public enum ExceptionMsg { AUTHENTICATION_EXCEPTION_NO_USER("No such user found. Invalid credentials."), AUTHENTICATION_EXCEPTION_SYS_ERROR("System error occured, " + "please consult your administrator for help."), NO_CURRENT_USER_EXCEPTION("No user is login"), WRONG_CURRENT_USER_TYPE_EXCEPTION("Wrong user type access."); private final String msg; private ExceptionMsg(String msg) { this.msg = msg; } public String getMsg() { return msg; } }
Add author and author email.
#!/usr/bin/env python import setuptools install_requires = [ 'PrettyTable==0.7.2', 'kazoo==1.00', 'simplejson', 'argparse', 'kafka-python' ] setuptools.setup( name = 'stormkafkamon', version = '0.1.0', license = 'Apache', description = '''Monitor offsets of a storm kafka spout.''', author = "Philip O'Toole", author_email = 'philipomailbox-github@yahoo.com', url = 'https://github.com/otoolep/stormkafkamon', platforms = 'any', packages = ['stormkafkamon'], zip_safe = True, verbose = False, install_requires = install_requires, dependency_links = ['https://github.com/mumrah/kafka-python/tarball/0.7#egg=kafka-python-0.7.2-0'], entry_points={ 'console_scripts': [ 'skmon = stormkafkamon.monitor:main' ] }, )
#!/usr/bin/env python import setuptools install_requires = [ 'PrettyTable==0.7.2', 'kazoo==1.00', 'simplejson', 'argparse', 'kafka-python' ] setuptools.setup( name = 'stormkafkamon', version = '0.1.0', license = 'Apache', description = '''Monitor offsets of a storm kafka spout.''', author = '', author_email = '', url = 'https://github.com/otoolep/stormkafkamon', platforms = 'any', packages = ['stormkafkamon'], zip_safe = True, verbose = False, install_requires = install_requires, dependency_links = ['https://github.com/mumrah/kafka-python/tarball/0.7#egg=kafka-python-0.7.2-0'], entry_points={ 'console_scripts': [ 'skmon = stormkafkamon.monitor:main' ] }, )
Reduce log messages in production
var db = require('./db'); module.exports = function (server, cookieParser, sessionStore) { var io = require('socket.io').listen(server); var SessionSockets = require('session.socket.io'); var sessionSockets = new SessionSockets(io, sessionStore, cookieParser); var env = process.env.NODE_ENV || 'development'; if ('production' == env) { io.set('log level', 1); } sessionSockets.on('connection', function (err, socket, session) { var found; if (err || !session.user) { socket.emit('login:unauthorized'); return; } socket.emit('login:success', session.user); socket.session = session; socket.on('start', function () { db.users.findOne({login: session.user}, function (err, user) { socket.user = user; io.sockets.$emit('start', socket); }); }); }); return io; };
var db = require('./db'); module.exports = function (server, cookieParser, sessionStore) { var io = require('socket.io').listen(server); var SessionSockets = require('session.socket.io'); var sessionSockets = new SessionSockets(io, sessionStore, cookieParser); sessionSockets.on('connection', function (err, socket, session) { var found; if (err || !session.user) { socket.emit('login:unauthorized'); return; } socket.emit('login:success', session.user); socket.session = session; socket.on('start', function () { db.users.findOne({login: session.user}, function (err, user) { socket.user = user; io.sockets.$emit('start', socket); }); }); }); return io; };
Make more explicit variable name.
# Neurotopics/code/DataSet.py import neurosynth.analysis.reduce as nsar class DataSet: """ A DataSet takes a NeuroSynth dataset and extracts the DOI's, and word subset of interest. It uses reduce.average_within_regions to get the average activation in the regions of interest (ROIs) of the img. """ def __init__(self, neurosynth_dataset, image_file_name, word_counts_file): self.word_subset = neurosynth_dataset.get_feature_names() self.dois = list(neurosynth_dataset.feature_table.ids) self.average_activation = nsar.average_within_regions(neurosynth_dataset, image_file_name) self.get_word_subset_counts(self.word_subset, word_counts_file) def get_word_subset_counts(self, word_subset, word_counts_file): pass
# Neurotopics/code/DataSet.py import neurosynth.analysis.reduce as nsar class DataSet: """ A DataSet takes a NeuroSynth dataset and extracts the DOI's, and word subset of interest. It uses reduce.average_within_regions to get the average activation in the regions of interest (ROIs) of the img. """ def __init__(self, neurosynth_dataset, img, word_counts_file): self.word_subset = neurosynth_dataset.get_feature_names() self.dois = list(neurosynth_dataset.feature_table.ids) self.average_activation = nsar.average_within_regions(neurosynth_dataset, img) self.get_word_subset_counts(self.word_subset, word_counts_file) def get_word_subset_counts(self, word_subset, word_counts_file): pass
Change encoding name for no reason
# encoding=utf_8 from __future__ import unicode_literals import socket from time import sleep def mount(s, at, uuid=None, label=None, name=None): for name, value in ((b'uuid', uuid), (b'label', label), (b'name', name)): if value is not None: value = value.encode('utf_8') at = at.encode('utf_8') msg = b'5:mount{0}:{1}={2}{3}:at={4}$'.format( len(name + value) + 1, name, value, len(b'at' + at) + 1, at) print repr(msg) s.sendall(msg[0:9]) sleep(1) s.sendall(msg[9:]) return def main(): s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) s.connect('/tmp/arise.sock') mount(s, '/mnt/place', label='UFDé') sleep(1) if __name__ == '__main__': main()
# encoding=utf-8 from __future__ import unicode_literals import socket from time import sleep def mount(s, at, uuid=None, label=None, name=None): for name, value in ((b'uuid', uuid), (b'label', label), (b'name', name)): if value is not None: value = value.encode('utf_8') at = at.encode('utf_8') msg = b'5:mount{0}:{1}={2}{3}:at={4}$'.format( len(name + value) + 1, name, value, len(b'at' + at) + 1, at) print repr(msg) s.sendall(msg[0:9]) sleep(1) s.sendall(msg[9:]) return def main(): s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) s.connect('/tmp/arise.sock') mount(s, '/mnt/place', label='UFDé') sleep(1) if __name__ == '__main__': main()
Call Fatalf to use the format specifier Signed-off-by: John Stephens <7eec02f6af4e6b1fb20edca992e35ddef4347d3d@docker.com>
package winio import "testing" func TestLookupInvalidSid(t *testing.T) { _, err := LookupSidByName(".\\weoifjdsklfj") aerr, ok := err.(*AccountLookupError) if !ok || aerr.Err != cERROR_NONE_MAPPED { t.Fatalf("expected AccountLookupError with ERROR_NONE_MAPPED, got %s", err) } } func TestLookupValidSid(t *testing.T) { sid, err := LookupSidByName("Everyone") if err != nil || sid != "S-1-1-0" { t.Fatalf("expected S-1-1-0, got %s, %s", sid, err) } } func TestLookupEmptyNameFails(t *testing.T) { _, err := LookupSidByName(".\\weoifjdsklfj") aerr, ok := err.(*AccountLookupError) if !ok || aerr.Err != cERROR_NONE_MAPPED { t.Fatalf("expected AccountLookupError with ERROR_NONE_MAPPED, got %s", err) } }
package winio import "testing" func TestLookupInvalidSid(t *testing.T) { _, err := LookupSidByName(".\\weoifjdsklfj") aerr, ok := err.(*AccountLookupError) if !ok || aerr.Err != cERROR_NONE_MAPPED { t.Fatalf("expected AccountLookupError with ERROR_NONE_MAPPED, got %s", err) } } func TestLookupValidSid(t *testing.T) { sid, err := LookupSidByName("Everyone") if err != nil || sid != "S-1-1-0" { t.Fatal("expected S-1-1-0, got %s, %s", sid, err) } } func TestLookupEmptyNameFails(t *testing.T) { _, err := LookupSidByName(".\\weoifjdsklfj") aerr, ok := err.(*AccountLookupError) if !ok || aerr.Err != cERROR_NONE_MAPPED { t.Fatalf("expected AccountLookupError with ERROR_NONE_MAPPED, got %s", err) } }
Use AppCompat instead of ActionBar
package org.apache.taverna.mobile.activities; import org.apache.taverna.mobile.R; import org.apache.taverna.mobile.fragments.workflowdetails.RunFragment; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; public class RunResult extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_run_result); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, RunFragment.newInstance()) .commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. return false; } @Override public boolean onOptionsItemSelected(MenuItem item) { this.finish(); return super.onOptionsItemSelected(item); } }
package org.apache.taverna.mobile.activities; import org.apache.taverna.mobile.R; import org.apache.taverna.mobile.fragments.workflowdetails.RunFragment; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; public class RunResult extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_run_result); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, RunFragment.newInstance()) .commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. return false; } @Override public boolean onOptionsItemSelected(MenuItem item) { this.finish(); return super.onOptionsItemSelected(item); } }
Fix error in showing expand button when it didn't need it
var CS = CS || {}; CS.BufferLength = 200; CS.Console = new Array(); CS.LastConsoleLength = 0; CS.SetProgress = function (percent) { document.getElementById('bar').style.width = percent + '%'; document.getElementById('percentage').innerHTML = percent + '%'; } CS.SetStatus = function (status) { document.getElementById('status').innerHTML = status; } CS.WriteConsole = function (text) { CS.Console.push(text); } CS.ShowAll = function() { CS.BufferLength = Number.MAX_SAFE_INTEGER; CS.BatchComplete(); } CS.BatchComplete = function () { if (CS.LastConsoleLength >= CS.Console.length) return; var bufferArray = CS.Console.slice(Math.max(0, CS.Console.length - CS.BufferLength), CS.Console.length); var contents = bufferArray.join(''); if (bufferArray.length != CS.Console.length) { contents = "<button onclick=\"CS.ShowAll()\" class=\"expand\">Expand complete log</button>" + contents; } var consoleElement = document.getElementById('console'); consoleElement.innerHTML = contents; var scrollHeight = Math.max(consoleElement.scrollHeight, consoleElement.clientHeight); consoleElement.scrollTop = scrollHeight - consoleElement.clientHeight; }
var CS = CS || {}; CS.BufferLength = 200; CS.Console = new Array(10000); CS.LastConsoleLength = 0; CS.SetProgress = function (percent) { document.getElementById('bar').style.width = percent + '%'; document.getElementById('percentage').innerHTML = percent + '%'; } CS.SetStatus = function (status) { document.getElementById('status').innerHTML = status; } CS.WriteConsole = function (text) { CS.Console.push(text); } CS.ShowAll = function() { CS.BufferLength = Number.MAX_SAFE_INTEGER; CS.BatchComplete(); } CS.BatchComplete = function () { if (CS.LastConsoleLength >= CS.Console.length) return; var bufferArray = CS.Console.slice(Math.max(0, CS.Console.length - CS.BufferLength), CS.Console.length); var contents = bufferArray.join(''); if (bufferArray.length !== CS.Console.length) { contents = "<button onclick=\"CS.ShowAll()\" class=\"expand\">Expand complete log</button>" + contents; } var console = document.getElementById('console'); console.innerHTML = contents; var scrollHeight = Math.max(console.scrollHeight, console.clientHeight); console.scrollTop = scrollHeight - console.clientHeight; }
Add description to config generator
import { Base } from 'yeoman-generator'; import generatorArguments from './arguments'; import generatorOptions from './options'; import generatorSteps from './steps'; export default class ConfigGenerator extends Base { constructor(...args) { super(...args); Object.keys(generatorArguments).forEach(key => this.argument(key, generatorArguments[key])); Object.keys(generatorOptions).forEach(key => this.option(key, generatorOptions[key])); this.description = 'Scaffolds configuration for REST API'; } get configuring() { return generatorSteps.configuring; } get conflicts() { return generatorSteps.conflicts; } get default() { return generatorSteps.default; } get end() { return generatorSteps.end; } get initializing() { return generatorSteps.initializing } get install() { return generatorSteps.install; } get prompting() { return generatorSteps.prompting } get writing() { return generatorSteps.writing; } }
import { Base } from 'yeoman-generator'; import generatorArguments from './arguments'; import generatorOptions from './options'; import generatorSteps from './steps'; export default class ConfigGenerator extends Base { constructor(...args) { super(...args); Object.keys(generatorArguments).forEach(key => this.argument(key, generatorArguments[key])); Object.keys(generatorOptions).forEach(key => this.option(key, generatorOptions[key])); } get configuring() { return generatorSteps.configuring; } get conflicts() { return generatorSteps.conflicts; } get default() { return generatorSteps.default; } get end() { return generatorSteps.end; } get initializing() { return generatorSteps.initializing } get install() { return generatorSteps.install; } get prompting() { return generatorSteps.prompting } get writing() { return generatorSteps.writing; } }
Rename asset part and remove image root
/** * Load configuration objects */ import path from 'path' import * as databaseConfig from './database' import * as redisConfig from './redis' import * as awsConfig from './aws' // Environment export const env = process.env.NODE_ENV || 'development' // Server export const keys = ['keys'] // Database, Redis, AWS export const database = databaseConfig[env] export const redis = redisConfig[env] export const aws = awsConfig[env] // Assets path export const ASSETS_PATH = path.resolve(__dirname, '../build/assets') // Queue names export const PROCESS_IMAGE_WORKER_QUEUE = 'PROCESS_IMAGE_WORKER_QUEUE' export const IMAGE_UPDATES_WORKER_QUEUE = 'IMAGE_UPDATES_WORKER_QUEUE' export const VOTE_UPDATES_WORKER_QUEUE = 'VOTE_UPDATES_WORKER_QUEUE'
/** * Load configuration objects */ import path from 'path' import * as databaseConfig from './database' import * as redisConfig from './redis' import * as awsConfig from './aws' // Environment export const env = process.env.NODE_ENV || 'development' // Server export const keys = ['keys'] // Database, Redis, AWS export const database = databaseConfig[env] export const redis = redisConfig[env] export const aws = awsConfig[env] // Assets path export const assetsPath = path.resolve(__dirname, '../build/assets') // Image root url // export const imageRoot = `//localhost:10001/${aws.bucket}` // Queue names export const PROCESS_IMAGE_WORKER_QUEUE = 'PROCESS_IMAGE_WORKER_QUEUE' export const IMAGE_UPDATES_WORKER_QUEUE = 'IMAGE_UPDATES_WORKER_QUEUE' export const VOTE_UPDATES_WORKER_QUEUE = 'VOTE_UPDATES_WORKER_QUEUE'
Put the content type here. git-svn-id: 3b6cb4556d214d66df54bca2662d7ef408f367bf@3330 46e82423-29d8-e211-989e-002590a4cdd4
<?php # # $Id: news.php,v 1.1.2.19 2005-05-17 22:47:34 dan Exp $ # # Copyright (c) 1998-2003 DVL Software Limited # DEFINE('MAX_PORTS', 20); require_once($_SERVER['DOCUMENT_ROOT'] . '/include/common.php'); require_once($_SERVER['DOCUMENT_ROOT'] . '/include/freshports.php'); require_once($_SERVER['DOCUMENT_ROOT'] . '/include/databaselogin.php'); require_once($_SERVER['DOCUMENT_ROOT'] . '/include/getvalues.php'); DEFINE('NEWSCACHE', $_SERVER['DOCUMENT_ROOT'] . '/../caching/cache/news.rss'); header('Content-type: application/rss+xml'); if (file_exists(NEWSCACHE) && is_readable(NEWSCACHE)) { readfile(NEWSCACHE); } $Statistics->Save(); ?>
<?php # # $Id: news.php,v 1.1.2.18 2004-11-26 14:57:20 dan Exp $ # # Copyright (c) 1998-2003 DVL Software Limited # DEFINE('MAX_PORTS', 20); require_once($_SERVER['DOCUMENT_ROOT'] . '/include/common.php'); require_once($_SERVER['DOCUMENT_ROOT'] . '/include/freshports.php'); require_once($_SERVER['DOCUMENT_ROOT'] . '/include/databaselogin.php'); require_once($_SERVER['DOCUMENT_ROOT'] . '/include/getvalues.php'); DEFINE('NEWSCACHE', $_SERVER['DOCUMENT_ROOT'] . '/../caching/cache/news.rss'); if (file_exists(NEWSCACHE) && is_readable(NEWSCACHE)) { readfile(NEWSCACHE); } $Statistics->Save(); ?>
Create test environment first to prevent the modified bootstrap configuration to be overwritten
<?php /** * Definition of class LanguageServiceTest * * @copyright 2014-today Justso GmbH * @author j.schirrmacher@justso.de * @package justso\justtexts\test */ namespace justso\justtexts\test; use justso\justapi\Bootstrap; use justso\justapi\testutil\ServiceTestBase; use justso\justtexts\service\Language; /** * Class LanguageServiceTest * @package justso\justtexts\test */ class LanguageServiceTest extends ServiceTestBase { public function testGetLanguages() { $env = $this->createTestEnvironment(); $config = array( 'environments' => array('test' => array('approot' => '/var/www')), 'languages' => array('de', 'en'), ); $env->getBootstrap()->setTestConfiguration('/var/www', $config); $service = new Language($env); $service->getAction(); $this->assertJSONHeader($env); $this->assertSame('["de","en"]', $env->getResponseContent()); } }
<?php /** * Definition of class LanguageServiceTest * * @copyright 2014-today Justso GmbH * @author j.schirrmacher@justso.de * @package justso\justtexts\test */ namespace justso\justtexts\test; use justso\justapi\Bootstrap; use justso\justapi\testutil\ServiceTestBase; use justso\justtexts\service\Language; /** * Class LanguageServiceTest * @package justso\justtexts\test */ class LanguageServiceTest extends ServiceTestBase { public function testGetLanguages() { $config = array( 'environments' => array('test' => array('approot' => '/var/www')), 'languages' => array('de', 'en'), ); Bootstrap::getInstance()->setTestConfiguration('/var/www', $config); $env = $this->createTestEnvironment(); $service = new Language($env); $service->getAction(); $this->assertJSONHeader($env); $this->assertSame('["de","en"]', $env->getResponseContent()); } }
Use the async version of readFile
'use strict'; var _ = require('lodash'); var fs = require('fs'); var hljs = require('../../build'); var jsdom = require('jsdom').jsdom; var utility = require('../utility'); describe('special cases tests', function() { before(function(done) { var filename = utility.buildPath('fixtures', 'index.html'); fs.readFile(filename, 'utf-8', function(err, page) { var blocks; // Allows hljs to use document global.document = jsdom(page); // Setup hljs environment hljs.configure({ tabReplace: ' ' }); hljs.initHighlighting(); // Setup hljs for non-`<pre><code>` tests hljs.configure({ useBR: true }); blocks = document.querySelectorAll('.code'); _.each(blocks, hljs.highlightBlock); done(err); }); }); require('./explicitLanguage'); require('./customMarkup'); require('./languageAlias'); require('./noHighlight'); require('./subLanguages'); require('./buildClassName'); require('./useBr'); });
'use strict'; var _ = require('lodash'); var fs = require('fs'); var hljs = require('../../build'); var jsdom = require('jsdom').jsdom; var utility = require('../utility'); describe('special cases tests', function() { before(function() { var blocks, filename = utility.buildPath('fixtures', 'index.html'), page = fs.readFileSync(filename, 'utf-8'); // Allows hljs to use document global.document = jsdom(page); // Setup hljs environment hljs.configure({ tabReplace: ' ' }); hljs.initHighlighting(); // Setup hljs for non-`<pre><code>` tests hljs.configure({ useBR: true }); blocks = document.querySelectorAll('.code'); _.each(blocks, hljs.highlightBlock); }); require('./explicitLanguage'); require('./customMarkup'); require('./languageAlias'); require('./noHighlight'); require('./subLanguages'); require('./buildClassName'); require('./useBr'); });
Fix broken ME conduit textures
package crazypants.enderio.conduit.me; import net.minecraft.item.ItemStack; import crazypants.enderio.ModObject; import crazypants.enderio.conduit.AbstractItemConduit; import crazypants.enderio.conduit.IConduit; import crazypants.enderio.conduit.ItemConduitSubtype; public class ItemMEConduit extends AbstractItemConduit { private static ItemConduitSubtype[] subtypes = new ItemConduitSubtype[] { new ItemConduitSubtype(ModObject.itemMEConduit.name(), "enderio:itemMeConduit"), }; public static ItemMEConduit create() { ItemMEConduit result = new ItemMEConduit(); result.init(subtypes); return result; } protected ItemMEConduit() { super(ModObject.itemMEConduit); } @Override public Class<? extends IConduit> getBaseConduitType() { return IMEConduit.class; } @Override public IConduit createConduit(ItemStack item) { return new MEConduit(); } }
package crazypants.enderio.conduit.me; import net.minecraft.item.ItemStack; import crazypants.enderio.ModObject; import crazypants.enderio.conduit.AbstractItemConduit; import crazypants.enderio.conduit.IConduit; import crazypants.enderio.conduit.ItemConduitSubtype; public class ItemMEConduit extends AbstractItemConduit { private static ItemConduitSubtype[] subtypes = new ItemConduitSubtype[] { new ItemConduitSubtype(ModObject.itemMEConduit.name(), "enderio:itemMEConduit"), }; public static ItemMEConduit create() { ItemMEConduit result = new ItemMEConduit(); result.init(subtypes); return result; } protected ItemMEConduit() { super(ModObject.itemMEConduit); } @Override public Class<? extends IConduit> getBaseConduitType() { return IMEConduit.class; } @Override public IConduit createConduit(ItemStack item) { return new MEConduit(); } }
Create Hash method to engine.Dot
package engine import "fmt" type Dot struct { X uint8 Y uint8 } // Equals compares two dots func (d1 Dot) Equals(d2 Dot) bool { return d1 == d2 || (d1.X == d2.X && d1.Y == d2.Y) } // Implementing json.Marshaler interface func (d Dot) MarshalJSON() ([]byte, error) { return []byte(fmt.Sprintf("[%d,%d]", d.X, d.Y)), nil } func (d Dot) Hash() string { return string([]byte{d.X, d.Y}) } func (d Dot) String() string { return fmt.Sprintf("[%d, %d]", d.X, d.Y) } // DistanceTo calculates distance between two dots func (from Dot) DistanceTo(to Dot) (res uint16) { if !from.Equals(to) { if from.X > to.X { res = uint16(from.X - to.X) } else { res = uint16(to.X - from.X) } if from.Y > to.Y { res += uint16(from.Y - to.Y) } else { res += uint16(to.Y - from.Y) } } return }
package engine import "fmt" type Dot struct { X uint8 Y uint8 } // Equals compares two dots func (d1 Dot) Equals(d2 Dot) bool { return d1 == d2 || (d1.X == d2.X && d1.Y == d2.Y) } // Implementing json.Marshaler interface func (d Dot) MarshalJSON() ([]byte, error) { return []byte(fmt.Sprintf("[%d,%d]", d.X, d.Y)), nil } func (d Dot) String() string { return fmt.Sprintf("[%d, %d]", d.X, d.Y) } // DistanceTo calculates distance between two dots func (from Dot) DistanceTo(to Dot) (res uint16) { if !from.Equals(to) { if from.X > to.X { res = uint16(from.X - to.X) } else { res = uint16(to.X - from.X) } if from.Y > to.Y { res += uint16(from.Y - to.Y) } else { res += uint16(to.Y - from.Y) } } return }
Fix a typo in description: it's => its
from setuptools import setup setup( name='python-binary-memcached', version='0.24.6', author='Jayson Reis', author_email='santosdosreis@gmail.com', description='A pure python module to access memcached via its binary protocol with SASL auth support', url='https://github.com/jaysonsantos/python-binary-memcached', packages=['bmemcached'], classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', ], install_requires=[ 'six' ] )
from setuptools import setup setup( name='python-binary-memcached', version='0.24.6', author='Jayson Reis', author_email='santosdosreis@gmail.com', description='A pure python module to access memcached via it\'s binary protocol with SASL auth support', url='https://github.com/jaysonsantos/python-binary-memcached', packages=['bmemcached'], classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', ], install_requires=[ 'six' ] )
Add __future__ imports to a new module
# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. """Custom collections classes. """ from __future__ import division, absolute_import, print_function class IdentityFallbackDict(dict): """A dictionary which is "transparent" (maps keys to themselves) for all keys not in it. """ def __getitem__(self, key): try: return dict.__getitem__(self, key) except KeyError: return key
# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. """Custom collections classes """ class IdentityFallbackDict(dict): """A dictionary which is "transparent" (maps keys to themselves) for all keys not in it. """ def __getitem__(self, key): try: return dict.__getitem__(self, key) except KeyError: return key
Add links to header buttons
@extends('_layouts.master') @section('body') <!-- Sticky Header --> <div id="header-placeholder"></div> <header> <div class="header-left"> <a href="http://www.artic.edu/"> <img src="images/logo.svg"> </a> <span class="exhibit"> <span class="title">Gauguin</span> <span class="pipe">|</span> <span class="subtitle">Artist as Alchemist</span> </span> </div> <div class="header-right"> <span class="dates"> <span class="start">June 25</span> <span class="dash">–</span> <span class="end">Sept 10</span> </span> <span class="buttons"> <a class="btn btn-small btn-member" href="https://sales.artic.edu/memberships">Become a Member</a> <a class="btn btn-small btn-ticket" href="https://sales.artic.edu/admissiondate"><span class="verb">Get </span>Tickets</a> </span> </div> </header> @endsection
@extends('_layouts.master') @section('body') <!-- Sticky Header --> <div id="header-placeholder"></div> <header> <div class="header-left"> <a href="http://www.artic.edu/"> <img src="images/logo.svg"> </a> <span class="exhibit"> <span class="title">Gauguin</span> <span class="pipe">|</span> <span class="subtitle">Artist as Alchemist</span> </span> </div> <div class="header-right"> <span class="dates"> <span class="start">June 25</span> <span class="dash">–</span> <span class="end">Sept 10</span> </span> <span class="buttons"> <a class="btn btn-small btn-member" href="#" >Become a Member</a> <a class="btn btn-small btn-ticket" href="#" ><span class="verb">Get </span>Tickets</a> </span> </div> </header> @endsection
Remove ability to recieve messages
from http_client import HttpClient class Bot(): """ @breif Facebook messenger bot """ def __init__(self, token): self.api_token = token self.client = HttpClient() def send_message(self, message, completion): def completion(response, error): if error is None: # TODO: Is there anything the bot needs to do? # maybe retry if it fails...? pass else: completion() self.client.submit_request('/me/messages', 'POST', message.to_json(), completion)
from http_client import HttpClient """ @breif Facebook messenger bot """ class Bot(): def __init__(self, token): self.api_token = token self.client = HttpClient() def send_message(self, message, completion): def completion(response, error): if error is None: # TODO: Is there anything the bot needs to do? # maybe retry if it fails...? pass else: completion() self.client.submit_request('/me/messages', 'POST', message.to_json(), completion) def handle_incoming(): raise NotImplementedError
Stop the bot at the end
package main import ( "fmt" "math/rand" "os" "time" "github.com/erbridge/gotwit" "github.com/erbridge/gotwit/twitter" "github.com/erbridge/wikipaedian/wiki" ) func main() { var ( con twitter.ConsumerConfig acc twitter.AccessConfig ) f := "secrets.json" if _, err := os.Stat(f); err == nil { con, acc, _ = twitter.LoadConfigFile(f) } else { con, acc, _ = twitter.LoadConfigEnv() } b := gotwit.NewBot("wikipaedian", con, acc) go func() { if err := b.Start(); err != nil { panic(err) } }() now := time.Now() rand.Seed(now.UnixNano()) next := time.Date( now.Year(), now.Month(), now.Day(), now.Hour()+1, 0, 0, 0, now.Location(), ) sleep := next.Sub(now) fmt.Printf("%v until first tweet\n", sleep) time.Sleep(sleep) if c, err := wiki.NewClient(&b); err != nil { panic(err) } else { c.Start(1 * time.Hour) } if err := b.Stop(); err != nil { panic(err) } }
package main import ( "fmt" "math/rand" "os" "time" "github.com/erbridge/gotwit" "github.com/erbridge/gotwit/twitter" "github.com/erbridge/wikipaedian/wiki" ) func main() { var ( con twitter.ConsumerConfig acc twitter.AccessConfig ) f := "secrets.json" if _, err := os.Stat(f); err == nil { con, acc, _ = twitter.LoadConfigFile(f) } else { con, acc, _ = twitter.LoadConfigEnv() } b := gotwit.NewBot("wikipaedian", con, acc) go func() { if err := b.Start(); err != nil { panic(err) } }() now := time.Now() rand.Seed(now.UnixNano()) next := time.Date( now.Year(), now.Month(), now.Day(), now.Hour()+1, 0, 0, 0, now.Location(), ) sleep := next.Sub(now) fmt.Printf("%v until first tweet\n", sleep) time.Sleep(sleep) if c, err := wiki.NewClient(&b); err != nil { panic(err) } else { c.Start(1 * time.Hour) } }
Make tests for class cluttering consistent * Remove the extra level of `describe` * use should to begin test names
'use strict'; describe('block class names', function() { it('should add language class name to block', function() { var expected = 'some-class hljs xml', actual = document.getElementById('without-hljs-class').className; actual.should.equal(expected); }); it('should not clutter block class (first)', function () { var expected = 'hljs some-class xml', actual = document.getElementById('with-hljs-class-first').className; actual.should.equal(expected); }); it('should not clutter block class (last)', function () { var expected = 'some-class hljs xml', actual = document.getElementById('with-hljs-class-last').className; actual.should.equal(expected); }); it('should not clutter block class (spaces around)', function () { var expected = 'hljs some-class xml', actual = document.getElementById('with-hljs-class-spaces-around').className; actual.should.equal(expected); }); });
'use strict'; describe('block class names', function() { it('should add language class name to block', function() { var expected = 'some-class hljs xml', actual = document.getElementById('without-hljs-class').className; actual.should.equal(expected); }); describe('do not clutter block class name', function() { it('first', function () { var expected = 'hljs some-class xml', actual = document.getElementById('with-hljs-class-first').className; actual.should.equal(expected); }); it('last', function () { var expected = 'some-class hljs xml', actual = document.getElementById('with-hljs-class-last').className; actual.should.equal(expected); }); it('spaces around', function () { var expected = 'hljs some-class xml', actual = document.getElementById('with-hljs-class-spaces-around').className; actual.should.equal(expected); }); }); });