text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix document.ready function for future Nextcloud versions
/* * Copyright (c) 2017 * * This file is licensed under the Affero General Public License version 3 * or later. * * See the COPYING-README file. * */ (function() { if (!OCA.Weather) { /** * Namespace for the files app * @namespace OCA.Weather */ OCA.Weather = {}; } /** * @namespace OCA.Weather.Admin */ OCA.Weather.Admin = { initialize: function() { $('#submitOWMApiKey').on('click', _.bind(this._onClickSubmitOWMApiKey, this)); }, _onClickSubmitOWMApiKey: function () { OC.msg.startSaving('#OWMApiKeySettingsMsg'); var request = $.ajax({ url: OC.generateUrl('/apps/weather/settings/apikey'), type: 'POST', data: { apikey: $('#openweathermap-api-key').val() } }); request.done(function (data) { $('#openweathermap-api-key').val(data.apikey); OC.msg.finishedSuccess('#OWMApiKeySettingsMsg', 'Saved'); }); request.fail(function () { OC.msg.finishedError('#OWMApiKeySettingsMsg', 'Error'); }); } } })(); window.addEventListener('DOMContentLoaded', function () { OCA.Weather.Admin.initialize(); });
/* * Copyright (c) 2017 * * This file is licensed under the Affero General Public License version 3 * or later. * * See the COPYING-README file. * */ (function() { if (!OCA.Weather) { /** * Namespace for the files app * @namespace OCA.Weather */ OCA.Weather = {}; } /** * @namespace OCA.Weather.Admin */ OCA.Weather.Admin = { initialize: function() { $('#submitOWMApiKey').on('click', _.bind(this._onClickSubmitOWMApiKey, this)); }, _onClickSubmitOWMApiKey: function () { OC.msg.startSaving('#OWMApiKeySettingsMsg'); var request = $.ajax({ url: OC.generateUrl('/apps/weather/settings/apikey'), type: 'POST', data: { apikey: $('#openweathermap-api-key').val() } }); request.done(function (data) { $('#openweathermap-api-key').val(data.apikey); OC.msg.finishedSuccess('#OWMApiKeySettingsMsg', 'Saved'); }); request.fail(function () { OC.msg.finishedError('#OWMApiKeySettingsMsg', 'Error'); }); } } })(); $(document).ready(function() { OCA.Weather.Admin.initialize(); });
Fix for actual windows user agent string
/*! * Module dependencies. */ var useragent = require('useragent'); /** * Parse User-Agent for Cordova Platform. * * Options: * * - `ua` {String} is the server request user-agent header. * - `[jsUA]` {String} is the optional user-agent from the client-side JS. * * Returns: * * - {Object} to describe the platform. * - `ios` {Boolean} true when iOS. * - `android` {Boolean} true when Android. * - `platform` {String} is the platform name (`ios`, `android`, etc). */ module.exports.parse = function() { var agent = useragent.parse.apply(useragent, arguments), browser = agent.toAgent(), platform = {}; // find the user-agent's platform platform = { android: /Android/i.test(browser), ios: /Mobile Safari/i.test(browser), windows: /IE Mobile/i.test(browser), platform: 'unknown' }; // .platform is the stringified platform name for (var key in platform) { if (platform[key]) { platform.platform = key; break; } } return platform; };
/*! * Module dependencies. */ var useragent = require('useragent'); /** * Parse User-Agent for Cordova Platform. * * Options: * * - `ua` {String} is the server request user-agent header. * - `[jsUA]` {String} is the optional user-agent from the client-side JS. * * Returns: * * - {Object} to describe the platform. * - `ios` {Boolean} true when iOS. * - `android` {Boolean} true when Android. * - `platform` {String} is the platform name (`ios`, `android`, etc). */ module.exports.parse = function() { var agent = useragent.parse.apply(useragent, arguments), browser = agent.toAgent(), platform = {}; // find the user-agent's platform platform = { android: /Android/i.test(browser), ios: /Mobile Safari/i.test(browser), windows: /Windows Phone/i.test(browser), platform: 'unknown' }; // .platform is the stringified platform name for (var key in platform) { if (platform[key]) { platform.platform = key; break; } } return platform; };
Remove the initial value for WebHookTarget.extra_data in the evolution. The original evolution adding the WebHookTarget.extra_data had an initial value, and even with changing that in another field, it will still apply on existing installs. This needs to be modified in order to allow installation on MySQL.
from django_evolution.mutations import AddField, RenameField from django.db import models from djblets.db.fields import JSONField MUTATIONS = [ AddField('WebHookTarget', 'encoding', models.CharField, initial='application/json', max_length=40), AddField('WebHookTarget', 'repositories', models.ManyToManyField, null=True, related_model='scmtools.Repository'), AddField('WebHookTarget', 'custom_content', models.TextField, null=True), AddField('WebHookTarget', 'use_custom_content', models.BooleanField, initial=False), AddField('WebHookTarget', 'apply_to', models.CharField, initial='A', max_length=1), AddField('WebHookTarget', 'extra_data', JSONField, initial=None), RenameField('WebHookTarget', 'handlers', 'events'), ]
from django_evolution.mutations import AddField, RenameField from django.db import models from djblets.db.fields import JSONField MUTATIONS = [ AddField('WebHookTarget', 'encoding', models.CharField, initial='application/json', max_length=40), AddField('WebHookTarget', 'repositories', models.ManyToManyField, null=True, related_model='scmtools.Repository'), AddField('WebHookTarget', 'custom_content', models.TextField, null=True), AddField('WebHookTarget', 'use_custom_content', models.BooleanField, initial=False), AddField('WebHookTarget', 'apply_to', models.CharField, initial='A', max_length=1), AddField('WebHookTarget', 'extra_data', JSONField, initial='{}'), RenameField('WebHookTarget', 'handlers', 'events'), ]
Fix createInitialQuotes guard clause issue
package io.github.jordao76.quotes; import java.util.*; import org.springframework.boot.*; import org.springframework.boot.autoconfigure.*; import org.springframework.context.annotation.*; import io.github.jordao76.quotes.domain.*; @SpringBootApplication public class QuoteApplication { public static void main(String[] args) { SpringApplication.run(QuoteApplication.class, args); } @Bean public CommandLineRunner createInitialQuotes(QuoteRepository repo) { return (args) -> { if (repo.count() > 0) return; repo.save(Arrays.asList( new Quote( "Any sufficiently advanced technology is indistinguishable from magic.", "Arthur C. Clarke"), new Quote( "Perfection (in design) is achieved not when there is nothing more to add, but rather when there is nothing more to take away.", "Antoine de Saint-Exupery"), new Quote( "On two occasions I have been asked, 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out?' I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question.", "Charles Babbage"))); }; } }
package io.github.jordao76.quotes; import java.util.*; import org.springframework.boot.*; import org.springframework.boot.autoconfigure.*; import org.springframework.context.annotation.*; import io.github.jordao76.quotes.domain.*; @SpringBootApplication public class QuoteApplication { public static void main(String[] args) { SpringApplication.run(QuoteApplication.class, args); } @Bean public CommandLineRunner createInitialQuotes(QuoteRepository repo) { return (args) -> { if (repo.count() < 0) return; repo.save(Arrays.asList( new Quote( "Any sufficiently advanced technology is indistinguishable from magic.", "Arthur C. Clarke"), new Quote( "Perfection (in design) is achieved not when there is nothing more to add, but rather when there is nothing more to take away.", "Antoine de Saint-Exupery"), new Quote( "On two occasions I have been asked, 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out?' I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question.", "Charles Babbage"))); }; } }
Set up `process.env` for development build Looks like React will fail without this as it cannot find `process.env`.
'use strict'; var extend = require('xtend'); var webpack = require('webpack'); var common = require('./webpack.common'); module.exports = extend(common, { devtool: 'eval', entry: [ 'webpack-dev-server/client?http://0.0.0.0:3000', 'webpack/hot/only-dev-server', './demos/index', ], output: { path: __dirname, filename: 'bundle.js', publicPath: '/demos/' }, plugins: [ new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('development'), } }), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), ], module: { loaders: common.loaders.concat([{ test: /\.jsx?$/, loaders: ['react-hot', 'jsx-loader?harmony'], }]) } });
'use strict'; var extend = require('xtend'); var webpack = require('webpack'); var common = require('./webpack.common'); module.exports = extend(common, { devtool: 'eval', entry: [ 'webpack-dev-server/client?http://0.0.0.0:3000', 'webpack/hot/only-dev-server', './demos/index', ], output: { path: __dirname, filename: 'bundle.js', publicPath: '/demos/' }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), ], module: { loaders: common.loaders.concat([{ test: /\.jsx?$/, loaders: ['react-hot', 'jsx-loader?harmony'], }]) } });
Fix hero for only supported size
import React, { Component, PropTypes } from 'react'; import s from './Hero.css'; export default class Hero extends Component { render() { const { className, children, size, ...remainingProps, } = this.props; const classNames = [ s.root, s ? s[s] : null, size ? s[size] : null, className, ].join(' '); return ( <div className={classNames} {...remainingProps} > {children} </div> )} }; Hero.propTypes = { children: PropTypes.any, className: PropTypes.string, size: PropTypes.oneOf([ 'full', ]), };
import React, { Component, PropTypes } from 'react'; import s from './Hero.css'; export default class Hero extends Component { render() { const { className, children, size, ...remainingProps, } = this.props; const classNames = [ s.root, s ? s[s] : null, size ? s[size] : null, className, ].join(' '); return ( <div className={classNames} {...remainingProps} > {children} </div> )} }; Hero.propTypes = { children: PropTypes.any, className: PropTypes.string, size: PropTypes.oneOf([ 'large', ]), };
Fix deprecations on PHP 8.2
<?php namespace Symfony\Component\Serializer\Tests\Normalizer\Features; #[\AllowDynamicProperties] class ObjectDummy { protected $foo; /** * @var array */ public $bar; private $baz; protected $camelCase; protected $object; public function getFoo() { return $this->foo; } public function setFoo($foo) { $this->foo = $foo; } public function isBaz() { return $this->baz; } public function setBaz($baz) { $this->baz = $baz; } public function getFooBar() { return $this->foo.$this->bar; } public function getCamelCase() { return $this->camelCase; } public function setCamelCase($camelCase) { $this->camelCase = $camelCase; } public function otherMethod() { throw new \RuntimeException('Dummy::otherMethod() should not be called'); } public function setObject($object) { $this->object = $object; } public function getObject() { return $this->object; } }
<?php namespace Symfony\Component\Serializer\Tests\Normalizer\Features; class ObjectDummy { protected $foo; /** * @var array */ public $bar; private $baz; protected $camelCase; protected $object; public function getFoo() { return $this->foo; } public function setFoo($foo) { $this->foo = $foo; } public function isBaz() { return $this->baz; } public function setBaz($baz) { $this->baz = $baz; } public function getFooBar() { return $this->foo.$this->bar; } public function getCamelCase() { return $this->camelCase; } public function setCamelCase($camelCase) { $this->camelCase = $camelCase; } public function otherMethod() { throw new \RuntimeException('Dummy::otherMethod() should not be called'); } public function setObject($object) { $this->object = $object; } public function getObject() { return $this->object; } }
:new: Use iterator instead of forEach
'use strict' /* @flow */ import type {Disposable} from './disposable' export class CompositeDisposable { disposed: boolean; disposables: Set<Disposable>; constructor(){ this.disposed = false this.disposables = new Set(arguments) } add(){ if (!this.disposed) { let length = arguments.length for (let i = 0; i < length; ++i) { this.disposables.add(arguments[i]) } } } remove(){ if (!this.disposed) { let length = arguments.length for (let i = 0; i < length; ++i) { this.disposables.delete(arguments[i]) } } } clear(){ if (!this.disposed) { this.disposables.clear() } } isDisposed(): boolean { return this.disposed } dispose(){ if (!this.disposed) { for (const item of this.disposables) { item.dispose() } this.disposed = true this.disposables.clear() } } }
'use strict' /* @flow */ import type {Disposable} from './disposable' export class CompositeDisposable { disposed: boolean; disposables: Set<Disposable>; constructor(){ this.disposed = false this.disposables = new Set(arguments) } add(){ if (!this.disposed) { let length = arguments.length for (let i = 0; i < length; ++i) { this.disposables.add(arguments[i]) } } } remove(){ if (!this.disposed) { let length = arguments.length for (let i = 0; i < length; ++i) { this.disposables.delete(arguments[i]) } } } clear(){ if (!this.disposed) { this.disposables.clear() } } isDisposed(): boolean { return this.disposed } dispose(){ if (!this.disposed) { this.disposed = true this.disposables.forEach(function(item) { item.dispose() }) this.disposables.clear() } } }
Make sure only strings are returned for HTTP headers
import random import os import time import struct import binascii import sys if sys.version_info.major is 2: string_types = basestring else: string_types = str _rnd = random.Random() _current_pid = 0 def generate_id(): """ Generate a 64bit signed integer for use as a Span or Trace ID """ global _current_pid pid = os.getpid() if (_current_pid != pid): _current_pid = pid _rnd.seed(int(1000000 * time.time()) ^ pid) return _rnd.randint(-9223372036854775808, 9223372036854775807) def id_to_header(id): """ Convert a 64bit signed integer to an unsigned base 16 hex string """ if not isinstance(id, int): return "" byteString = struct.pack('>q', id) return str(binascii.hexlify(byteString).decode('UTF-8').lstrip('0')) def header_to_id(header): """ Convert an unsigned base 16 hex string into a 64bit signed integer """ if not isinstance(header, string_types): return 0 # Pad the header to 16 chars header = header.zfill(16) r = binascii.unhexlify(header) return struct.unpack('>q', r)[0]
import random import os import time import struct import binascii import sys if sys.version_info.major is 2: string_types = basestring else: string_types = str _rnd = random.Random() _current_pid = 0 def generate_id(): """ Generate a 64bit signed integer for use as a Span or Trace ID """ global _current_pid pid = os.getpid() if (_current_pid != pid): _current_pid = pid _rnd.seed(int(1000000 * time.time()) ^ pid) return _rnd.randint(-9223372036854775808, 9223372036854775807) def id_to_header(id): """ Convert a 64bit signed integer to an unsigned base 16 hex string """ if not isinstance(id, int): return "" byteString = struct.pack('>q', id) return binascii.hexlify(byteString).decode('UTF-8').lstrip('0') def header_to_id(header): """ Convert an unsigned base 16 hex string into a 64bit signed integer """ if not isinstance(header, string_types): return 0 # Pad the header to 16 chars header = header.zfill(16) r = binascii.unhexlify(header) return struct.unpack('>q', r)[0]
Revert "point more info link to mailto" This reverts commit b49158110562840fc2fa7400abefb80f3f2eaa09.
// Page modules var FastClick = require('fastclick') var nav = require('./nav.js') var socialShare = require('./social-share') var analytics = require('./analytics') nav.init() analytics.init() FastClick.attach(document.body) // Load and process data require.ensure(['./api', './get-api-data', './template-render', 'spin.js', 'lodash'], function (require) { var apiRoutes = require('./api') var getApiData = require('./get-api-data') var templating = require('./template-render') var Spinner = require('spin.js') var _ = require('lodash') // Spinner var spin = document.getElementById('spin') var loading = new Spinner().spin(spin) // Get API data using promise getApiData.data(apiRoutes.needs) .then(function (result) { var needsFromApi = result.data _.each(needsFromApi, function(need) { need.link = "give-item-submit-details.html?needId=" + need.id }) var theData = { 'needs': needsFromApi } var callback = function () { loading.stop() socialShare.init() } templating.renderTemplate('js-need-list-tpl', theData, 'js-need-list-output', callback) }) })
// Page modules var FastClick = require('fastclick') var nav = require('./nav.js') var socialShare = require('./social-share') var analytics = require('./analytics') nav.init() analytics.init() FastClick.attach(document.body) // Load and process data require.ensure(['./api', './get-api-data', './template-render', 'spin.js', 'lodash'], function (require) { var apiRoutes = require('./api') var getApiData = require('./get-api-data') var templating = require('./template-render') var Spinner = require('spin.js') var _ = require('lodash') // Spinner var spin = document.getElementById('spin') var loading = new Spinner().spin(spin) // Get API data using promise getApiData.data(apiRoutes.needs) .then(function (result) { var needsFromApi = result.data _.each(needsFromApi, function(need) { need.link = "mailto:givehelp@streetsupport.net?subject=" + need.serviceProviderId + " need: " + need.description }) var theData = { 'needs': needsFromApi } var callback = function () { loading.stop() socialShare.init() } templating.renderTemplate('js-need-list-tpl', theData, 'js-need-list-output', callback) }) })
Replace config load callback wrapper
'use strict'; const readConfig = require('restore-server-config'); // singleton let config; /** * Loads the configuration and stores it in the config singleton. * @param {string} baseDir Directory which contains the folder cfg with the config files. * @param [Logger] logger */ function load(baseDir, logger) { return (cb) => { readConfig(baseDir, logger, (err, cfg) => { if (err) { cb(err, cfg); } else { config = cfg; cb(null, cfg); } }); }; } /** * Get config from singleton. * If singelton is undefined load id from current working directory. * @param [Logger] logger * @return {Object} nconf configuration object */ module.exports.get = function* get(logger) { if (config) { return config; } yield load(process.cwd(), logger); return config; }; module.exports.load = load;
'use strict'; const readConfig = require('restore-server-config'); // singleton let config; /** * Loads the configuration and stores it in the config singleton. * @param {string} baseDir Directory which contains the folder cfg with the config files. * @param [Logger] logger */ function load(baseDir, logger) { return (cb) => { readConfig(baseDir, logger, (cfg) => { config = cfg; cb(null, cfg); }); }; } /** * Get config from singleton. * If singelton is undefined load id from current working directory. * @param [Logger] logger * @return {Object} nconf configuration object */ module.exports.get = function* get(logger) { if (config) { return config; } yield load(process.cwd(), logger); return config; }; module.exports.load = load;
Fix HTMLParser compatibility in Python 3
# -*- coding: utf-8 -*- """ coop_cms manage compatibilty with django and python versions """ import sys from django import VERSION if sys.version_info[0] < 3: # Python 2 from StringIO import StringIO from HTMLParser import HTMLParser else: # Python 3 from io import BytesIO as StringIO from html.parser import HTMLParser as BaseHTMLParser class HTMLParser(BaseHTMLParser): def __init__(self): BaseHTMLParser.__init__(self, convert_charrefs=False) try: from django.utils.deprecation import MiddlewareMixin except ImportError: MiddlewareMixin = object if VERSION >= (1, 9, 0): from wsgiref.util import FileWrapper else: from django.core.servers.basehttp import FileWrapper if VERSION >= (1, 8, 0): from unittest import SkipTest else: # Deprecated in Django 1.9 from django.utils.unittest import SkipTest def make_context(request, context_dict): """""" if VERSION >= (1, 9, 0): context = dict(context_dict) if request: context['request'] = request else: from django.template import RequestContext, Context if request: context = RequestContext(request, context_dict) else: context = Context(context_dict) return context
# -*- coding: utf-8 -*- """ coop_cms manage compatibilty with django and python versions """ import sys from django import VERSION if sys.version_info[0] < 3: # Python 2 from HTMLParser import HTMLParser from StringIO import StringIO else: # Python 3 from html.parser import HTMLParser from io import BytesIO as StringIO try: from django.utils.deprecation import MiddlewareMixin except ImportError: MiddlewareMixin = object if VERSION >= (1, 9, 0): from wsgiref.util import FileWrapper else: from django.core.servers.basehttp import FileWrapper if VERSION >= (1, 8, 0): from unittest import SkipTest else: # Deprecated in Django 1.9 from django.utils.unittest import SkipTest def make_context(request, context_dict): """""" if VERSION >= (1, 9, 0): context = dict(context_dict) if request: context['request'] = request else: from django.template import RequestContext, Context if request: context = RequestContext(request, context_dict) else: context = Context(context_dict) return context
Fix articles schema {uri} -> {source: uri}
import React from 'react' import Question from './question' import Article from './article' import fetch from 'isomorphic-fetch' class ArticleList extends React.Component { constructor (props) { super(props) this.state = { articles: [ { id: 0, title: 'Example article', source: { uri: 'http://localhost' } } ] } } componentWillMount () { fetch('/backend') .then(response => response.json()) .then(articles => this.setState({articles})) } render () { const articles = this.state.articles.map(({id, title, source}) => <Article key={id} title={title} link={source.uri} /> ) return ( <div> <Question title='Describa el flujo migratorio de talento en el mundo' /> <h3 className='h6 my-4 text-muted'> Artículos propuestos para responder a la pregunta </h3> <main> {articles} </main> </div> ) } } export default ArticleList
import React from 'react' import Question from './question' import Article from './article' import fetch from 'isomorphic-fetch' class ArticleList extends React.Component { constructor (props) { super(props) this.state = { articles: [ { id: 0, title: 'Example article', uri: 'http://localhost' } ] } } componentWillMount () { fetch('/backend') .then(response => response.json()) .then(articles => this.setState({articles})) } render () { const articles = this.state.articles.map(({id, title, uri}) => <Article key={id} title={title} uri={uri} /> ) return ( <div> <Question title='Describa el flujo migratorio de talento en el mundo' /> <h3 className='h6 my-4 text-muted'> Artículos propuestos para responder a la pregunta </h3> <main> {articles} </main> </div> ) } } export default ArticleList
Add Method the return time now in complete UTC iso complete format
from datetime import datetime import time """Helper functions Consists of functions to typically be used within templates, but also available to Controllers. This module is available to templates as 'h'. """ # Import helpers as desired, or define your own, ie: #from webhelpers.html.tags import checkbox, password def importModuleFromFile(fullpath): """Loads and returns module defined by the file path. Returns None if file could not be loaded""" import os import sys import logging log = logging.getLogger(__name__) sys.path.append(os.path.dirname(fullpath)) module = None try: module = __import__(os.path.splitext(os.path.basename(fullpath))[0]) except Exception as ex: log.exception("Failed to load module:\n"+ex) finally: del sys.path[-1] return module def convertToISO8601UTC (dateTimeArg=None): if isinstance(dateTimeArg, datetime) == True: return datetime.utcfromtimestamp(time.mktime(dateTimeArg.timetuple())) return dateTimeArg def convertToISO8601Zformat(dateTimeArg=None): if isinstance(dateTimeArg, datetime) ==True: return convertToISO8601UTC (dateTimeArg).isoformat()+ "Z" return dateTimeArg def nowToISO8601Zformat(): return convertToISO8601Zformat(datetime.now())
"""Helper functions Consists of functions to typically be used within templates, but also available to Controllers. This module is available to templates as 'h'. """ # Import helpers as desired, or define your own, ie: #from webhelpers.html.tags import checkbox, password def importModuleFromFile(fullpath): """Loads and returns module defined by the file path. Returns None if file could not be loaded""" import os import sys import logging log = logging.getLogger(__name__) sys.path.append(os.path.dirname(fullpath)) module = None try: module = __import__(os.path.splitext(os.path.basename(fullpath))[0]) except Exception as ex: log.exception("Failed to load module:\n"+ex) finally: del sys.path[-1] return module def convertToISO8601UTC (datetime=None): if datetime != None: return (datetime - datetime.utcoffset()).replace(tzinfo=None) return datetime def convertToISO8601Zformat(datetime=None): if datetime != None: return ((datetime - datetime.utcoffset()).replace(tzinfo=None)).isoformat() + "Z" return datetime
Remove useless events that don't exist
import Ember from 'ember'; import jquiWidget from 'ember-cli-jquery-ui/mixins/jqui-widget'; export default Ember.TextField.extend(jquiWidget, { uiType: 'datepicker', uiOptions: ["altField", "altFormat", "appendText", "autoSize", "beforeShow", "beforeShowDay", "buttonImage", "buttonImageOnly", "buttonText", "calculateWeek", "changeMonth", "changeYear", "closeText", "constrainInput", "currentText", "dateFormat", "dayNames", "dayNamesMin", "dayNamesShort", "defaultDate", "duration", "firstDay", "gotoCurrent", "hideIfNoPrevNext", "isRTL", "maxDate", "minDate", "monthNames", "monthNamesShort", "navigationAsDateFormat", "nextText", "numberOfMonths", "onChangeMonthYear", "onClose", "onSelect", "prevText", "selectOtherMonths", "shortYearCutoff", "showAnim", "showButtonPanel", "showCurrentAtPos", "showMonthAfterYear", "showOn", "showOptions", "showOtherMonths", "showWeek", "stepMonths", "weekHeader", "yearRange", "yearSuffix"] });
import Ember from 'ember'; import jquiWidget from 'ember-cli-jquery-ui/mixins/jqui-widget'; export default Ember.TextField.extend(jquiWidget, { uiType: 'datepicker', uiOptions: ["altField", "altFormat", "appendText", "autoSize", "beforeShow", "beforeShowDay", "buttonImage", "buttonImageOnly", "buttonText", "calculateWeek", "changeMonth", "changeYear", "closeText", "constrainInput", "currentText", "dateFormat", "dayNames", "dayNamesMin", "dayNamesShort", "defaultDate", "duration", "firstDay", "gotoCurrent", "hideIfNoPrevNext", "isRTL", "maxDate", "minDate", "monthNames", "monthNamesShort", "navigationAsDateFormat", "nextText", "numberOfMonths", "onChangeMonthYear", "onClose", "onSelect", "prevText", "selectOtherMonths", "shortYearCutoff", "showAnim", "showButtonPanel", "showCurrentAtPos", "showMonthAfterYear", "showOn", "showOptions", "showOtherMonths", "showWeek", "stepMonths", "weekHeader", "yearRange", "yearSuffix"], uiEvents: ['onChangeMonthYear', 'onClose', 'onSelect'] });
Remove unused success and use "Error" object
package sphere import ( "bytes" "encoding/gob" "encoding/json" "errors" ) // Packet indicates the data of the message type Packet struct { Type PacketType `json:"type"` Namespace string `json:"namespace,omitempty"` Room string `json:"room,omitempty"` Cid int `json:"cid,omitempty"` Rid int `json:"rid,omitempty"` Error *Error `json:"error,omitempty"` Message *Message `json:"message,omitempty"` Machine string `json:"-"` } // ParsePacket returns Packet from bytes func ParsePacket(data []byte) (*Packet, error) { var p *Packet if err := json.Unmarshal(data, &p); err != nil { return nil, errors.New("packet format is invalid") } return p, nil } // Packet.toJSON returns json byte array from Packet func (p *Packet) toJSON() ([]byte, error) { return json.Marshal(p) } // Packet.toBytes returns byte array from Packet func (p *Packet) toBytes() ([]byte, error) { var buf bytes.Buffer enc := gob.NewEncoder(&buf) err := enc.Encode(p) if err != nil { return nil, err } return buf.Bytes(), nil }
package sphere import ( "bytes" "encoding/gob" "encoding/json" "errors" ) // Packet indicates the data of the message type Packet struct { Success bool `json:"success"` Type PacketType `json:"type"` Channel string `json:"channel,omitempty"` Cid int `json:"cid,omitempty"` Rid int `json:"rid,omitempty"` Error error `json:"error,omitempty"` Message *Message `json:"message,omitempty"` } // ParsePacket returns Packet from bytes func ParsePacket(data []byte) (*Packet, error) { var p *Packet if err := json.Unmarshal(data, &p); err != nil { return nil, errors.New("packet format is invalid") } return p, nil } // Packet.toJSON returns json byte array from Packet func (p *Packet) toJSON() ([]byte, error) { return json.Marshal(p) } // Packet.toBytes returns byte array from Packet func (p *Packet) toBytes() ([]byte, error) { var buf bytes.Buffer enc := gob.NewEncoder(&buf) err := enc.Encode(p) if err != nil { return nil, err } return buf.Bytes(), nil }
Add timeout to all tests
# -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # """ File for running tests programmatically. """ # Third party imports import pytest def main(): """ Run pytest tests. """ errno = pytest.main(['-x', 'spyder_terminal', '-v', '-rw', '--durations=10', '--cov=spyder_terminal', '--cov-report=term-missing', '--timeout=30']) # sys.exit doesn't work here because some things could be running # in the background (e.g. closing the main window) when this point # is reached. And if that's the case, sys.exit does't stop the # script (as you would expected). if errno != 0: raise SystemExit(errno) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # """ File for running tests programmatically. """ # Third party imports import pytest def main(): """ Run pytest tests. """ errno = pytest.main(['-x', 'spyder_terminal', '-v', '-rw', '--durations=10', '--cov=spyder_terminal', '--cov-report=term-missing', '--timeout=20']) # sys.exit doesn't work here because some things could be running # in the background (e.g. closing the main window) when this point # is reached. And if that's the case, sys.exit does't stop the # script (as you would expected). if errno != 0: raise SystemExit(errno) if __name__ == '__main__': main()
Update data source to 2016 feed
angular.module('F1FeederApp.services', []) .factory('ergastAPIservice', function($http) { var ergastAPI = {}; ergastAPI.getDrivers = function() { return $http({ method: 'JSONP', url: 'http://ergast.com/api/f1/2016/driverStandings.json?callback=JSON_CALLBACK' }); } ergastAPI.getDriverDetails = function(id) { return $http({ method: 'JSONP', url: 'http://ergast.com/api/f1/2016/drivers/'+ id +'/driverStandings.json?callback=JSON_CALLBACK' }); } ergastAPI.getDriverRaces = function(id) { return $http({ method: 'JSONP', url: 'http://ergast.com/api/f1/2016/drivers/'+ id +'/results.json?callback=JSON_CALLBACK' }); } return ergastAPI; });
angular.module('F1FeederApp.services', []) .factory('ergastAPIservice', function($http) { var ergastAPI = {}; ergastAPI.getDrivers = function() { return $http({ method: 'JSONP', url: 'http://ergast.com/api/f1/2013/driverStandings.json?callback=JSON_CALLBACK' }); } ergastAPI.getDriverDetails = function(id) { return $http({ method: 'JSONP', url: 'http://ergast.com/api/f1/2013/drivers/'+ id +'/driverStandings.json?callback=JSON_CALLBACK' }); } ergastAPI.getDriverRaces = function(id) { return $http({ method: 'JSONP', url: 'http://ergast.com/api/f1/2013/drivers/'+ id +'/results.json?callback=JSON_CALLBACK' }); } return ergastAPI; });
Allow direct linking to cities
// 404 page using mapbox to show cities around the world. // Helper to generate the kind of coordinate pairs I'm using to store cities function bounds() { var center = map.getCenter(); return {lat: center.lat, lng: center.lng, zoom: map.getZoom()}; } L.mapbox.accessToken = "pk.eyJ1IjoiY29udHJvdmVyc2lhbCIsImEiOiJjaXMwaXEwYjUwM2l6MnpwOHdodTh6Y24xIn0.JOD0uX_n_KXqhJ7ERnK0Lg"; var map = L.mapbox.map("map", "mapbox.pencil", {zoomControl: false}); function go(city) { var placenames = Object.keys(places); city = city || placenames[Math.floor(Math.random() * placenames.length)]; var pos = places[city]; map.setView( [pos.lat, pos.lng], pos.zoom ); } if (places[window.location.search.substring(1)]) { go(window.location.search.substring(1)); } else { go(); }
// 404 page using mapbox to show cities around the world. // Helper to generate the kind of coordinate pairs I'm using to store cities function bounds() { var center = map.getCenter(); return {lat: center.lat, lng: center.lng, zoom: map.getZoom()}; } L.mapbox.accessToken = "pk.eyJ1IjoiY29udHJvdmVyc2lhbCIsImEiOiJjaXMwaXEwYjUwM2l6MnpwOHdodTh6Y24xIn0.JOD0uX_n_KXqhJ7ERnK0Lg"; var map = L.mapbox.map("map", "mapbox.pencil", {zoomControl: false}); function go(city) { var placenames = Object.keys(places); city = city || placenames[Math.floor(Math.random() * placenames.length)]; var pos = places[city]; map.setView( [pos.lat, pos.lng], pos.zoom ); } go();
Refactor using functions and a list comprehension
import sublime, sublime_plugin class SumCommand(sublime_plugin.TextCommand): def run(self, edit): sum_view = self.view.window().new_file() sum_view.set_name('Sum') file_text = self.view.substr(sublime.Region(0, self.view.size())) numbers = [to_number(s) for s in file_text.split() if is_number(s)] result = sum(numbers) sum_view.insert(edit, 0, str(result)) sum_view.set_read_only(True) sum_view.set_scratch(True) def is_int(s): """Return boolean indicating whether a string can be parsed to an int.""" try: int(s) return True except ValueError: return False def is_float(s): """Return boolean indicating whether a string can be parsed to an float.""" try: float(s) return True except ValueError: return False def is_number(s): """Return boolean indicating whether a string can be parsed to an int or float.""" return is_int(s) or is_float(s) def to_number(s): """ Parse and return number from string. Return float only if number is not an int. Assume number can be parsed from string. """ try: return int(s) except ValueError: return float(s)
import sublime, sublime_plugin class SumCommand(sublime_plugin.TextCommand): def run(self, edit): sum_view = self.view.window().new_file() sum_view.set_name('Sum') file_text = self.view.substr(sublime.Region(0, self.view.size())) numbers = [] for s in file_text.split(): try: numbers.append(int(s)) except ValueError: try: numbers.append(float(s)) except ValueError: pass result = sum(numbers) sum_view.insert(edit, 0, str(result)) sum_view.set_read_only(True) sum_view.set_scratch(True)
Add mutex on codecs map
package kafka import "sync" var codecs = make(map[int8]CompressionCodec) var codecsMutex sync.RWMutex // RegisterCompressionCodec registers a compression codec so it can be used by a Writer. func RegisterCompressionCodec(codec func() CompressionCodec) { c := codec() codecsMutex.Lock() codecs[c.Code()] = c codecsMutex.Unlock() } // CompressionCodec represents a compression codec to encode and decode // the messages. // See : https://cwiki.apache.org/confluence/display/KAFKA/Compression type CompressionCodec interface { // Code returns the compression codec code Code() int8 // Encode encodes the src data and writes the result to dst. // If ths destination buffer is too small, the function should // return the bytes.ErrToolarge error. Encode(dst, src []byte) (int, error) // Decode decodes the src data and writes the result to dst. // If ths destination buffer is too small, the function should // return the bytes.ErrToolarge error. Decode(dst, src []byte) (int, error) } const compressionCodecMask int8 = 0x03 const DefaultCompressionLevel int = -1 const CompressionNoneCode = 0
package kafka var codecs = make(map[int8]CompressionCodec) // RegisterCompressionCodec registers a compression codec so it can be used by a Writer. func RegisterCompressionCodec(codec func() CompressionCodec) { c := codec() codecs[c.Code()] = c } // CompressionCodec represents a compression codec to encode and decode // the messages. // See : https://cwiki.apache.org/confluence/display/KAFKA/Compression type CompressionCodec interface { // Code returns the compression codec code Code() int8 // Encode encodes the src data and writes the result to dst. // If ths destination buffer is too small, the function should // return the bytes.ErrToolarge error. Encode(dst, src []byte) (int, error) // Decode decodes the src data and writes the result to dst. // If ths destination buffer is too small, the function should // return the bytes.ErrToolarge error. Decode(dst, src []byte) (int, error) } const compressionCodecMask int8 = 0x03 const DefaultCompressionLevel int = -1 const CompressionNoneCode = 0
Decrease the slerp increment for dramatic effect
var THREE = require('three'), raf = require('raf-component'); module.exports = function camera (cam) { var cameraPosition = cam.position.clone(), cameraLookAt = new THREE.Vector3(0, 20000, 0); update(); return { moveCamera: function (x, y, z) { cameraPosition.set(x, y, z); }, lookTo: function (x, y, z) { cameraLookAt.set(x, y, z); } }; function update () { raf(update); cam.position.lerp(cameraPosition, 0.01); var targetMat = new THREE.Matrix4(); targetMat.lookAt(cam.position, cameraLookAt, cam.up); var targetQuat = new THREE.Quaternion(); targetQuat.setFromRotationMatrix(targetMat); cam.quaternion.slerp(targetQuat, 0.01); } };
var THREE = require('three'), raf = require('raf-component'); module.exports = function camera (cam) { var cameraPosition = cam.position.clone(), cameraLookAt = new THREE.Vector3(0, 20000, 0); update(); return { moveCamera: function (x, y, z) { cameraPosition.set(x, y, z); }, lookTo: function (x, y, z) { cameraLookAt.set(x, y, z); } }; function update () { raf(update); cam.position.lerp(cameraPosition, 0.01); var targetMat = new THREE.Matrix4(); targetMat.lookAt(cam.position, cameraLookAt, cam.up); var targetQuat = new THREE.Quaternion(); targetQuat.setFromRotationMatrix(targetMat); cam.quaternion.slerp(targetQuat, 0.07); } };
Add a quick little newline.
#!/bin/env python # -*- coding: utf8 -*- from setuptools import setup setup( name='fedimg', version='0.0.1', description='Service to automatically upload built Fedora images \ to internal and external cloud providers.', classifiers=[ "Programming Language :: Python :: 2", "License :: OSI Approved :: GNU Affero General Public License \ v3 or later (AGPLv3+)", ] keywords='python Fedora cloud image uploader', author='David Gay', author_email='oddshocks@riseup.net', url='https://github.com/oddshocks/fedimg', license='AGPLv3+', include_package_data=True, zip_safe=False, install_requires=["fedmsg"], packages=[], entry_points=""" [moksha.consumer] fedimg = fedimg:FedImg """, )
#!/bin/env python # -*- coding: utf8 -*- from setuptools import setup setup( name='fedimg', version='0.0.1', description='Service to automatically upload built Fedora images \ to internal and external cloud providers.', classifiers=[ "Programming Language :: Python :: 2", "License :: OSI Approved :: GNU Affero General Public License \ v3 or later (AGPLv3+)", ] keywords='python Fedora cloud image uploader', author='David Gay', author_email='oddshocks@riseup.net', url='https://github.com/oddshocks/fedimg', license='AGPLv3+', include_package_data=True, zip_safe=False, install_requires=["fedmsg"], packages=[], entry_points=""" [moksha.consumer] fedimg = fedimg:FedImg """, )
Fix a bug with bad names used as query selectors.
/** * Utility functions. */ function serializeToJSON(arr) { // Convert form data to a proper json value var json = {}; $.each(arr, function(_, pair){ json[pair.name] = pair.value; }); return json; } function guid() { // Credit: http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } function normalizeName(name) { return 'id_' + name.replace(/#/gi, '').replace(/\./gi, '').replace(/ /gi, '_'); }
/** * Utility functions. */ function serializeToJSON(arr) { // Convert form data to a proper json value var json = {}; $.each(arr, function(_, pair){ json[pair.name] = pair.value; }); return json; } function guid() { // Credit: http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } function normalizeName(name) { return name.replace(/#/gi, '').replace(/\./gi, '').replace(/ /gi, '_'); }
Fix error cause by payment number
/** * Created by Wayne on 16/3/11. */ 'use strict'; var newTenderService = require('../../../libraries/services/new_tender_payment'), fs = require('fs'); exports.examine = function (req, res, next) { var tender = req.tender; var user = req.user; newTenderService.examine(tender, user, function (err, result) { return res.send(err || result); }); }; exports.payment = function (req, res, next) { var tender = req.tender; var user = req.user; if (!req.body.type) { return res.send({err: {type: 'empty_type'}}); } if (!req.body.number) { return res.send({err: {type: 'empty_number'}}); } if (isNaN(parseInt(req.body.number)) || parseInt(req.body.number) < 0) { return res.send({err: {type: 'invalid_number'}}); } newTenderService.payment(tender, user, req.body.type, req.body.number, function (err, result) { return res.send(err || result); }); };
/** * Created by Wayne on 16/3/11. */ 'use strict'; var newTenderService = require('../../../libraries/services/new_tender_payment'), fs = require('fs'); exports.examine = function (req, res, next) { var tender = req.tender; var user = req.user; newTenderService.examine(tender, user, function (err, result) { return res.send(err || result); }); }; exports.payment = function (req, res, next) { var tender = req.tender; var user = req.user; if (!req.body.type) { return res.send({err: {type: 'empty_type'}}); } if (req.body.number) { return res.send({err: {type: 'empty_number'}}); } if (isNaN(parseInt(req.body.number)) || parseInt(req.body.number) < 0) { return res.send({err: {type: 'invalid_number'}}); } newTenderService.payment(tender, user, req.body.type, req.body.number, function (err, result) { return res.send(err || result); }); };
Fix config to accept system variables
package gr.iti.mklab.framework.common.domain.config; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.mongodb.morphia.annotations.Entity; import gr.iti.mklab.framework.common.domain.JSONable; /** * Class for the configuration of streams or storages * reading a set of parameters * * @author manosetro - manosetro@iti.gr * */ @Entity(noClassnameStored = true) public class Configuration extends JSONable implements Iterable<String> { /** * */ private static final long serialVersionUID = 5070483137103099259L; private static Pattern pattern = Pattern.compile("(\\Q${\\E)(.*)(\\Q}\\E)"); public static final String CLASS_PATH = "Classpath"; private Map<String, String> params = new HashMap<String, String>(); public String getParameter(String name) { return getParameter(name,null); } public String getParameter(String name, String defaultValue){ String value = params.get(name); Matcher matcher = pattern.matcher(value); if(value != null && matcher.find()) { value = matcher.group(2); value = System.getProperty(value); } return value == null ? defaultValue : value; } public void setParameter(String name, String value) { params.put(name,value); } @Override public Iterator<String> iterator() { return params.keySet().iterator(); } }
package gr.iti.mklab.framework.common.domain.config; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.mongodb.morphia.annotations.Entity; import gr.iti.mklab.framework.common.domain.JSONable; /** * Class for the configuration of streams or storages * reading a set of parameters * * @author manosetro - manosetro@iti.gr * */ @Entity(noClassnameStored = true) public class Configuration extends JSONable implements Iterable<String> { /** * */ private static final long serialVersionUID = 5070483137103099259L; public static final String CLASS_PATH = "Classpath"; private Map<String, String> params = new HashMap<String, String>(); public String getParameter(String name) { return getParameter(name,null); } public String getParameter(String name, String defaultValue){ String value = params.get(name); return value == null ? defaultValue : value; } public void setParameter(String name, String value) { params.put(name,value); } @Override public Iterator<String> iterator() { return params.keySet().iterator(); } }
Create a GET products method
from flask import Flask # Create Flask application app = Flask(__name__) @app.route('/inventory') def index(): """ Intro page of the inventory API This method will only return some welcome words. Returns: response: welcome words in json format and status 200 Todo: * Finish the implementations. * Write the tests for this. """ pass @app.route('/inventory/products', methods=['GET']) def get_product_list(): """ Get info about all products This method will get the info about all the products Args: no arguments Returns: response: product information(product id, location id, used/new/open_box, total_quantity, restock_level) status 200 if succeeded Todo: * Finish the implementations. * Write the tests for this. """ @app.route('/inventory/products/<int:id>', methods=['PUT']) def update_product(id): """ Update info about a product This method will update the info about a product (eg. amount of new, open box or used.) Args: id (string): The id of the product to be update Returns: response: update successful message with status 200 if succeeded or no product found with status 404 if cannot found the product or invalid update with status 400 if the update violates any limitation. Todo: * Finish the implementations. * Write the tests for this. """ pass
from flask import Flask # Create Flask application app = Flask(__name__) @app.route('/inventory') def index(): """ Intro page of the inventory API This method will only return some welcome words. Returns: response: welcome words in json format and status 200 Todo: * Finish the implementations. * Write the tests for this. """ pass @app.route('/inventory/products/<int:id>', methods=['PUT']) def update_product(id): """ Update info about a product This method will update the info about a product (eg. amount of new, open box or used.) Args: id (string): The id of the product to be update Returns: response: update successful message with status 200 if succeeded or no product found with status 404 if cannot found the product or invalid update with status 400 if the update violates any limitation. Todo: * Finish the implementations. * Write the tests for this. """ pass
Implement the new deferred providers interface
<?php namespace Modules\Recipe\Providers; use Illuminate\Contracts\Support\DeferrableProvider; use Illuminate\Support\ServiceProvider; class DeferredServiceProvider extends ServiceProvider implements DeferrableProvider { /** * Register the service provider. * * @return void */ public function register() { app()->bind('foo', function () { return 'bar'; }); app()->bind('deferred', function () { return; }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['deferred']; } }
<?php namespace Modules\Recipe\Providers; use Illuminate\Support\ServiceProvider; class DeferredServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Register the service provider. * * @return void */ public function register() { app()->bind('foo', function () { return 'bar'; }); app()->bind('deferred', function () { return; }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['deferred']; } }
Make tests run on sqlite by default
import os import dj_database_url DATABASE_URL = os.environ.get("DATABASE_URL", "sqlite:///:memory:") DATABASES = { "default": dj_database_url.parse(DATABASE_URL), } INSTALLED_APPS = ("django_dbq",) MIDDLEWARE_CLASSES = ( "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ) SECRET_KEY = "abcde12345" LOGGING = { "version": 1, "disable_existing_loggers": True, "handlers": {"console": {"level": "DEBUG", "class": "logging.StreamHandler",},}, "root": {"handlers": ["console"], "level": "INFO",}, "loggers": {"django_dbq": {"level": "CRITICAL", "propagate": True,},}, }
import os import dj_database_url DATABASES = { "default": dj_database_url.parse(os.environ["DATABASE_URL"]), } INSTALLED_APPS = ("django_dbq",) MIDDLEWARE_CLASSES = ( "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ) SECRET_KEY = "abcde12345" LOGGING = { "version": 1, "disable_existing_loggers": True, "handlers": {"console": {"level": "DEBUG", "class": "logging.StreamHandler",},}, "root": {"handlers": ["console"], "level": "INFO",}, "loggers": {"django_dbq": {"level": "CRITICAL", "propagate": True,},}, }
fix(frontend): Fix bug with games after first authorization.
/** * Created by stas on 06.01.16. */ 'use strict'; var playzoneApp = angular.module('playzoneApp', [ 'ngRoute', 'ngCookies', 'ngResource', 'ngWebSocket', 'playzoneControllers', 'playzoneServices', 'pascalprecht.translate', 'LocalStorageModule' ]).run(['$http', '$rootScope', '$cookies', 'UserRest', 'WebsocketService', function ($http, $rootScope, $cookies, UserRest, WebsocketService) { $rootScope.user = new UserRest({ login: $rootScope.user ? $rootScope.user.login : $cookies.get("user_login"), token: $rootScope.user ? $rootScope.user.token : $cookies.get("user_token"), password: $rootScope.user ? $rootScope.user.token : $cookies.get("user_token") }); $rootScope.user.$auth().then( function() { WebsocketService.introduction($rootScope.user); } ); }]); var checkIfUnauthorized = function ($q, $rootScope, $location) { if ($rootScope.user && $rootScope.user.isAuth) { $location.path('/'); } }; var playzoneControllers = angular.module('playzoneControllers', []); var playzoneServices = angular.module('playzoneServices', []);
/** * Created by stas on 06.01.16. */ 'use strict'; var playzoneApp = angular.module('playzoneApp', [ 'ngRoute', 'ngCookies', 'ngResource', 'ngWebSocket', 'playzoneControllers', 'playzoneServices', 'pascalprecht.translate', 'LocalStorageModule' ]).run(['$http', '$rootScope', '$cookies', 'UserRest', 'WebsocketService', function ($http, $rootScope, $cookies, UserRest, WebsocketService) { $rootScope.user = new UserRest({ login: $cookies.get("user_login"), token: $cookies.get("user_token"), password: $cookies.get("user_token") }); $rootScope.user.$auth().then( function() { WebsocketService.introduction($rootScope.user); } ); }]); var checkIfUnauthorized = function ($q, $rootScope, $location) { if ($rootScope.user && $rootScope.user.isAuth) { $location.path('/'); } }; var playzoneControllers = angular.module('playzoneControllers', []); var playzoneServices = angular.module('playzoneServices', []);
Add private API version property to client.
/** * index.js * Client entry point. * * @author Francis Brito <fr.br94@gmail.com> * @license MIT */ 'use strict'; /** * Client * Provides methods to access PrintHouse's API. * * @param {String} apiKey API key identifying account owner. * @param {Object} opts Contains options to be passed to the client */ var Client = function Client(apiKey, opts) { opts = opts || {}; if (!apiKey) { throw new Error('No API key provided.'); } this._apiUrl = opts.apiUrl || Client.DEFAULT_API_URL; this._apiVersion = -1; }; /** * Default API endpoint. * Used if no API endpoint is passed in opts parameter when constructing a client. * * @type {String} */ Client.DEFAULT_API_URL = 'http://printhouse.io/api'; /** * Default API version. * Used if no API version is passed in opts parameter when constructing a client. * * @type {String} */ Client.DEFAULT_API_VERSION = 1; module.exports = { Client: Client };
/** * index.js * Client entry point. * * @author Francis Brito <fr.br94@gmail.com> * @license MIT */ 'use strict'; /** * Client * Provides methods to access PrintHouse's API. * * @param {String} apiKey API key identifying account owner. * @param {Object} opts Contains options to be passed to the client */ var Client = function Client(apiKey, opts) { opts = opts || {}; if (!apiKey) { throw new Error('No API key provided.'); } this._apiUrl = opts.apiUrl || Client.DEFAULT_API_URL; }; /** * Default API endpoint. * Used if no API endpoint is passed in opts parameter when constructing a client. * * @type {String} */ Client.DEFAULT_API_URL = 'http://printhouse.io/api'; /** * Default API version. * Used if no API version is passed in opts parameter when constructing a client. * * @type {String} */ Client.DEFAULT_API_VERSION = 1; module.exports = { Client: Client };
Fix proper handling of form submission in serializer
<?php class Analytics_Options_Serializer { public static function save() { $option_name = 'analytics'; if ( !( empty( $_POST['vendor-type'] ) || empty( $_POST['config'] ) ) ) { if ( empty( $_POST['id-value'] ) ) { $_POST['id-value'] = md5( $_POST['config'] ); } $new_analytics_options = array( $_POST['id-value'], $_POST['vendor-type'], stripslashes( $_POST['config'] ) ); $inner_option_name = $_POST['vendor-type'] . '-' . $_POST['id-value']; $analytics_options = get_option( $option_name ); if ( ! $analytics_options ) { $analytics_options = array(); } if ( isset( $_POST['delete'] ) ) { unset( $analytics_options[ $inner_option_name ] ); } else { $analytics_options[ $inner_option_name ] = $new_analytics_options; } update_option( $option_name, $analytics_options, false ); } // [Redirect] Keep the user in the analytics options page // Wrap in is_admin() to enable phpunit tests to exercise this code if ( is_admin() ) { wp_redirect( admin_url( 'admin.php?page=amp-analytics-options' ) ); } } }
<?php class Analytics_Options_Serializer { public static function save() { $option_name = 'analytics'; if ( empty( $_POST['vendor-type'] ) || empty( $_POST['config'] ) ) { return; } if ( empty($_POST['id-value'])) { $_POST['id-value'] = md5($_POST['config']); } $new_analytics_options = array( $_POST['id-value'], $_POST['vendor-type'], stripslashes($_POST['config']) ); $inner_option_name = $_POST['vendor-type'] . '-' . $_POST['id-value']; $analytics_options = get_option($option_name); if ( ! $analytics_options ) { $analytics_options = array(); } if ( isset($_POST['delete']) ) { unset($analytics_options[$inner_option_name]); } else { $analytics_options[$inner_option_name] = $new_analytics_options; } update_option( $option_name, $analytics_options, false); // [Redirect] Keep the user in the analytics options page // Wrap in is_admin() to enable phpunit tests to exercise this code if ( is_admin() ) { wp_redirect( admin_url( 'admin.php?page=amp-analytics-options' ) ); } } }
Use new function name for doc generator
var geonames = require('geonames-stream'); var peliasConfig = require( 'pelias-config' ).generate(); var peliasAdminLookup = require( 'pelias-admin-lookup' ); var dbclient = require('pelias-dbclient'); var model = require( 'pelias-model' ); var resolvers = require('./resolvers'); var adminLookupMetaStream = require('../lib/streams/adminLookupMetaStream'); var peliasDocGenerator = require( '../lib/streams/peliasDocGenerator'); module.exports = function( filename ){ var pipeline = resolvers.selectSource( filename ) .pipe( geonames.pipeline ) .pipe( peliasDocGenerator.create() ); if( peliasConfig.imports.geonames.adminLookup ){ pipeline = pipeline .pipe( adminLookupMetaStream.create() ) .pipe( peliasAdminLookup.stream() ); } pipeline .pipe(model.createDocumentMapperStream()) .pipe( dbclient() ); };
var geonames = require('geonames-stream'); var peliasConfig = require( 'pelias-config' ).generate(); var peliasAdminLookup = require( 'pelias-admin-lookup' ); var dbclient = require('pelias-dbclient'); var model = require( 'pelias-model' ); var resolvers = require('./resolvers'); var adminLookupMetaStream = require('../lib/streams/adminLookupMetaStream'); var peliasDocGenerator = require( '../lib/streams/peliasDocGenerator'); module.exports = function( filename ){ var pipeline = resolvers.selectSource( filename ) .pipe( geonames.pipeline ) .pipe( peliasDocGenerator.createPeliasDocGenerator() ); if( peliasConfig.imports.geonames.adminLookup ){ pipeline = pipeline .pipe( adminLookupMetaStream.create() ) .pipe( peliasAdminLookup.stream() ); } pipeline .pipe(model.createDocumentMapperStream()) .pipe( dbclient() ); };
Add controller to handle patching stage configs
'use strict' // let logger = require('tracer').colorConsole() let registry = require('../../extensions/registry') let basic = require('./basic-response-helper') module.exports = { setStageConfig: function setStageConfig(req, res) { basic.insertRespond(req, res, 'pipeline_stage_configs') }, updateStageConfig: function updateStageConfig(req, res) { basic.patchRespond(req, res, 'pipeline_stage_configs') }, deleteStageConfig: function deleteStageConfig(req, res) { basic.deleteRespond(req, res, 'pipeline_stage_configs') }, getAvailableTypes: function getAvailableTypes(req, res) { res.status(201).send({data: registry.getStageTypes()}) }, /** * Get stages for a specific pipeline * * @param req * @param res */ getListForPipeline: function getListForPipeline(req, res) { basic.getListCustom(req, res, 'pipeline_stage_configs', query => { return query.where('pipeline_config_id', req.params.id) }) } }
'use strict' // let logger = require('tracer').colorConsole() let registry = require('../../extensions/registry') let basic = require('./basic-response-helper') module.exports = { setStageConfig: function setStageConfig(req, res) { basic.insertRespond(req, res, 'pipeline_stage_configs') }, deleteStageConfig: function setStageConfig(req, res) { basic.deleteRespond(req, res, 'pipeline_stage_configs') }, getAvailableTypes: function getAvailableTypes(req, res) { res.status(201).send({data: registry.getStageTypes()}) }, /** * Get stages for a specific pipeline * * @param req * @param res */ getListForPipeline: function getListForPipeline(req, res) { basic.getListCustom(req, res, 'pipeline_stage_configs', query => { return query.where('pipeline_config_id', req.params.id) }) } }
Add mark as read button to all link types, including local HN links
HNSpecial.settings.registerModule("mark_as_read", function () { function editLinks() { var titles = _.toArray(document.getElementsByClassName("title")); titles.forEach(function (title) { if (!title.getAttribute("data-hnspecial-mark-as-read") && title.children.length > 0 && title.children[0].nodeName == "A") { title.setAttribute("data-hnspecial-mark-as-read", "true"); // Create the Mark as read "button" var button = _.createElement("span", { classes: ["hnspecial-mark-as-read-button"], content: "&#10004;" // tick symbol }); // Add the click listener button.addEventListener("click", function (e) { chrome.extension.sendRequest({ module: "mark_as_read", action: "toggle", params: { url: e.target.parentElement.children[1].href } }); }); // Insert the button into the page title.insertBefore(button, title.children[0]); } }); } // Run it editLinks(); // Subscribe to the event emitted when new links are present HNSpecial.settings.subscribe("new links", editLinks); });
HNSpecial.settings.registerModule("mark_as_read", function () { function editLinks() { var titles = _.toArray(document.getElementsByClassName("title")); titles.forEach(function (title) { if (!title.getAttribute("data-hnspecial-mark-as-read") && title.childElementCount === 2 && title.children[1].classList.contains("comhead")) { title.setAttribute("data-hnspecial-mark-as-read", "true"); // Create the Mark as read "button" var button = _.createElement("span", { classes: ["hnspecial-mark-as-read-button"], content: "&#10004;" // tick symbol }); // Add the click listener button.addEventListener("click", function (e) { chrome.extension.sendRequest({ module: "mark_as_read", action: "toggle", params: { url: e.target.parentElement.children[1].href } }); }); // Insert the button into the page title.insertBefore(button, title.children[0]); } }); } // Run it editLinks(); // Subscribe to the event emitted when new links are present HNSpecial.settings.subscribe("new links", editLinks); });
Fix improper grammar in Dutch i18n file Grammar is incorrect when maximum is 1, 'kunnen' should be 'kan' in that case.
define(function () { // Dutch return { errorLoading: function () { return 'De resultaten konden niet worden geladen.'; }, inputTooLong: function (args) { var overChars = args.input.length - args.maximum; var message = 'Gelieve ' + overChars + ' karakters te verwijderen'; return message; }, inputTooShort: function (args) { var remainingChars = args.minimum - args.input.length; var message = 'Gelieve ' + remainingChars + ' of meer karakters in te voeren'; return message; }, loadingMore: function () { return 'Meer resultaten laden…'; }, maximumSelected: function (args) { var verb = args.maximum == 1 ? 'kan' : 'kunnen'; var message = 'Er ' + verb + ' maar ' + args.maximum + ' item'; if (args.maximum != 1) { message += 's'; } message += ' worden geselecteerd'; return message; }, noResults: function () { return 'Geen resultaten gevonden…'; }, searching: function () { return 'Zoeken…'; } }; });
define(function () { // Dutch return { errorLoading: function () { return 'De resultaten konden niet worden geladen.'; }, inputTooLong: function (args) { var overChars = args.input.length - args.maximum; var message = 'Gelieve ' + overChars + ' karakters te verwijderen'; return message; }, inputTooShort: function (args) { var remainingChars = args.minimum - args.input.length; var message = 'Gelieve ' + remainingChars + ' of meer karakters in te voeren'; return message; }, loadingMore: function () { return 'Meer resultaten laden…'; }, maximumSelected: function (args) { var message = 'Er kunnen maar ' + args.maximum + ' item'; if (args.maximum != 1) { message += 's'; } message += ' worden geselecteerd'; return message; }, noResults: function () { return 'Geen resultaten gevonden…'; }, searching: function () { return 'Zoeken…'; } }; });
Update dsub version to 0.4.3 PiperOrigin-RevId: 343898649
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.4.3'
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.4.3.dev0'
Add observerFunc to observe with a Gauge
// Copyright 2016 The Prometheus Authors // 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 prometheus import "time" // Observer is the interface that wraps the Observe method, used by Histogram // and Summary to add observations. type Observer interface { Observe(float64) } type observerFunc func(float64) func (o observerFunc) Observe(value float64) { o(value) } type Timer struct { begin time.Time observer Observer } func StartTimer() *Timer { return &Timer{begin: time.Now()} } func (t *Timer) With(o Observer) *Timer { t.observer = o return t } func (t *Timer) WithGauge(g Gauge) *Timer { t.observer = observerFunc(g.Set) return t } func (t *Timer) Stop() { if t.observer != nil { t.observer.Observe(time.Since(t.begin).Seconds()) } }
// Copyright 2016 The Prometheus Authors // 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 prometheus import "time" // Observer is the interface that wraps the Observe method, used by Histogram // and Summary to add observations. type Observer interface { Observe(float64) } type Timer struct { begin time.Time observer Observer gauge Gauge } func StartTimer() *Timer { return &Timer{begin: time.Now()} } func (t *Timer) With(o Observer) *Timer { t.observer = o return t } func (t *Timer) WithGauge(g Gauge) *Timer { t.gauge = g return t } func (t *Timer) Stop() { if t.observer != nil { t.observer.Observe(time.Since(t.begin).Seconds()) } if t.gauge != nil { t.gauge.Set(time.Since(t.begin).Seconds()) } }
Update for changes in JavaHL conflict resolution callback
package org.tigris.subversion.svnclientadapter.javahl; import org.tigris.subversion.javahl.ConflictDescriptor; import org.tigris.subversion.javahl.ConflictResolverCallback; import org.tigris.subversion.javahl.ConflictResult; import org.tigris.subversion.javahl.SubversionException; import org.tigris.subversion.svnclientadapter.ISVNConflictResolver; import org.tigris.subversion.svnclientadapter.SVNClientException; public class JhlConflictResolver implements ConflictResolverCallback { ISVNConflictResolver worker; public JhlConflictResolver(ISVNConflictResolver worker) { super(); this.worker = worker; } public ConflictResult resolve(ConflictDescriptor descrip) throws SubversionException { try { return new ConflictResult(worker.resolve(JhlConverter.convertConflictDescriptor(descrip)), null); } catch (SVNClientException e) { throw new JhlException(e); } } }
package org.tigris.subversion.svnclientadapter.javahl; import org.tigris.subversion.javahl.ConflictDescriptor; import org.tigris.subversion.javahl.ConflictResolverCallback; import org.tigris.subversion.javahl.SubversionException; import org.tigris.subversion.svnclientadapter.ISVNConflictResolver; import org.tigris.subversion.svnclientadapter.SVNClientException; public class JhlConflictResolver implements ConflictResolverCallback { ISVNConflictResolver worker; public JhlConflictResolver(ISVNConflictResolver worker) { super(); this.worker = worker; } public int resolve(ConflictDescriptor descrip) throws SubversionException { try { return worker.resolve(JhlConverter.convertConflictDescriptor(descrip)); } catch (SVNClientException e) { throw new JhlException(e); } } }
Rename Node.js "Stable" releases to "Current"
const groupRe = /^((:?\w|\-|,|, )+):\s*/i , reverts = require('./reverts') function toGroups (summary) { summary = reverts.cleanSummary(summary) var m = summary.match(groupRe) return (m && m[1]) || '' } function cleanSummary (summary) { return (summary || '').replace(groupRe, '') } function isReleaseCommit (summary) { return /^Working on v?\d{1,2}\.\d{1,3}\.\d{1,3}$/.test(summary) || /^\d{4}-\d{2}-\d{2},? Version \d{1,2}\.\d{1,3}\.\d{1,3} (["'][A-Za-z ]+["'] )?\((Current|Stable|LTS|Maintenance)\)/.test(summary) || /^\d{4}-\d{2}-\d{2},? io.js v\d{1,2}\.\d{1,3}\.\d{1,3} Release/.test(summary) || /^\d+\.\d+\.\d+$/.test(summary) // `npm version X` style commit } module.exports.toGroups = toGroups module.exports.cleanSummary = cleanSummary module.exports.isReleaseCommit = isReleaseCommit
const groupRe = /^((:?\w|\-|,|, )+):\s*/i , reverts = require('./reverts') function toGroups (summary) { summary = reverts.cleanSummary(summary) var m = summary.match(groupRe) return (m && m[1]) || '' } function cleanSummary (summary) { return (summary || '').replace(groupRe, '') } function isReleaseCommit (summary) { return /^Working on v?\d{1,2}\.\d{1,3}\.\d{1,3}$/.test(summary) || /^\d{4}-\d{2}-\d{2},? Version \d{1,2}\.\d{1,3}\.\d{1,3} (["'][A-Za-z ]+["'] )?\((Stable|LTS|Maintenance)\)/.test(summary) || /^\d{4}-\d{2}-\d{2},? io.js v\d{1,2}\.\d{1,3}\.\d{1,3} Release/.test(summary) || /^\d+\.\d+\.\d+$/.test(summary) // `npm version X` style commit } module.exports.toGroups = toGroups module.exports.cleanSummary = cleanSummary module.exports.isReleaseCommit = isReleaseCommit
Add sphinxcontrib-httpdomain for readthedocs build
#!/usr/bin/env python # from distutils.core import setup from setuptools import setup, find_packages import multiprocessing # nopep8 setup(name='orlo', version='0.0.1', description='Deployment data capture API', author='Alex Forbes', author_email='alforbes@ebay.com', license='GPL', long_description=open('README.md').read(), url='https://github.com/eBayClassifiedsGroup/orlo', packages=find_packages(), include_package_data=True, install_requires=[ 'arrow', 'Flask', 'Flask-SQLAlchemy', 'Flask-Testing', 'Flask-Migrate', 'gunicorn', 'psycopg2', 'pytz', 'sphinxcontrib-httpdomain', 'sqlalchemy-utils', ], test_suite='tests', )
#!/usr/bin/env python # from distutils.core import setup from setuptools import setup, find_packages import multiprocessing # nopep8 setup(name='orlo', version='0.0.1', description='Deployment data capture API', author='Alex Forbes', author_email='alforbes@ebay.com', license='GPL', long_description=open('README.md').read(), url='https://github.com/eBayClassifiedsGroup/orlo', packages=find_packages(), include_package_data=True, install_requires=[ 'arrow', 'Flask', 'Flask-SQLAlchemy', 'Flask-Testing', 'Flask-Migrate', 'gunicorn', 'psycopg2', 'pytz', 'sqlalchemy-utils', ], test_suite='tests', )
Fix error with saving credentials in python 2.7 This fixes #102
import getpass import os from appdirs import user_cache_dir try: # python2.7 input = raw_input except NameError: pass CONFIG_FILE_NAME = os.path.join( user_cache_dir(appname='spoppy'), '.creds' ) def get_config(): if os.path.exists(CONFIG_FILE_NAME): with open(CONFIG_FILE_NAME, 'r') as f: return [ line.strip() for line in f.readlines() ][:2] return None, None def set_config(username, password): with open(CONFIG_FILE_NAME, 'w') as f: f.write(username) f.write('\n') f.write(password) def get_config_from_user(): username, password = ( input('Username: '), getpass.getpass('Password: ') ) set_config(username, password) return username, password def clear_config(): os.remove(CONFIG_FILE_NAME)
import getpass import os from appdirs import user_cache_dir CONFIG_FILE_NAME = os.path.join( user_cache_dir(appname='spoppy'), '.creds' ) def get_config(): if os.path.exists(CONFIG_FILE_NAME): with open(CONFIG_FILE_NAME, 'r') as f: return [ line.strip() for line in f.readlines() ][:2] return None, None def set_config(username, password): with open(CONFIG_FILE_NAME, 'w') as f: f.write(username) f.write('\n') f.write(password) def get_config_from_user(): username, password = ( input('Username: '), getpass.getpass('Password: ') ) set_config(username, password) return username, password def clear_config(): os.remove(CONFIG_FILE_NAME)
Switch to hash locationType in hopes of fixing demo app
module.exports = function (environment) { var ENV = { APP: {}, rootURL: '/', EmberENV: { FEATURES: {} }, googleFonts: [ 'Roboto:300' ], environment: environment, locationType: 'hash', modulePrefix: 'dummy', 'ember-prop-types': { spreadProperty: 'options', throwErrors: false, validateOnUpdate: true } } switch (environment) { case 'production': ENV.rootURL = '/ember-prop-types' break case 'test': // Testem prefers this... ENV.rootURL = '/' ENV.locationType = 'none' // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false ENV.APP.LOG_VIEW_LOOKUPS = false ENV.APP.rootElement = '#ember-testing' break } return ENV }
module.exports = function (environment) { var ENV = { APP: {}, rootURL: '/', EmberENV: { FEATURES: {} }, googleFonts: [ 'Roboto:300' ], environment: environment, locationType: 'auto', modulePrefix: 'dummy', 'ember-prop-types': { spreadProperty: 'options', throwErrors: false, validateOnUpdate: true } } switch (environment) { case 'production': ENV.rootURL = '/ember-prop-types' break case 'test': // Testem prefers this... ENV.rootURL = '/' ENV.locationType = 'none' // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false ENV.APP.LOG_VIEW_LOOKUPS = false ENV.APP.rootElement = '#ember-testing' break } return ENV }
Update to VGG laod from datadir
from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_fcn import fcn8_vgg import tensorflow as tf def inference(hypes, images, train=True): """Build the MNIST model up to where it may be used for inference. Args: images: Images placeholder, from inputs(). train: whether the network is used for train of inference Returns: softmax_linear: Output tensor with the computed logits. """ vgg16_npy_path = os.path.join(hypes['dirs']['data_dir'], "vgg16.npy") vgg_fcn = fcn8_vgg.FCN8VGG(vgg16_npy_path=vgg16_npy_path) num_classes = hypes["fc_size"] vgg_fcn.wd = hypes['wd'] vgg_fcn.build(images, train=train, num_classes=num_classes, random_init_fc8=True) vgg_dict = {'unpooled': vgg_fcn.conv5_3, 'deep_feat': vgg_fcn.pool5, 'deep_feat_channels': 512, 'early_feat': vgg_fcn.conv4_3, 'scored_feat': vgg_fcn.score_fr} return vgg_dict
from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_fcn import fcn8_vgg import tensorflow as tf def inference(hypes, images, train=True): """Build the MNIST model up to where it may be used for inference. Args: images: Images placeholder, from inputs(). train: whether the network is used for train of inference Returns: softmax_linear: Output tensor with the computed logits. """ vgg_fcn = fcn8_vgg.FCN8VGG() num_classes = hypes["fc_size"] vgg_fcn.wd = hypes['wd'] vgg_fcn.build(images, train=train, num_classes=num_classes, random_init_fc8=True) vgg_dict = {'unpooled': vgg_fcn.conv5_3, 'deep_feat': vgg_fcn.pool5, 'deep_feat_channels': 512, 'early_feat': vgg_fcn.conv4_3, 'scored_feat': vgg_fcn.score_fr} return vgg_dict
Add retries to sample data init
import Promise from 'bluebird'; import process from 'process'; import util from 'util'; import { withRetries } from 'killrvideo-nodejs-common'; import { Scheduler } from './scheduler'; import * as availableTasks from './tasks'; import { initCassandraAsync } from './utils/cassandra'; import { initializeSampleDataAsync } from './sample-data/initialize'; // Allow promise cancellation Promise.config({ cancellation: true }); /** * Async start the application. */ async function startAsync() { let scheduler = null; try { // Make sure C* is ready to go await withRetries(initCassandraAsync, 10, 10, 'Could not initialize Cassandra keyspace', false); // Initialize sample data await withRetries(initializeSampleDataAsync, 10, 10, 'Could not initialize sample data', false); // Start scheduled tasks scheduler = new Scheduler(availableTasks); scheduler.start(); return scheduler; } catch (err) { if (scheduler !== null) scheduler.stop(); console.error('Unable to start Sample Data Generator'); console.error(err); process.exit(1); } } // Start the app let startPromise = startAsync(); // Handler for attempting to gracefully shutdown function onStop() { console.log('Attempting to shutdown'); if (startPromise.isFulfilled()) { let s = startPromise.value(); s.stop(); } else { startPromise.cancel(); } process.exit(0); } // Attempt to shutdown on SIGINT process.on('SIGINT', onStop);
import Promise from 'bluebird'; import process from 'process'; import util from 'util'; import { withRetries } from 'killrvideo-nodejs-common'; import { Scheduler } from './scheduler'; import * as availableTasks from './tasks'; import { initCassandraAsync } from './utils/cassandra'; import { initializeSampleDataAsync } from './sample-data/initialize'; // Allow promise cancellation Promise.config({ cancellation: true }); /** * Async start the application. */ async function startAsync() { let scheduler = null; try { // Make sure C* is ready to go await withRetries(initCassandraAsync, 10, 10, 'Could not initialize Cassandra keyspace', false); // Initialize sample data await initializeSampleDataAsync(); // Start scheduled tasks scheduler = new Scheduler(availableTasks); scheduler.start(); return scheduler; } catch (err) { if (scheduler !== null) scheduler.stop(); console.error('Unable to start Sample Data Generator'); console.error(err); process.exit(1); } } // Start the app let startPromise = startAsync(); // Handler for attempting to gracefully shutdown function onStop() { console.log('Attempting to shutdown'); if (startPromise.isFulfilled()) { let s = startPromise.value(); s.stop(); } else { startPromise.cancel(); } process.exit(0); } // Attempt to shutdown on SIGINT process.on('SIGINT', onStop);
Fix wrong unix socket handler
package exporter import ( "net" "net/url" "time" "github.com/prometheus/common/log" ) // UnixStatsReader reads uwsgi stats from specified unix socket. type UnixStatsReader struct { filename string } func init() { StatsReaderCreators = append(StatsReaderCreators, newUnixStatsReader) } func newUnixStatsReader(u *url.URL, uri string, timeout time.Duration) StatsReader { if u.Scheme != "unix" { return nil } return &UnixStatsReader{ filename: u.Path, } } func (reader *UnixStatsReader) Read() (*UwsgiStats, error) { conn, err := net.Dial("unix", string(reader.filename)) if err != nil { log.Errorf("Error while reading uwsgi stats from unix socket: %s", reader.filename) return nil, err } defer conn.Close() uwsgiStats, err := parseUwsgiStatsFromIO(conn) if err != nil { log.Errorf("Failed to unmarshal JSON: %s", err) return nil, err } return uwsgiStats, nil }
package exporter import ( "net" "net/url" "time" "github.com/prometheus/common/log" ) // UnixStatsReader reads uwsgi stats from specified unix socket. type UnixStatsReader struct { filename string } func init() { StatsReaderCreators = append(StatsReaderCreators, newHTTPStatsReader) } func newUnixStatsReader(u *url.URL, uri string, timeout time.Duration) StatsReader { if u.Scheme != "unix" { return nil } return &UnixStatsReader{ filename: u.Path, } } func (reader *UnixStatsReader) Read() (*UwsgiStats, error) { conn, err := net.Dial("unix", string(reader.filename)) if err != nil { log.Errorf("Error while reading uwsgi stats from unix socket: %s", reader.filename) return nil, err } defer conn.Close() uwsgiStats, err := parseUwsgiStatsFromIO(conn) if err != nil { log.Errorf("Failed to unmarshal JSON: %s", err) return nil, err } return uwsgiStats, nil }
Fix tests in the browser due to fixtures not loaded
/* In order for the tests to run in the browser the fixture files must * be loaded statically into an object. The 'brfs' module will replace * the fs.readFileSync('static_path') call by the contents of the file. */ const fs = require('fs'); // import syntax doesn't work inside karma const fixtures = { 'libraries.json': fs.readFileSync(__dirname + '/libraries.json'), 'library.json': fs.readFileSync(__dirname + '/library.json'), 'libraryVersions.json': fs.readFileSync(__dirname + '/libraryVersions.json'), 'test-library-publish-0.0.1.tar.gz': fs.readFileSync(__dirname + '/test-library-publish-0.0.1.tar.gz'), 'test-library-publish-0.0.2.tar.gz': fs.readFileSync(__dirname + '/test-library-publish-0.0.2.tar.gz'), }; function read(filename) { if (!fixtures[filename]) { throw new Error(`Fixture ${filename} doesn't exit`); } return fixtures[filename]; } function readJSON(filename) { return JSON.parse(read(filename)); } export { read, readJSON };
const fs = require('fs'); // import syntax doesn't work inside karma const fixtureNames = [ 'libraries.json', 'library.json', 'libraryVersions.json', 'test-library-publish-0.0.1.tar.gz', 'test-library-publish-0.0.2.tar.gz' ]; function readFixtures(fixtureNames) { const fixtures = {}; for (let idx in fixtureNames) { const name = fixtureNames[idx]; fixtures[name] = fs.readFileSync(`${__dirname}/${name}`); } return fixtures; } const fixtures = readFixtures(fixtureNames); function read(filename) { if (!fixtures[filename]) { throw new Error(`Fixture ${filename} doesn't exit`); } return fixtures[filename]; } function readJSON(filename) { return JSON.parse(read(filename)); } export { read, readJSON };
Fix tests now that "lifetimes" is commented out
import Ember from 'ember'; import { test } from 'qunit'; import moduleForAcceptance from '../../tests/helpers/module-for-acceptance'; import DocsController from 'dummy/docs/controller'; moduleForAcceptance('Acceptance | root'); test('visiting /', function(assert) { visit('/'); andThen(function() { assert.equal(currentURL(), '/'); assert.ok(Ember.$('.navbar h3').text(), 'ember-concurrency'); }); }); test('visiting all docs', function(assert) { visit('/'); assert.expect(15); let contents = DocsController.proto().get('flatContents'); let i = 0; function step() { let page = contents[i++]; if (!page) { return; } let url = page.route.replace(/\./g, '/'); return visit(url).then(() => { assert.ok(true, "page rendered ok"); return step(); }); } return step(); });
import Ember from 'ember'; import { test } from 'qunit'; import moduleForAcceptance from '../../tests/helpers/module-for-acceptance'; import DocsController from 'dummy/docs/controller'; moduleForAcceptance('Acceptance | root'); test('visiting /', function(assert) { visit('/'); andThen(function() { assert.equal(currentURL(), '/'); assert.ok(Ember.$('.navbar h3').text(), 'ember-concurrency'); }); }); test('visiting all docs', function(assert) { visit('/'); assert.expect(16); let contents = DocsController.proto().get('flatContents'); let i = 0; function step() { let page = contents[i++]; if (!page) { return; } let url = page.route.replace(/\./g, '/'); return visit(url).then(() => { assert.ok(true, "page rendered ok"); return step(); }); } return step(); });
Move now sets the client position and allows the movement plugin do its thing
import logging from spock.mcp import mcdata, mcpacket from spock.mcmap import smpmap from micropsi_core.world.minecraft.psidispatcher import PsiDispatcher from spock.utils import pl_announce @pl_announce('Micropsi') class MicropsiPlugin(object): def __init__(self, ploader, settings): self.worldadapter = settings['worldadapter'] self.worldadapter.spockplugin = self self.net = ploader.requires('Net') self.event = ploader.requires('Event') self.world = ploader.requires('World') self.clientinfo = ploader.requires('ClientInfo') #MicroPsi Datatargets self.psi_dispatcher = PsiDispatcher(self) self.move_x = 0 self.move_z = 0 self.move_x_ = 0 self.move_z_ = 0 def move(self, position=None): if not (self.net.connected and self.net.proto_state == mcdata.PLAY_STATE): return self.clientinfo.position = position
import logging from spock.mcp import mcdata, mcpacket from spock.mcmap import smpmap from micropsi_core.world.minecraft.psidispatcher import PsiDispatcher from spock.utils import pl_announce @pl_announce('Micropsi') class MicropsiPlugin(object): def __init__(self, ploader, settings): self.worldadapter = settings['worldadapter'] self.worldadapter.spockplugin = self self.net = ploader.requires('Net') self.event = ploader.requires('Event') self.world = ploader.requires('World') self.clientinfo = ploader.requires('ClientInfo') #MicroPsi Datatargets self.psi_dispatcher = PsiDispatcher(self) self.move_x = 0 self.move_z = 0 self.move_x_ = 0 self.move_z_ = 0 def move(self, position=None): if not (self.net.connected and self.net.proto_state == mcdata.PLAY_STATE): return if position is None: position = self.client_info.position self.net.push(mcpacket.Packet( ident='PLAY>Player Position and Look', data=position ))
Change commentId to accurately be responseId.
$(document).ready( function () { $(".upvote").click( function() { var responseId = $(".upvote").data("id"); event.preventDefault(); $.ajax({ url: '/response/up_vote', method: 'POST', data: { id: responseId }, dataType: 'JSON' }).done( function (voteCount) { if (voteCount == 1) { $("span[data-id=" + responseId + "]").html(voteCount + " vote"); } else { $("span[data-id=" + responseId + "]").html(voteCount + " vote"); } }).fail( function (voteCount) { console.log("Failed. Here is the voteCount:"); console.log(voteCount); }) }) })
$(document).ready( function () { $(".upvote").click( function() { var commentId = $(".upvote").data("id"); event.preventDefault(); $.ajax({ url: '/response/up_vote', method: 'POST', data: { id: commentId }, dataType: 'JSON' }).done( function (voteCount) { if (voteCount == 1) { $("span[data-id=" + commentId + "]").html(voteCount + " vote"); } else { $("span[data-id=" + commentId + "]").html(voteCount + " vote"); } }).fail( function (voteCount) { console.log("Failed. Here is the voteCount:"); console.log(voteCount); }) }) })
Fix bug on sign in page when invalid credentials are given
from django import forms from django.contrib.auth import authenticate from .models import * class SignInForm(forms.Form): username = forms.CharField(max_length=100, label='Username') password = forms.CharField(max_length=100, label='Password', widget=forms.PasswordInput) def clean(self): cleaned_data = super(SignInForm, self).clean() user = authenticate(username=cleaned_data.get('username'), password=cleaned_data.get('password')) if user is None: raise forms.ValidationError('Invalid username or password') class TopicForm(forms.ModelForm): class Meta: model = Topic fields = ['title', 'tags'] tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all()) first_message = forms.CharField(widget=forms.Textarea) class NewMessageForm(forms.ModelForm): class Meta: model = Message fields = ['content'] content = forms.CharField(label="New message", widget=forms.Textarea) class EditMessageForm(forms.ModelForm): class Meta: model = Message fields = ['content'] content = forms.CharField(label="Edit message", widget=forms.Textarea)
from django import forms from django.contrib.auth import authenticate from .models import * class SignInForm(forms.Form): username = forms.CharField(max_length=100, label='Username') password = forms.CharField(max_length=100, label='Password', widget=forms.PasswordInput) def clean(self): cleaned_data = super(SignInForm, self).clean() user = authenticate(username=cleaned_data.get('username'), password=cleaned_data.get('password')) if user is None: raise ValidationError('Invalid username or password') class TopicForm(forms.ModelForm): class Meta: model = Topic fields = ['title', 'tags'] tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all()) first_message = forms.CharField(widget=forms.Textarea) class NewMessageForm(forms.ModelForm): class Meta: model = Message fields = ['content'] content = forms.CharField(label="New message", widget=forms.Textarea) class EditMessageForm(forms.ModelForm): class Meta: model = Message fields = ['content'] content = forms.CharField(label="Edit message", widget=forms.Textarea)
Add test code for mercury switch
const express = require('express'); const app = express(); const gpio = require('wiring-pi'); const socket = require('express-ws')(app); // setup pi connection gpio.wiringPiSetup(); gpio.pinMode(8, gpio.INPUT); gpio.pinMode(9, gpio.INPUT); const tilt = () => { // return gpio.analogRead(8); return gpio.digitalRead(8); } //app.use(express.static('./public')); // listen for websocket connections app.ws('/', function(ws, req) { // event listener waiting for message via socket connection ws.on('message', (message) => { console.log('received: ${message}'); }); // event listener waiting for connection to close ws.on('end', () => { console.log('Connection ended...'); }); // send a reading from tilt sensor every 50 ms setInterval(()=>{ let tilt_value = tilt(); console.log(tilt_value) ws.send(tilt_value); }, 50); }); // testing setInterval(()=>{ let tilt_value = tilt(); // console.log('tilt switch' + tilt_value); console.log('mercury digital switch' + gpio.digitalRead(9)); console.log('mercury analog switch' + gpio.analogRead(9)); }, 500); app.listen(3000, () => { console.info('Server started on port 3000'); })
const express = require('express'); const app = express(); const gpio = require('wiring-pi'); const socket = require('express-ws')(app); // setup pi connection gpio.wiringPiSetup(); gpio.pinMode(8, gpio.INPUT); const tilt = () => { // testing whether it's digital or analog // return gpio.analogRead(8); return gpio.digitalRead(8); } //app.use(express.static('./public')); // listen for websocket connections app.ws('/', function(ws, req) { // event listener waiting for message via socket connection ws.on('message', (message) => { console.log('received: ${message}'); }); // event listener waiting for connection to close ws.on('end', () => { console.log('Connection ended...'); }); // send a reading from tilt sensor every 50 ms setInterval(()=>{ let tilt_value = tilt(); console.log(tilt_value) ws.send(tilt_value); }, 50); }); // testing setInterval(()=>{ let tilt_value = tilt(); console.log(tilt_value) }, 500); app.listen(3000, () => { console.info('Server started on port 3000'); })
Add happy-nest in email subject
<?php // check if fields passed are empty if(empty($_POST['name']) || empty($_POST['email']) || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) { echo "No arguments Provided!"; return false; } $name = $_POST['name']; // $phone = $_POST['phone']; $email_address = $_POST['email']; $message = $_POST['message']; $numOfGuests = $_POST['numOfGuests']; $checkinDate = $_POST['checkin']; $checkoutDate = $_POST['checkout']; // create email body and send it $to = 'contact@happy-nest.in'; $email_subject = "Happy-nest accomodation inquiry"; $email_body = "New request\n\n". "Name of the guest: $name \n". "Email: $email_address\n". "Number of guests: $numOfGuests\n". "Checkin Date (mm/dd/yyyy): $checkinDate\n". "Checkout Date (mm/dd/yyyy): $checkoutDate\n". "Message \n $message"; $headers = "From: me@happy-nest.in\n"; $headers .= "Reply-To: $email_address"; mail($to, $email_subject, $email_body, $headers); return true; ?>
<?php // check if fields passed are empty if(empty($_POST['name']) || empty($_POST['email']) || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) { echo "No arguments Provided!"; return false; } $name = $_POST['name']; // $phone = $_POST['phone']; $email_address = $_POST['email']; $message = $_POST['message']; $numOfGuests = $_POST['numOfGuests']; $checkinDate = $_POST['checkin']; $checkoutDate = $_POST['checkout']; // create email body and send it $to = 'contact@happy-nest.in'; $email_subject = "Accomodation inquiry"; $email_body = "New request\n\n". "Name of the guest: $name \n". "Email: $email_address\n". "Number of guests: $numOfGuests\n". "Checkin Date (mm/dd/yyyy): $checkinDate\n". "Checkout Date (mm/dd/yyyy): $checkoutDate\n". "Message \n $message"; $headers = "From: me@happy-nest.in\n"; $headers .= "Reply-To: $email_address"; mail($to, $email_subject, $email_body, $headers); return true; ?>
Use Moose for Perl 5
"""\ Perl code emitter for C'Dent """ from __future__ import absolute_import from cdent.emitter import Emitter as Base class Emitter(Base): LANGUAGE_ID = 'pm' def emit_includecdent(self, includecdent): self.writeln('use CDent::Run;') def emit_class(self, class_): name = class_.name self.writeln('package %s;' % name) self.writeln('use Moose;') self.writeln() self.emit(class_.has) self.writeln() self.writeln('1;') def emit_method(self, method): name = method.name self.writeln('sub %s {' % name) self.writeln(' my $self = shift;') self.emit(method.has, indent=True) self.writeln('}') def emit_println(self, println): self.write('print ', indent=True) self.emit(println.args) self.writeln(', "\\n";', indent=False) def emit_return(self, ret): self.writeln('return;')
"""\ Perl code emitter for C'Dent """ from __future__ import absolute_import from cdent.emitter import Emitter as Base class Emitter(Base): LANGUAGE_ID = 'pm' def emit_includecdent(self, includecdent): self.writeln('use CDent::Run;') def emit_class(self, class_): name = class_.name self.writeln('package %s;' % name) self.writeln('use CDent::Class;') self.writeln() self.emit(class_.has) self.writeln() self.writeln('1;') def emit_method(self, method): name = method.name self.writeln('sub %s {' % name) self.writeln(' my $self = shift;') self.emit(method.has, indent=True) self.writeln('}') def emit_println(self, println): self.write('print ', indent=True) self.emit(println.args) self.writeln(', "\\n";', indent=False) def emit_return(self, ret): self.writeln('return;')
Return hooks return to the caller of "call" method
<?php namespace SlaxWeb\Hooks; class Hooks { protected static $_hooks = []; public static function set(array $hook) { if ((isset($hook["name"]) && isset($hook["class"])) === false) { return false; } self::$_hooks[$hook["name"]] = $hook["class"]; return true; } public static function call() { $params = func_get_args(); $name = array_shift($params); if (isset(self::$_hooks[$name])) { $obj = new self::$_hooks[$name](); return $obj->init(...$params); } } }
<?php namespace SlaxWeb\Hooks; class Hooks { protected static $_hooks = []; public static function set(array $hook) { if ((isset($hook["name"]) && isset($hook["class"])) === false) { return false; } self::$_hooks[$hook["name"]] = $hook["class"]; return true; } public static function call() { $params = func_get_args(); $name = array_shift($params); if (isset(self::$_hooks[$name])) { $obj = new self::$_hooks[$name](); $obj->init(...$params); } } }
Fix extra colon in status_code key
import sys import os import json import unittest import xmlrunner from flask import Flask, Response from flask_sqlalchemy import SQLAlchemy from flask_restful import Api from flask_script import Manager, Server, prompt_bool from flask_migrate import Migrate, MigrateCommand app = Flask(__name__) app.config.from_pyfile('settings.py') db = SQLAlchemy(app) migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand) manager.add_command("runserver", Server(port=app.config["PORT"])) @manager.command def dropdb(): if prompt_bool( "Are you sure you want to lose all your data?"): db.drop_all() # Method used to unify responses sintax def build_response(status_code, description="", error="", data=""): jd = {"status_code" : status_code, "error": error, "description": description, "data": data} resp = Response(response=json.dumps(jd), status=status_code, mimetype="application/json") return resp from routes.licenses import * from routes.types import * api = Api(app) api.add_resource(TypesList, '/api/v1/types/') api.add_resource(Types, '/api/v1/types/<typeID>/') api.add_resource(LicensesList, '/api/v1/licenses/') api.add_resource(Licenses, '/api/v1/licenses/<licenseID>/')
import sys import os import json import unittest import xmlrunner from flask import Flask, Response from flask_sqlalchemy import SQLAlchemy from flask_restful import Api from flask_script import Manager, Server, prompt_bool from flask_migrate import Migrate, MigrateCommand app = Flask(__name__) app.config.from_pyfile('settings.py') db = SQLAlchemy(app) migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand) manager.add_command("runserver", Server(port=app.config["PORT"])) @manager.command def dropdb(): if prompt_bool( "Are you sure you want to lose all your data?"): db.drop_all() # Method used to unify responses sintax def build_response(status_code, description="", error="", data=""): jd = {"status_code:" : status_code, "error": error, "description": description, "data": data} resp = Response(response=json.dumps(jd), status=status_code, mimetype="application/json") return resp from routes.licenses import * from routes.types import * api = Api(app) api.add_resource(TypesList, '/api/v1/types/') api.add_resource(Types, '/api/v1/types/<typeID>/') api.add_resource(LicensesList, '/api/v1/licenses/') api.add_resource(Licenses, '/api/v1/licenses/<licenseID>/')
Remove echo, so undot() can be used like str_replace()
<?php /* * Layout functions */ // `encrypt` // // Encrypts `$data` with base64. function encrypt($data) { echo base64_encode($data); } // `decrypt` // // Decrypts `$data` with base64. function decrypt($data) { echo base64_decode($data); } // `is_currentfile` // // Checks for current file. Change the target class name if necessary. function is_currentfile($file) { if (strpos($_SERVER['PHP_SELF'], $file)) { echo 'class="active"'; } } // `filecount` // // Counts number of files in a directory. `$dir` must be without a trailing // slash. function filecount($dir) { $i = 0; foreach (glob($dir . '/*') as $file) { if (!is_dir($file)) { $i++; } } echo $i; } // `feedparse` // // Parses RSS or Atom feed. function feedparse($url) { $feed = fopen($url, 'r'); $data = stream_get_contents($feed); fclose($feed); echo $data; } // `randomize` // // Selects a random value from array. function randomize($array) { echo $array[array_rand($array)]; } // `undot` // // Removes dots from string. function undot($string) { $string = str_replace('.', '', $string); }
<?php /* * Layout functions */ // `encrypt` // // Encrypts `$data` with base64. function encrypt($data) { echo base64_encode($data); } // `decrypt` // // Decrypts `$data` with base64. function decrypt($data) { echo base64_decode($data); } // `is_currentfile` // // Checks for current file. Change the target class name if necessary. function is_currentfile($file) { if (strpos($_SERVER['PHP_SELF'], $file)) { echo 'class="active"'; } } // `filecount` // // Counts number of files in a directory. `$dir` must be without a trailing // slash. function filecount($dir) { $i = 0; foreach (glob($dir . '/*') as $file) { if (!is_dir($file)) { $i++; } } echo $i; } // `feedparse` // // Parses RSS or Atom feed. function feedparse($url) { $feed = fopen($url, 'r'); $data = stream_get_contents($feed); fclose($feed); echo $data; } // `randomize` // // Selects a random value from array. function randomize($array) { echo $array[array_rand($array)]; } // `undot` // // Removes dots from string. function undot($string) { $string = str_replace('.', '', $string); echo $string; }
Drop Boilerplate <IE8 classes; wp_title cleanup
<!DOCTYPE html> <!--[if IE 8]><html class="no-js lt-ie9" <?php language_attributes(); ?>><![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" <?php language_attributes(); ?>> <!--<![endif]--> <head> <meta charset="utf-8"> <title><?php wp_title(''); ?></title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="icon" type="image/x-icon" href="/favicon.ico" /> <?php wp_head(); ?> <?php if (wp_count_posts()->publish > 0) : ?> <link rel="alternate" type="application/rss+xml" title="<?php echo get_bloginfo('name'); ?> Feed" href="<?php echo home_url(); ?>/feed/"> <?php endif; ?> </head>
<!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" <?php language_attributes(); ?>> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" <?php language_attributes(); ?>> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" <?php language_attributes(); ?>> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" <?php language_attributes(); ?>> <!--<![endif]--> <head> <meta charset="utf-8"> <title><?php wp_title('|', true, 'right'); bloginfo('name'); ?></title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="icon" type="image/x-icon" href="/favicon.ico" /> <?php wp_head(); ?> <?php if (wp_count_posts()->publish > 0) : ?> <link rel="alternate" type="application/rss+xml" title="<?php echo get_bloginfo('name'); ?> Feed" href="<?php echo home_url(); ?>/feed/"> <?php endif; ?> </head>
Make splitVarName a static method
const DocumentedItem = require('./item'); class DocumentedVarType extends DocumentedItem { registerMetaInfo(data) { this.directData = data; } serialize() { const names = []; for(const name of this.directData.names) names.push(this.constructor.splitVarName(name)); return { types: names }; } static splitVarName(str) { if(str === '*') return ['*', '']; const matches = str.match(/([\w]+)([^\w]+)/g); const output = []; if(matches) { for(const match of matches) { const groups = match.match(/([\w]+)([^\w]+)/); output.push([groups[1], groups[2]]); } } else { output.push([str.match(/(\w+)/g)[0], '']); } return output; } } /* { "names":[ "String" ] } */ module.exports = DocumentedVarType;
const DocumentedItem = require('./item'); class DocumentedVarType extends DocumentedItem { registerMetaInfo(data) { this.directData = data; } serialize() { const names = []; for(const name of this.directData.names) names.push(splitVarName(name)); return { types: names }; } } /* { "names":[ "String" ] } */ function splitVarName(str) { if(str === '*') return ['*', '']; const matches = str.match(/([\w]+)([^\w]+)/g); const output = []; if(matches) { for(const match of matches) { const groups = match.match(/([\w]+)([^\w]+)/); output.push([groups[1], groups[2]]); } } else { output.push([str.match(/(\w+)/g)[0], '']); } return output; } module.exports = DocumentedVarType;
Rename database migration for compatibility
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class LaravelStaplerImagesCreateImages extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('images', function(Blueprint $table) { $table->increments('id'); $table->string('url'); $table->string('sizes_md5')->nullable(); $table->string('image_file_name')->nullable(); $table->integer('image_file_size')->nullable(); $table->string('image_content_type')->nullable(); $table->datetime('image_updated_at')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('images'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateImages extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('images', function(Blueprint $table) { $table->increments('id'); $table->string('url'); $table->string('sizes_md5')->nullable(); $table->string('image_file_name')->nullable(); $table->integer('image_file_size')->nullable(); $table->string('image_content_type')->nullable(); $table->datetime('image_updated_at')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('images'); } }
Add test that changing the request struct doesn't affect logging
package log import ( "bytes" "log" "net/http" "net/http/httptest" "regexp" "testing" ) func TestCommonLogHandler(t *testing.T) { h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { r.URL.Path = "/changed" w.Header().Set("X-Path", r.URL.Path) w.Write([]byte("Testing 1 2 3")) }) // output := "" logw := bytes.NewBuffer(nil) // logw.Write([]byte("testing")) // log.Println(logw.String()) testlog := log.New(logw, "", 0) ts := httptest.NewServer(CommonLogHandler(testlog, h)) defer ts.Close() res, err := http.Get(ts.URL + "/foo/bar") if err != nil { t.Fatal(err) } e := regexp.MustCompile(`^127.0.0.1:\d+ - - [.+] "GET /foo/bar HTTP/1.1" 200 13$`) g := logw.String() if e.MatchString(g) { t.Errorf("test 1: got %s, want %s", g, e) } res.Body.Close() }
package log import ( "bytes" "log" "net/http" "net/http/httptest" "regexp" "testing" ) func TestCommonLogHandler(t *testing.T) { h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-Path", r.URL.Path) w.Write([]byte("Testing 1 2 3")) }) // output := "" logw := bytes.NewBuffer(nil) // logw.Write([]byte("testing")) // log.Println(logw.String()) testlog := log.New(logw, "", 0) ts := httptest.NewServer(CommonLogHandler(testlog, h)) defer ts.Close() res, err := http.Get(ts.URL + "/foo/bar") if err != nil { t.Fatal(err) } e := regexp.MustCompile(`^127.0.0.1:\d+ - - [.+] "GET /foo/bar HTTP/1.1" 200 13$`) g := logw.String() if e.MatchString(g) { t.Errorf("test 1: got %s, want %s", g, e) } res.Body.Close() }
Disable template caching for now.
import os import tornado.web from tornado.options import define from .handlers import LandingHandler, RequestHandler class InteractApp(tornado.web.Application): """ Entry point for the interact app. """ def __init__(self, config=None): # Terrible hack to get config object in global namespace. This allows # us to use options.config to get the global config object. # # TODO(sam): Replace with a better solution define('config', config) base_url = config['URL'] socket_url = config['URL'] + 'socket/(\w+)' settings = dict( debug=True, serve_traceback=True, compiled_template_cache=False, template_path=os.path.join(os.path.dirname(__file__), "templates"), static_path="/srv/interact/app/static", static_url_prefix="/hub/interact/static/", ) static_url = "r{}/static/(.*)".format(base_url) handlers = [ (base_url, LandingHandler), (socket_url, RequestHandler), ] super(InteractApp, self).__init__(handlers, **settings)
import os import tornado.web from tornado.options import define from .handlers import LandingHandler, RequestHandler class InteractApp(tornado.web.Application): """ Entry point for the interact app. """ def __init__(self, config=None): # Terrible hack to get config object in global namespace. This allows # us to use options.config to get the global config object. # # TODO(sam): Replace with a better solution define('config', config) base_url = config['URL'] socket_url = config['URL'] + 'socket/(\w+)' settings = dict( debug=True, serve_traceback=True, template_path=os.path.join(os.path.dirname(__file__), "templates"), static_path="/srv/interact/app/static", static_url_prefix="/hub/interact/static/", ) static_url = "r{}/static/(.*)".format(base_url) handlers = [ (base_url, LandingHandler), (socket_url, RequestHandler), ] super(InteractApp, self).__init__(handlers, **settings)
Annotate scenegraph group items with runtime context.
import {Transform} from 'vega-dataflow'; import {Item, GroupItem} from 'vega-scenegraph'; import {inherits} from 'vega-util'; /** * Bind scenegraph items to a scenegraph mark instance. * @constructor * @param {object} params - The parameters for this operator. * @param {object} params.markdef - The mark definition for creating the mark. * This is an object of legal scenegraph mark properties which *must* include * the 'marktype' property. * @param {Array<number>} params.scenepath - Scenegraph tree coordinates for the mark. * The path is an array of integers, each indicating the index into * a successive chain of items arrays. */ export default function Mark(params) { Transform.call(this, null, params); } var prototype = inherits(Mark, Transform); prototype.transform = function(_, pulse) { var mark = this.value; // acquire mark on first invocation if (!mark) { mark = pulse.dataflow.scenegraph().mark(_.scenepath, _.markdef); mark.source = this; this.value = mark; mark.group.context = _.scenepath.context; } // initialize entering items var Init = mark.marktype === 'group' ? GroupItem : Item; pulse.visit(pulse.ADD, function(item) { Init.call(item, mark); }); // bind items array to scenegraph mark return (mark.items = pulse.source, pulse); };
import {Transform} from 'vega-dataflow'; import {Item, GroupItem} from 'vega-scenegraph'; import {inherits} from 'vega-util'; /** * Bind scenegraph items to a scenegraph mark instance. * @constructor * @param {object} params - The parameters for this operator. * @param {object} params.markdef - The mark definition for creating the mark. * This is an object of legal scenegraph mark properties which *must* include * the 'marktype' property. * @param {Array<number>} params.scenepath - Scenegraph tree coordinates for the mark. * The path is an array of integers, each indicating the index into * a successive chain of items arrays. */ export default function Mark(params) { Transform.call(this, null, params); } var prototype = inherits(Mark, Transform); prototype.transform = function(_, pulse) { var mark = this.value; // acquire mark on first invocation if (!mark) { mark = pulse.dataflow.scenegraph().mark(_.scenepath, _.markdef); mark.source = this; this.value = mark; } // initialize entering items var Init = mark.marktype === 'group' ? GroupItem : Item; pulse.visit(pulse.ADD, function(item) { Init.call(item, mark); }); // bind items array to scenegraph mark return (mark.items = pulse.source, pulse); };
Fix path existence ensuring function
const fs = require('fs') const glob = require('glob') const outputDirectory = [process.argv[2] || 'snapshots'] .filter(x => x) .join('/') const createDir = dir => { const splitPath = dir.split('/') splitPath.reduce((path, subPath) => { if (path && !fs.existsSync(path)) { console.log(`Create directory at ${path}.`); fs.mkdirSync(path) } return `${path}/${subPath}` }) } glob('src/__snapshots__/*.snap', {}, (er, files) => { console.log({ argv: process.argv }) files.forEach(fileName => { const newName = fileName .replace(/__snapshots__\//g, '') .replace('src/', `${outputDirectory}/`) console.log(`Move file ${fileName} to ${newName}.`); createDir(newName) fs.renameSync(fileName, newName) }) glob('src/__snapshots__', {}, (er, files) => { files.forEach(fileName => { fs.rmdirSync(fileName) }) }) })
const fs = require('fs') const glob = require('glob') const outputDirectory = [process.argv[2] || 'snapshots'] .filter(x => x) .join('/') const createDir = dir => { const splitPath = dir.split('/') splitPath.reduce((path, subPath) => { if (!fs.existsSync(path)) { console.log(`Create directory at ${path}.`); fs.mkdirSync(path) } return `${path}/${subPath}` }) } glob('src/__snapshots__/*.snap', {}, (er, files) => { console.log({ argv: process.argv }) files.forEach(fileName => { const newName = fileName .replace(/__snapshots__\//g, '') .replace('src/', `${outputDirectory}/`) console.log(`Move file ${fileName} to ${newName}.`); createDir(newName) fs.renameSync(fileName, newName) }) glob('src/__snapshots__', {}, (er, files) => { files.forEach(fileName => { fs.rmdirSync(fileName) }) }) })
Add classifiers for Python 2 and 3
# # setup.py # # Copyright (c) 2013 Luis Garcia. # This source file is subject to terms of the MIT License. (See file LICENSE) # """Setup script for the scope library.""" from distutils.core import setup NAME = 'scope' VERSION = '0.1.1' DESCRIPTION = 'Template library for multi-language code generation' AUTHOR = 'Luis Garcia' AUTHOR_EMAIL = 'lgarcia@codespot.in' URL = 'https://github.com/lrgar/scope' CLASSIFIERS = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: C++', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Code Generators', 'Topic :: Software Development :: Libraries' ] LICENSE = 'MIT' setup( name=NAME, version=VERSION, description=DESCRIPTION, author=AUTHOR, author_email=AUTHOR_EMAIL, url=URL, packages=['scope', 'scope.lang'], license=LICENSE, classifiers=CLASSIFIERS )
# # setup.py # # Copyright (c) 2013 Luis Garcia. # This source file is subject to terms of the MIT License. (See file LICENSE) # """Setup script for the scope library.""" from distutils.core import setup NAME = 'scope' VERSION = '0.1.1' DESCRIPTION = 'Template library for multi-language code generation' AUTHOR = 'Luis Garcia' AUTHOR_EMAIL = 'lgarcia@codespot.in' URL = 'https://github.com/lrgar/scope' CLASSIFIERS = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: C++', 'Programming Language :: Python', 'Topic :: Software Development :: Code Generators', 'Topic :: Software Development :: Libraries' ] LICENSE = 'MIT' setup( name=NAME, version=VERSION, description=DESCRIPTION, author=AUTHOR, author_email=AUTHOR_EMAIL, url=URL, packages=['scope', 'scope.lang'], license=LICENSE, classifiers=CLASSIFIERS )
Set config logging in init to debug
import os, logging from flask import Flask from flask.ext.basicauth import BasicAuth from raven.contrib.flask import Sentry app = Flask(__name__) app.config.from_object(os.environ.get('SETTINGS')) if app.config.get('BASIC_AUTH_USERNAME'): app.config['BASIC_AUTH_FORCE'] = True basic_auth = BasicAuth(app) # Sentry exception reporting if 'SENTRY_DSN' in os.environ: sentry = Sentry(app, dsn=os.environ['SENTRY_DSN']) if not app.debug: app.logger.addHandler(logging.StreamHandler()) app.logger.setLevel(logging.INFO) app.logger.debug("\nConfiguration\n%s\n" % app.config) @app.context_processor def asset_path_context_processor(): return { 'asset_path': '/static/build/', 'landregistry_asset_path': '/static/build/' } @app.context_processor def address_processor(): from lrutils import build_address def process_address_json(address_json): return build_address(address_json) return dict(formatted=process_address_json)
import os, logging from flask import Flask from flask.ext.basicauth import BasicAuth from raven.contrib.flask import Sentry app = Flask(__name__) app.config.from_object(os.environ.get('SETTINGS')) if app.config.get('BASIC_AUTH_USERNAME'): app.config['BASIC_AUTH_FORCE'] = True basic_auth = BasicAuth(app) # Sentry exception reporting if 'SENTRY_DSN' in os.environ: sentry = Sentry(app, dsn=os.environ['SENTRY_DSN']) if not app.debug: app.logger.addHandler(logging.StreamHandler()) app.logger.setLevel(logging.INFO) app.logger.info("\nConfiguration\n%s\n" % app.config) @app.context_processor def asset_path_context_processor(): return { 'asset_path': '/static/build/', 'landregistry_asset_path': '/static/build/' } @app.context_processor def address_processor(): from lrutils import build_address def process_address_json(address_json): return build_address(address_json) return dict(formatted=process_address_json)
Add background and text color
// Dependencies var CaptchaPng = require("captchapng"); // Sessions var sessions = {}; // Captcha configuration var serverConfig = { width: 100, height: 30 }; // Get configuration M.emit("captcha.getConfig", function (c) { serverConfig = c; }); // Verify captcha M.on("captcha.verify", function (link, answer, callback) { var sid = link.session && link.session._sid; callback(answer === sessions[sid]); }); /** * captcha * Serves the captcha image * * @name captcha * @function * @param {Object} link Mono link object * @return */ exports.captcha = function (link) { var res = link.res; // Generate number and store it in sessions cache var number = parseInt(Math.random() * 9000 + 1000); if (!link.session || !link.session._sid) { sessions[link.session._sid] = number; } var cap = new CaptchaPng(serverConfig.width, serverConfig.height, number); cap.color(0, 100, 0, 0); cap.color(80, 80, 80, 255); var img = cap.getBase64(); var imgBase64 = new Buffer(img, "base64"); res.writeHead(200, { "Content-Type": "image/png" }); res.end(imgBase64); };
// Dependencies var CaptchaPng = require("captchapng"); // Sessions var sessions = {}; // Captcha configuration var serverConfig = { width: 100, height: 30 }; // Get configuration M.emit("captcha.getConfig", function (c) { serverConfig = c; }); // Verify captcha M.on("captcha.verify", function (link, answer, callback) { var sid = link.session && link.session._sid; callback(answer === sessions[sid]); }); /** * captcha * Serves the captcha image * * @name captcha * @function * @param {Object} link Mono link object * @return */ exports.captcha = function (link) { var res = link.res; // Generate number and store it in sessions cache var number = parseInt(Math.random() * 9000 + 1000); if (!link.session || !link.session._sid) { sessions[link.session._sid] = number; } var cap = new CaptchaPng(serverConfig.width, serverConfig.height, number); var img = cap.getBase64(); var imgBase64 = new Buffer(img, "base64"); res.writeHead(200, { "Content-Type": "image/png" }); res.end(imgBase64); };
Remove formvalidation test as it is not being used
/* * ADR Reporting * Copyright (C) 2017 Divay Prakash * GNU Affero General Public License 3.0 (https://github.com/divayprakash/adr/blob/master/LICENSE) */ var dataUriTest; Modernizr.on('datauri', function(result) { dataUriTest = result.valueOf() && result.over32kb; var hiddenTest = Modernizr.hidden; var inputTest = Modernizr.input.max && Modernizr.input.min && Modernizr.input.placeholder && Modernizr.input.step; var inputTypesTest = Modernizr.inputtypes.date && Modernizr.inputtypes.email && Modernizr.inputtypes.number && Modernizr.inputtypes.range && Modernizr.inputtypes.tel; var mediaQueriesTest = Modernizr.mediaqueries; var placeholderTest = Modernizr.placeholder; var totalTest = dataUriTest && formValidationTest && hiddenTest && inputTest && inputTypesTest && mediaQueriesTest && placeholderTest; if (totalTest) document.getElementById('warning').style.display = 'none'; else document.getElementById('main-div').style.display = 'none'; });
/* * ADR Reporting * Copyright (C) 2017 Divay Prakash * GNU Affero General Public License 3.0 (https://github.com/divayprakash/adr/blob/master/LICENSE) */ var dataUriTest; Modernizr.on('datauri', function(result) { dataUriTest = result.valueOf() && result.over32kb; var formValidationTest = Modernizr.formvalidation; var hiddenTest = Modernizr.hidden; var inputTest = Modernizr.input.max && Modernizr.input.min && Modernizr.input.placeholder && Modernizr.input.step; var inputTypesTest = Modernizr.inputtypes.date && Modernizr.inputtypes.email && Modernizr.inputtypes.number && Modernizr.inputtypes.range && Modernizr.inputtypes.tel; var mediaQueriesTest = Modernizr.mediaqueries; var placeholderTest = Modernizr.placeholder; var totalTest = dataUriTest && formValidationTest && hiddenTest && inputTest && inputTypesTest && mediaQueriesTest && placeholderTest; if (totalTest) document.getElementById('warning').style.display = 'none'; else document.getElementById('main-div').style.display = 'none'; });
Fix issue where unidentified mac's would not show up in device lists
var express = require('express'); var router = express.Router(); router.get('/', function (req, res, next) { var stat_data = {}; var count = 0; for (var key in dhcp_lease_data) { /** * If we don't have a vendor - set as N/A */ if (dhcp_lease_data[key].mac_oui_vendor === "") { dhcp_lease_data[key].mac_oui_vendor = "N/A"; } /** * Init array */ if (typeof stat_data[(typeof dhcp_lease_data[key].mac_oui_vendor !== "undefined" ? dhcp_lease_data[key].mac_oui_vendor : 'Misc')] === "undefined") stat_data[(typeof dhcp_lease_data[key].mac_oui_vendor !== "undefined" ? dhcp_lease_data[key].mac_oui_vendor : 'Misc')] = 0; let vendor_string = (typeof dhcp_lease_data[key].mac_oui_vendor !== "undefined" && dhcp_lease_data[key].mac_oui_vendor != "" ? dhcp_lease_data[key].mac_oui_vendor : 'Misc'); /** * Increment vendor count */ stat_data[vendor_string]++; } /** * Return JSON response */ res.setHeader('Content-Type', 'application/json'); res.send(JSON.stringify(stat_data)); }); module.exports = router;
var express = require('express'); var router = express.Router(); var fs = require('fs'); router.get('/', function(req, res, next) { var stat_data = {}; var count = 0; for (var key in dhcp_lease_data) { if((typeof dhcp_lease_data[key].mac_oui_vendor !== "undefined" ? dhcp_lease_data[key].mac_oui_vendor : 'Misc') == "") continue; if(typeof stat_data[(typeof dhcp_lease_data[key].mac_oui_vendor !== "undefined" ? dhcp_lease_data[key].mac_oui_vendor : 'Misc')] === "undefined") stat_data[(typeof dhcp_lease_data[key].mac_oui_vendor !== "undefined" ? dhcp_lease_data[key].mac_oui_vendor : 'Misc')] = 0; stat_data[(typeof dhcp_lease_data[key].mac_oui_vendor !== "undefined" && dhcp_lease_data[key].mac_oui_vendor != "" ? dhcp_lease_data[key].mac_oui_vendor : 'Misc')]++; } res.setHeader('Content-Type', 'application/json'); res.send(JSON.stringify(stat_data)); }); module.exports = router;
Disable verbose logging in command line tool.
package main import ( "flag" "fmt" "io/ioutil" "os" "github.com/mat/besticon/besticon" ) func main() { besticon.SetLogOutput(ioutil.Discard) // Disable verbose logging all := flag.Bool("all", false, "Display all Icons, not just the best.") flag.Parse() if len(os.Args) <= 1 { fmt.Fprintf(os.Stderr, "please provide a URL.\n") os.Exit(100) } url := os.Args[len(os.Args)-1] icons, err := besticon.FetchIcons(url) if err != nil { fmt.Fprintf(os.Stderr, "%s: failed to fetch icons: %s\n", url, err) os.Exit(1) } if *all { for _, img := range icons { if img.Width > 0 { fmt.Printf("%s: %s\n", url, img.URL) } } } else { if len(icons) > 0 { best := icons[0] fmt.Printf("%s: %s\n", url, best.URL) } else { fmt.Fprintf(os.Stderr, "%s: no icons found\n", url) os.Exit(2) } } }
package main import ( "flag" "fmt" "github.com/mat/besticon/besticon" "os" ) func main() { all := flag.Bool("all", false, "Display all Icons, not just the best.") flag.Parse() if len(os.Args) <= 1 { fmt.Fprintf(os.Stderr, "please provide a URL.\n") os.Exit(100) } url := os.Args[len(os.Args)-1] icons, err := besticon.FetchIcons(url) if err != nil { fmt.Fprintf(os.Stderr, "%s: failed to fetch icons: %s\n", url, err) os.Exit(1) } if *all { for _, img := range icons { if img.Width > 0 { fmt.Printf("%s: %s\n", url, img.URL) } } } else { if len(icons) > 0 { best := icons[0] fmt.Printf("%s: %s\n", url, best.URL) } else { fmt.Fprintf(os.Stderr, "%s: no icons found\n", url) os.Exit(2) } } }
Fix typo in ifLess helper docs
<?php /* * This file is part of Handlebars.php Helpers Set * * (c) Dmitriy Simushev <simushevds@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace JustBlackBird\HandlebarsHelpers\Comparison; use Handlebars\Helper as HelperInterface; /** * Conditional helper that checks if one value is less than another one. * * By "less" strict inequality is meant. That's why in cases where two equal * values are compared the result of the "less" operation is false. * * Example of usage: * ```handlebars * {{#ifLess first second}} * The first argument is less than the second one. * {{else}} * The first argument is more or equal to the second one. * {{/ifLess}} * ``` * * @author Dmitriy Simushev <simushevds@gmail.com> */ class IfLessHelper extends AbstractComparisonHelper implements HelperInterface { /** * {@inheritdoc} */ protected function evaluateCondition($args) { if (count($args) != 2) { throw new \InvalidArgumentException( '"ifLess" helper expects exactly two arguments.' ); } return ($args[0] < $args[1]); } }
<?php /* * This file is part of Handlebars.php Helpers Set * * (c) Dmitriy Simushev <simushevds@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace JustBlackBird\HandlebarsHelpers\Comparison; use Handlebars\Helper as HelperInterface; /** * Conditional helper that checks if one value is less than another one. * * My "less" strict inequality is meant. That's why in cases where two equal * values are compared the result of the "less" operation is false. * * Example of usage: * ```handlebars * {{#ifLess first second}} * The first argument is less than the second one. * {{else}} * The first argument is more or equal to the second one. * {{/ifLess}} * ``` * * @author Dmitriy Simushev <simushevds@gmail.com> */ class IfLessHelper extends AbstractComparisonHelper implements HelperInterface { /** * {@inheritdoc} */ protected function evaluateCondition($args) { if (count($args) != 2) { throw new \InvalidArgumentException( '"ifLess" helper expects exactly two arguments.' ); } return ($args[0] < $args[1]); } }
Increment version number for release of new features and bug fixes to pypi
__doc__ = """ Manipulate audio with an simple and easy high level interface. See the README file for details, usage info, and a list of gotchas. """ from setuptools import setup setup( name='pydub', version='0.7.0', author='James Robert', author_email='jiaaro@gmail.com', description='Manipulate audio with an simple and easy high level interface', license='MIT', keywords='audio sound high-level', url='http://pydub.com', packages=['pydub'], long_description=__doc__, classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Intended Audience :: Developers', 'Operating System :: OS Independent', "Topic :: Multimedia :: Sound/Audio", "Topic :: Multimedia :: Sound/Audio :: Analysis", "Topic :: Multimedia :: Sound/Audio :: Conversion", "Topic :: Multimedia :: Sound/Audio :: Editors", "Topic :: Multimedia :: Sound/Audio :: Mixers", "Topic :: Software Development :: Libraries", 'Topic :: Utilities', ] )
__doc__ = """ Manipulate audio with an simple and easy high level interface. See the README file for details, usage info, and a list of gotchas. """ from setuptools import setup setup( name='pydub', version='0.6.3', author='James Robert', author_email='jiaaro@gmail.com', description='Manipulate audio with an simple and easy high level interface', license='MIT', keywords='audio sound high-level', url='http://pydub.com', packages=['pydub'], long_description=__doc__, classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Intended Audience :: Developers', 'Operating System :: OS Independent', "Topic :: Multimedia :: Sound/Audio", "Topic :: Multimedia :: Sound/Audio :: Analysis", "Topic :: Multimedia :: Sound/Audio :: Conversion", "Topic :: Multimedia :: Sound/Audio :: Editors", "Topic :: Multimedia :: Sound/Audio :: Mixers", "Topic :: Software Development :: Libraries", 'Topic :: Utilities', ] )
Add method to say Achmed is dead.
package com.github.aureliano.achmed.helper; import java.util.Calendar; public final class EasterEggHelper { private EasterEggHelper() { throw new InstantiationError(this.getClass().getName() + " cannot be instantiated."); } public static String greeting() { Calendar calendar = Calendar.getInstance(); int hour = calendar.get(Calendar.HOUR_OF_DAY); String greetingMessage = null; if ((hour >= 5) && (hour < 12)) { greetingMessage = "morning"; } else if ((hour >= 12) && (hour < 18)) { greetingMessage = "afternoon"; } else if ((hour >= 18) && (hour < 21) || ((hour == 20) && (calendar.get(Calendar.MINUTE) <= 30))) { greetingMessage = "evening"; } else { greetingMessage = "night"; } return "Good " + greetingMessage + "... Infidel!"; } public static String hello() { return "Hey, I just met you and this is crazy. But I will kill you, so silence maybe."; } public static String silence() { return "SILENCE...! I kill you!"; } public static String youAreDead() { return "I'm dead?! But I just got my flu shot!"; } }
package com.github.aureliano.achmed.helper; import java.util.Calendar; public final class EasterEggHelper { private EasterEggHelper() { throw new InstantiationError(this.getClass().getName() + " cannot be instantiated."); } public static String greeting() { Calendar calendar = Calendar.getInstance(); int hour = calendar.get(Calendar.HOUR_OF_DAY); String greetingMessage = null; if ((hour >= 5) && (hour < 12)) { greetingMessage = "morning"; } else if ((hour >= 12) && (hour < 18)) { greetingMessage = "afternoon"; } else if ((hour >= 18) && (hour < 21) || ((hour == 20) && (calendar.get(Calendar.MINUTE) <= 30))) { greetingMessage = "evening"; } else { greetingMessage = "night"; } return "Good " + greetingMessage + "... Infidel!"; } public static String hello() { return "Hey, I just met you and this is crazy. But I will kill you, so silence maybe."; } public static String silence() { return "SILENCE...! I kill you!"; } public static String yourAreDead() { return "I'm dead?! But I just got my flu shot!"; } }
Use HTML in example project and fix linking to wrong file
var sys = require('sys'); var posix = require('posix'); var path = require('path'); var HTTP301MovedPermanently = require('bomberjs/lib/http_responses').HTTP301MovedPermanently; function htmlHead () { return '<html><head><title>Bomber.js example app</title></head><body>'; } function htmlFoot () { return '</body></html>'; } exports.index = function(request, response) { var html = htmlHead(); html += "<h1>index action</h1><p>See <tt>routes.js</tt> for more.</p>"; html += "<p>Other actions include:</p>"; html += "<ul><li><a href='/section/1000'>section/1000</a></li>"; html += "<li><a href='/section/2'>section/2 (special case)</a></li>"; html += "<li><a href='/simple/lorem'>lorem</a></li>"; html += "</ul>"; html += htmlFoot(); return html; }; exports.show = function(request, response) { if( request.params.id == 2 ) { return new HTTP301MovedPermanently('http://google.com'); } else { return htmlHead() + "show action" + htmlFoot(); } }; // can be accessed at /simple/lorem exports.lorem = function(request, response) { // posix.cat returns a Node promise. Which at this time isn't chainable // so this example is pretty simple. But once we can chain, I'll show // how to manipulate the result as you move through the chain. var filename = path.join(path.dirname(__filename),'../resources/text.txt'); return posix.cat(filename); };
var sys = require('sys'); var posix = require('posix'); var path = require('path'); var HTTP301MovedPermanently = require('bomberjs/lib/http_responses').HTTP301MovedPermanently; exports.index = function(request, response) { return "index action"; }; exports.show = function(request, response) { if( request.params.id == 2 ) { return new HTTP301MovedPermanently('http://google.com'); } else { return "show action"; } }; // can be accessed at /simple/lorem exports.lorem = function(request, response) { // posix.cat returns a Node promise. Which at this time isn't chainable // so this example is pretty simple. But once we can chain, I'll show // how to manipulate the result as you move through the chain. var filename = path.join(path.dirname(__filename),'../resources/lorem-ipsum.txt'); return posix.cat(filename); };
Create log directory if does'nt exist.
<?php namespace Rad\Logging\Adapter; use Rad\Logging\AbstractAdapter; /** * File Adapter * * @package Rad\Logging\Adapter */ class FileAdapter extends AbstractAdapter { protected $handle; /** * Rad\Logging\Adapter\FileAdapter constructor * * @param string $filePath Log file path */ public function __construct($filePath) { $dirPath = dirname($filePath); if (false === is_dir($dirPath)) { mkdir($dirPath, 0775, true); } if (substr($filePath, -4) !== '.log') { $filePath .= '.log'; } $this->handle = fopen($filePath, 'ab+'); } /** * Rad\Logging\Adapter\FileAdapter destructor */ public function __destruct() { $this->close(); } /** * Closes an open file pointer * * @return bool */ public function close() { return fclose($this->handle); } /** * {@inheritdoc} */ public function log($level, $message, $time, array $context = []) { fwrite($this->handle, $this->getFormatter()->format($level, $message, $time, $context)); } }
<?php namespace Rad\Logging\Adapter; use Rad\Logging\AbstractAdapter; /** * File Adapter * * @package Rad\Logging\Adapter */ class FileAdapter extends AbstractAdapter { protected $handle; /** * Rad\Logging\Adapter\FileAdapter constructor * * @param string $filePath Log file path */ public function __construct($filePath) { $this->handle = fopen($filePath, 'ab+'); } /** * Rad\Logging\Adapter\FileAdapter destructor */ public function __destruct() { $this->close(); } /** * Closes an open file pointer * * @return bool */ public function close() { return fclose($this->handle); } /** * {@inheritdoc} */ public function log($level, $message, $time, array $context = []) { fwrite($this->handle, $this->getFormatter()->format($level, $message, $time, $context)); } }
Work around bug in Safari styling of search input fields.
/** * @license * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ foam.CLASS({ package: 'foam.u2', name: 'TextField', extends: 'foam.u2.tag.Input', css: ` input[type="search"] { -webkit-appearance: textfield !important; } ^:read-only { border: none; background: rgba(0,0,0,0); } `, properties: [ { class: 'Int', name: 'displayWidth' } ], methods: [ function fromProperty(prop) { this.SUPER(prop); if ( ! this.displayWidth ) { this.size = this.displayWidth = prop.displayWidth; } if ( prop.visibility ) { this.visibility = prop.visibility; } } ] });
/** * @license * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ foam.CLASS({ package: 'foam.u2', name: 'TextField', extends: 'foam.u2.tag.Input', axioms: [ foam.u2.CSS.create({ code: '^:read-only { border: none; background: rgba(0,0,0,0); }' }) ], properties: [ { class: 'Int', name: 'displayWidth' } ], methods: [ function fromProperty(prop) { this.SUPER(prop); if ( ! this.displayWidth ) { this.size = this.displayWidth = prop.displayWidth; } if ( prop.visibility ) { this.visibility = prop.visibility; } } ] });
Revise tests to use np.testing.assert_allclose this is better - if na values mismatch (e,g, na in result where expected has a value) this errors and gives a message to that effect. the previous one just errored and it was very hard to tell why
import os import pytest import pandas as pd from glob import glob import numpy as np from gypsy import DATA_DIR from gypsy.forward_simulation import simulate_forwards_df TEST_FILES = glob(os.path.join(DATA_DIR, 'forward_simulation_files', '*.csv')) TEST_FILES = [(item) for item in TEST_FILES] CHART_FILES = glob(os.path.join(DATA_DIR, 'output', 'comparisons*.csv')) CHART_FILES = [(item) for item in CHART_FILES] @pytest.mark.parametrize("test_file", TEST_FILES) def test_compare_forward_simulation(test_file): input_df = pd.read_csv(test_file) expected_data_path = os.path.join( DATA_DIR, 'output', 'comparisons_{}'.format(os.path.basename(test_file)) ) plot_id = str(int(input_df.loc[0, 'PlotID'])) result = simulate_forwards_df(input_df, simulation_choice='yes')[plot_id] expected = pd.read_csv(expected_data_path, index_col=0) assert isinstance(result, pd.DataFrame) assert np.testing.assert_allclose( expected.values, result.values, rtol=0, atol=1e-4, equal_nan=True ) # regenerate output files # result.to_csv(expected_data_path)
import os import pytest import pandas as pd from glob import glob import numpy as np from gypsy import DATA_DIR from gypsy.forward_simulation import simulate_forwards_df TEST_FILES = glob(os.path.join(DATA_DIR, 'forward_simulation_files', '*.csv')) TEST_FILES = [(item) for item in TEST_FILES] CHART_FILES = glob(os.path.join(DATA_DIR, 'output', 'comparisons*.csv')) CHART_FILES = [(item) for item in CHART_FILES] @pytest.mark.parametrize("test_file", TEST_FILES) def test_compare_forward_simulation(test_file): input_df = pd.read_csv(test_file) expected_data_path = os.path.join( DATA_DIR, 'output', 'comparisons_{}'.format(os.path.basename(test_file)) ) plot_id = str(int(input_df.loc[0, 'PlotID'])) result = simulate_forwards_df(input_df, simulation_choice='yes')[plot_id] expected = pd.read_csv(expected_data_path, index_col=0) assert isinstance(result, pd.DataFrame) assert np.allclose( expected.values.astype(np.float64), result.values.astype(np.float64), equal_nan=True ) # regenerate output files # result.to_csv(expected_data_path)
8: Create documentation of DataSource Settings Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions cell = AdminControl.getCell() cellname = "/Cell:" + cell + "/" # Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines() dblist = [] for db in dbs: db = db.split('(') n = 0 for i in db: if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource': dblist.append(str(i).replace('"','')) n += 1 print dblist for db in dblist: print db # for db in dbs: # t1 = ibmcnx.functions.getDSId( db ) # AdminConfig.show( t1 ) # print '\n\n' # AdminConfig.showall( t1 ) # AdminConfig.showAttribute(t1,'statementCacheSize' ) # AdminConfig.showAttribute(t1,'[statementCacheSize]' )
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions cell = AdminControl.getCell() cellname = "/Cell:" + cell + "/" # Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines() dblist = [] for db in dbs: db = db.split('(') n = 0 for i in db: if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource': dblist.append(str(i).replace('"','')) n += 1 print dblist for db in dblist: print 'db' # for db in dbs: # t1 = ibmcnx.functions.getDSId( db ) # AdminConfig.show( t1 ) # print '\n\n' # AdminConfig.showall( t1 ) # AdminConfig.showAttribute(t1,'statementCacheSize' ) # AdminConfig.showAttribute(t1,'[statementCacheSize]' )
Fix ExtensionManagementApiBrowserTest.LaunchApp to no longer be order-dependent. With the break, it fails if the app happens to come before the extension in items. BUG=104091 TEST=none TBR=asargent@chromium.org Review URL: http://codereview.chromium.org/8801037 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@113141 0039d316-1c4b-4281-b951-d872f2087c98
// Copyright (c) 2011 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. window.onload = function() { chrome.management.getAll(function(items) { for (var i in items) { var item = items[i]; if (item.name == "packaged_app") { chrome.management.launchApp(item.id); } if (item.name == "simple_extension") { // Try launching a non-app extension, which should fail. var expected_error = "Extension " + item.id + " is not an App"; chrome.management.launchApp(item.id, function() { if (chrome.extension.lastError && chrome.extension.lastError.message == expected_error) { chrome.test.sendMessage("got_expected_error"); } }); } } }); };
// Copyright (c) 2010 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. window.onload = function() { chrome.management.getAll(function(items) { for (var i in items) { var item = items[i]; if (item.name == "packaged_app") { chrome.management.launchApp(item.id); break; } if (item.name == "simple_extension") { // Try launching a non-app extension, which should fail. var expected_error = "Extension " + item.id + " is not an App"; chrome.management.launchApp(item.id, function() { if (chrome.extension.lastError && chrome.extension.lastError.message == expected_error) { chrome.test.sendMessage("got_expected_error"); } }); } } }); };
Fix empty array in rest calls.
package com.kogimobile.android.baselibrary.rest.utils; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import java.lang.reflect.Type; import java.util.Collection; /** * Created by Julian Cardona on 5/21/15. */ public class CollectionTypedAdapter implements JsonSerializer<Collection<?>> { @Override public JsonElement serialize(Collection<?> src, Type typeOfSrc, JsonSerializationContext context) { if (src == null) // exclusion is made here return null; JsonArray array = new JsonArray(); for (Object child : src) { JsonElement element = context.serialize(child); array.add(element); } return array; } }
package com.kogimobile.android.baselibrary.rest.utils; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import java.lang.reflect.Type; import java.util.Collection; /** * Created by Julian Cardona on 5/21/15. */ public class CollectionTypedAdapter implements JsonSerializer<Collection<?>> { @Override public JsonElement serialize(Collection<?> src, Type typeOfSrc, JsonSerializationContext context) { if (src == null || src.isEmpty()) // exclusion is made here return null; JsonArray array = new JsonArray(); for (Object child : src) { JsonElement element = context.serialize(child); array.add(element); } return array; } }
Fix legacy use of action result
#!/usr/bin/env python # # Get the sysdig secure user rules file. # import os import sys sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdSecureClient # # Parse arguments # if len(sys.argv) != 2: print('usage: %s <sysdig-token>' % sys.argv[0]) print('You can find your token at https://secure.sysdig.com/#/settings/user') sys.exit(1) sdc_token = sys.argv[1] # # Instantiate the SDC client # sdclient = SdSecureClient(sdc_token, 'https://secure.sysdig.com') # # Get the configuration # ok, res = sdclient.get_user_falco_rules() # # Return the result # if ok: sys.stdout.write(res["userRulesFile"]["content"]) else: print(res) sys.exit(1)
#!/usr/bin/env python # # Get the sysdig secure user rules file. # import os import sys sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdSecureClient # # Parse arguments # if len(sys.argv) != 2: print('usage: %s <sysdig-token>' % sys.argv[0]) print('You can find your token at https://secure.sysdig.com/#/settings/user') sys.exit(1) sdc_token = sys.argv[1] # # Instantiate the SDC client # sdclient = SdSecureClient(sdc_token, 'https://secure.sysdig.com') # # Get the configuration # ok, res = sdclient.get_user_falco_rules() # # Return the result # if ok: sys.stdout.write(res[1]["userRulesFile"]["content"]) else: print(res) sys.exit(1)
Fix resize tool demo comments.
""" This demonstrates the resize tool. """ from enable.example_support import DemoFrame, demo_main from enable.api import Component, Container, Window from enable.tools.resize_tool import ResizeTool class Box(Component): resizable = "" def _draw_mainlayer(self, gc, view_bounds=None, mode="default"): with gc: dx, dy = self.bounds x, y = self.position gc.set_fill_color((1.0, 0.0, 0.0, 1.0)) gc.rect(x, y, dx, dy) gc.fill_path() class MyFrame(DemoFrame): def _create_window(self): box = Box(bounds=[100.0, 100.0], position=[50.0, 50.0]) box.tools.append(ResizeTool(component=box, hotspots=set(["top", "left", "right", "bottom", "top left", "top right", "bottom left", "bottom right"]))) container = Container(bounds=[500, 500]) container.add(box) return Window(self, -1, component=container) if __name__ == "__main__": # Save demo so that it doesn't get garbage collected when run within # existing event loop (i.e. from ipython). demo = demo_main(MyFrame)
""" This demonstrates the most basic drawing capabilities using Enable. A new component is created and added to a container. """ from enable.example_support import DemoFrame, demo_main from enable.api import Component, Container, Window from enable.tools.resize_tool import ResizeTool class Box(Component): resizable = "" def _draw_mainlayer(self, gc, view_bounds=None, mode="default"): with gc: dx, dy = self.bounds x, y = self.position gc.set_fill_color((1.0, 0.0, 0.0, 1.0)) gc.rect(x, y, dx, dy) gc.fill_path() class MyFrame(DemoFrame): def _create_window(self): box = Box(bounds=[100.0, 100.0], position=[50.0, 50.0]) box.tools.append(ResizeTool(component=box, hotspots=set(["top", "left", "right", "bottom", "top left", "top right", "bottom left", "bottom right"]))) container = Container(bounds=[500, 500]) container.add(box) return Window(self, -1, component=container) if __name__ == "__main__": # Save demo so that it doesn't get garbage collected when run within # existing event loop (i.e. from ipython). demo = demo_main(MyFrame)
Convert anonymous class to lambda
/* * 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 io.prestosql.orc; import io.prestosql.orc.metadata.statistics.ColumnStatistics; import java.util.Map; public interface OrcPredicate { OrcPredicate TRUE = (numberOfRows, statisticsByColumnIndex) -> true; /** * Should the ORC reader process a file section with the specified statistics. * * @param numberOfRows the number of rows in the segment; this can be used with * {@code ColumnStatistics} to determine if a column is only null * @param statisticsByColumnIndex statistics for column by ordinal position * in the file; this will match the field order from the hive metastore */ boolean matches(long numberOfRows, Map<Integer, ColumnStatistics> statisticsByColumnIndex); }
/* * 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 io.prestosql.orc; import io.prestosql.orc.metadata.statistics.ColumnStatistics; import java.util.Map; public interface OrcPredicate { OrcPredicate TRUE = new OrcPredicate() { @Override public boolean matches(long numberOfRows, Map<Integer, ColumnStatistics> statisticsByColumnIndex) { return true; } }; /** * Should the ORC reader process a file section with the specified statistics. * * @param numberOfRows the number of rows in the segment; this can be used with * {@code ColumnStatistics} to determine if a column is only null * @param statisticsByColumnIndex statistics for column by ordinal position * in the file; this will match the field order from the hive metastore */ boolean matches(long numberOfRows, Map<Integer, ColumnStatistics> statisticsByColumnIndex); }
Update travis-ci settings to use local backend with range queries
# This file is exec'd from settings.py, so it has access to and can # modify all the variables in settings.py. # If this file is changed in development, the development server will # have to be manually restarted because changes will not be noticed # immediately. DEBUG = False # disable compression for tests that check javascript contents COMPRESS_ENABLED = False # include database settings to use Mariadb ver on production (5.5) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'test', 'USER': 'root', 'HOST': 'localhost', 'PORT': '', 'TEST': { 'CHARSET': 'utf8', 'COLLATION': 'utf8_general_ci', }, }, } # must be defined for initial setup HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'derrida.common.solr_backend.RangeSolrEngine', 'URL': 'http://127.0.0.1:8983/solr/test-derrida', 'ADMIN_URL': 'http://127.0.0.1:8983/solr/admin/cores', } } # for unit tests, that swap test connection in for default HAYSTACK_TEST_CONNECTIONS = HAYSTACK_CONNECTIONS # secret key added as a travis build step
# This file is exec'd from settings.py, so it has access to and can # modify all the variables in settings.py. # If this file is changed in development, the development server will # have to be manually restarted because changes will not be noticed # immediately. DEBUG = False # disable compression for tests that check javascript contents COMPRESS_ENABLED = False # include database settings to use Mariadb ver on production (5.5) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'test', 'USER': 'root', 'HOST': 'localhost', 'PORT': '', 'TEST': { 'CHARSET': 'utf8', 'COLLATION': 'utf8_general_ci', }, }, } # must be defined for initial setup HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.solr_backend.SolrEngine', 'URL': 'http://127.0.0.1:8983/solr/test-derrida', 'ADMIN_URL': 'http://127.0.0.1:8983/solr/admin/cores', } } # for unit tests, that swap test connection in for default HAYSTACK_TEST_CONNECTIONS = HAYSTACK_CONNECTIONS # secret key added as a travis build step
Add no Cache-Control header to set it to 'no-cache'
<?php namespace filsh\yii2\oauth2server\controllers; use Yii; use yii\helpers\ArrayHelper; use filsh\yii2\oauth2server\filters\ErrorToExceptionFilter; class DefaultController extends \yii\rest\Controller { /** * @inheritdoc */ public function behaviors() { return ArrayHelper::merge(parent::behaviors(), [ 'exceptionFilter' => [ 'class' => ErrorToExceptionFilter::className() ], ]); } public function actionToken() { $server = $this->module->getServer(); $request = $this->module->getRequest(); $response = $server->handleTokenRequest($request); //Set cache control headers Yii::$app->response->headers['Cache-Control'] = 'no-cache'; Yii::$app->response->headers['Pragma'] = 'no-cache'; return $response->getParameters(); } }
<?php namespace filsh\yii2\oauth2server\controllers; use Yii; use yii\helpers\ArrayHelper; use filsh\yii2\oauth2server\filters\ErrorToExceptionFilter; class DefaultController extends \yii\rest\Controller { /** * @inheritdoc */ public function behaviors() { return ArrayHelper::merge(parent::behaviors(), [ 'exceptionFilter' => [ 'class' => ErrorToExceptionFilter::className() ], ]); } public function actionToken() { $server = $this->module->getServer(); $request = $this->module->getRequest(); $response = $server->handleTokenRequest($request); return $response->getParameters(); } }
Fix filereader to allow reading from jar file
package com.github.alexvictoor.livereload; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Scanner; public class FileReader { public static final Logger logger = LoggerFactory.getLogger(FileReader.class); public String readFileFromClassPath(String classPath) { return new Scanner(getClass().getResourceAsStream(classPath)).useDelimiter("\\Z").next(); //byte[] encoded = Files.readAllBytes(Paths.get(fileURI)); //return new String(encoded, Charset.defaultCharset()); } }
package com.github.alexvictoor.livereload; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; public class FileReader { public String readFileFromClassPath(String classPath) { try { URL resource = getClass().getResource(classPath); if (resource==null) { throw new IllegalArgumentException("Incorrect path file"); } URI fileURI = resource.toURI(); byte[] encoded = Files.readAllBytes(Paths.get(fileURI)); return new String(encoded, Charset.defaultCharset()); } catch (IOException e) { throw new RuntimeException(e); } catch (URISyntaxException e) { throw new RuntimeException(e); } } }
Update return value annotations and update example
'use strict'; /** * Sample elements from an array-like object. * * @module @stdlib/math/generics/random/sample * * @example * var sample = require( '@stdlib/math/generics/random/sample' ); * * var out = sample( 'abc' ); * // e.g., returns [ 'a', 'a', 'b' ] * * out = sample( [ 3, 6, 9 ] ); * // e.g., returns [ 3, 9, 6 ] * * var bool = ( out.length === 3 ); * // returns true * * @example * var sample = require( '@stdlib/math/generics/random/sample' ); * * var mysample = sample.factory( 323 ); * var out = mysample( [ 3, 6, 9 ], { * 'size': 10 * }); * // returns [ 3, 9, 3, 3, 3, 6, 3, 3, 3, 6 ] */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-read-only-property' ); var sample = require( './sample.js' ); var factory = require( './factory.js' ); // METHODS // setReadOnly( sample, 'factory', factory ); // EXPORTS // module.exports = sample;
'use strict'; /** * Sample elements from an array-like object. * * @module @stdlib/math/generics/random/sample * * @example * var sample = require( '@stdlib/math/generics/random/sample' ); * * var out = sample( 'abc' ); * // returns e.g. [ 'a', 'a', 'b' ] * out = sample( [ 3, 6, 9 ] ); * // returns e.g. [ 3, 9, 6 ] * * bool = out.length === 3; * // returns true * * var mysample = sample.factory( 323 ); * out = mysample( [ 3, 6, 9 ], { * 'size': 10 * }); * // returns [ 3, 9, 3, 3, 3, 6, 3, 3, 3, 6 ] */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-read-only-property' ); var sample = require( './sample.js' ); var factory = require( './factory.js' ); // METHODS // setReadOnly( sample, 'factory', factory ); // EXPORTS // module.exports = sample;
Make possible to open youtube links as audio only This add to youtube plugin the ability to open youtube links as audio only (without image, only the control panel)
// Namespace var mejs = mejs || {}; // version number mejs.version = '2.10.3'; // player number (for missing, same id attr) mejs.meIndex = 0; // media types accepted by plugins mejs.plugins = { silverlight: [ {version: [3,0], types: ['video/mp4','video/m4v','video/mov','video/wmv','audio/wma','audio/m4a','audio/mp3','audio/wav','audio/mpeg']} ], flash: [ {version: [9,0,124], types: ['video/mp4','video/m4v','video/mov','video/flv','video/rtmp','video/x-flv','audio/flv','audio/x-flv','audio/mp3','audio/m4a','audio/mpeg', 'video/youtube', 'video/x-youtube']} //,{version: [12,0], types: ['video/webm']} // for future reference (hopefully!) ], youtube: [ {version: null, types: ['video/youtube', 'video/x-youtube', 'audio/youtube', 'audio/x-youtube']} ], vimeo: [ {version: null, types: ['video/vimeo', 'video/x-vimeo']} ] };
// Namespace var mejs = mejs || {}; // version number mejs.version = '2.10.3'; // player number (for missing, same id attr) mejs.meIndex = 0; // media types accepted by plugins mejs.plugins = { silverlight: [ {version: [3,0], types: ['video/mp4','video/m4v','video/mov','video/wmv','audio/wma','audio/m4a','audio/mp3','audio/wav','audio/mpeg']} ], flash: [ {version: [9,0,124], types: ['video/mp4','video/m4v','video/mov','video/flv','video/rtmp','video/x-flv','audio/flv','audio/x-flv','audio/mp3','audio/m4a','audio/mpeg', 'video/youtube', 'video/x-youtube']} //,{version: [12,0], types: ['video/webm']} // for future reference (hopefully!) ], youtube: [ {version: null, types: ['video/youtube', 'video/x-youtube']} ], vimeo: [ {version: null, types: ['video/vimeo', 'video/x-vimeo']} ] };
Add a badge key to the data only if it has been provided and is numeric
<?php namespace Edujugon\PushNotification\Channels; use Edujugon\PushNotification\Messages\PushMessage; class ApnChannel extends PushChannel { /** * {@inheritdoc} */ protected function pushServiceName() { return 'apn'; } /** * {@inheritdoc} */ protected function buildData(PushMessage $message) { $data = [ 'aps' => [ 'alert' => [ 'title' => $message->title, 'body' => $message->body, ], 'sound' => $message->sound, ], ]; if (! empty($message->extra)) { $data['extraPayLoad'] = $message->extra; } if (is_numeric($message->badge)) { $data['aps']['badge'] = $message->badge; } return $data; } }
<?php namespace Edujugon\PushNotification\Channels; use Edujugon\PushNotification\Messages\PushMessage; class ApnChannel extends PushChannel { /** * {@inheritdoc} */ protected function pushServiceName() { return 'apn'; } /** * {@inheritdoc} */ protected function buildData(PushMessage $message) { $data = [ 'aps' => [ 'alert' => [ 'title' => $message->title, 'body' => $message->body, ], 'sound' => $message->sound, 'badge' => $message->badge, ], ]; if (! empty($message->extra)) { $data['extraPayLoad'] = $message->extra; } return $data; } }
Use Email type for `$user->email` field.
<?php namespace ProcessWire\GraphQL\Type; use GraphQL\Type\Definition\ObjectType; use GraphQL\Type\Definition\Type; use ProcessWire\GraphQL\Cache; use ProcessWire\GraphQL\Type\Fieldtype\FieldtypeEmail; class UserType { public static $name = 'User'; public static $description = 'ProcessWire User.'; public static function type() { return Cache::type(self::$name, function () { return new ObjectType([ 'name' => self::$name, 'description' => self::$description, 'fields' => [ 'name' => [ 'type' => Type::nonNull(Type::string()), 'description' => "The user's login name.", ], 'email' => [ 'type' => FieldtypeEmail::type(), 'description' => "The user's email address.", ], 'id' => [ 'type' => Type::nonNull(Type::id()), 'description' => "The user's id.", ], ] ]); }); } }
<?php namespace ProcessWire\GraphQL\Type; use GraphQL\Type\Definition\ObjectType; use GraphQL\Type\Definition\Type; use ProcessWire\GraphQL\Cache; class UserType { public static $name = 'User'; public static $description = 'ProcessWire User.'; public static function type() { return Cache::type(self::$name, function () { return new ObjectType([ 'name' => self::$name, 'description' => self::$description, 'fields' => [ 'name' => [ 'type' => Type::nonNull(Type::string()), 'description' => "The user's login name.", ], 'email' => [ 'type' => Type::nonNull(Type::string()), 'description' => "The user's email address.", ], 'id' => [ 'type' => Type::nonNull(Type::id()), 'description' => "The user's id.", ], ] ]); }); } }
Allow to run PHPStan tests on Windows
<?php declare(strict_types=1); namespace Tests; class PHPStanTest extends AbstractTestCase { protected $phpStanPreviousDirectory = '.'; protected function setUp(): void { parent::setUp(); $this->phpStanPreviousDirectory = getcwd(); chdir(__DIR__.'/../..'); } protected function tearDown(): void { chdir($this->phpStanPreviousDirectory); parent::tearDown(); } public function testAnalysesWithoutErrors(): void { if ($this->analyze(__DIR__.'/Fixture.php') === 0) { $this->assertTrue(true); } } private function analyze(string $file) { $output = shell_exec(implode(' ', [ implode(DIRECTORY_SEPARATOR, ['.', 'vendor', 'bin', 'phpstan']), 'analyse', '--configuration='.escapeshellarg(realpath(__DIR__.'/../../extension.neon')), '--no-progress', '--no-interaction', '--level=0', escapeshellarg(realpath($file)), ])); var_dump($output); return $output; } }
<?php declare(strict_types=1); namespace Tests; class PHPStanTest extends AbstractTestCase { protected $phpStanPreviousDirectory = '.'; protected function setUp(): void { parent::setUp(); $this->phpStanPreviousDirectory = getcwd(); chdir(__DIR__.'/../..'); } protected function tearDown(): void { chdir($this->phpStanPreviousDirectory); parent::tearDown(); } public function testAnalysesWithoutErrors(): void { if ($this->analyze(__DIR__.'/Fixture.php') === 0) { $this->assertTrue(true); } } private function analyze(string $file) { $output = shell_exec( 'vendor/bin/phpstan' . ' analyse' . ' --configuration="' . __DIR__ . '/../../extension.neon"' . ' --no-progress' . ' --no-interaction' . ' --level=0' . ' "' . $file . '"' ); var_dump($output); return $output; } }
Make test call location independent.
#!/usr/bin/env python # vim: set ts=4 sw=4 et sts=4 ai: # # Test some basic functionality. # import unittest import os import sys qpath = os.path.abspath(os.path.join(os.path.split(__file__)[0],'..')) sys.path.insert(0, qpath) class TestQBasic(unittest.TestCase): def setUp(self): if os.path.exists('/tmp/q'): os.remove('/tmp/q') def tearDown(self): self.setUp() def assertInQLog(self, string): self.assertTrue(os.path.exists('/tmp/q')) logdata = open('/tmp/q', 'r').read() try: self.assertIn(string, logdata) except AttributeError: self.assertTrue(string in logdata) def test_q_log_message(self): import q q.q('Test message') self.assertInQLog('Test message') def test_q_function_call(self): import q @q.t def test(arg): return 'RetVal' self.assertEqual('RetVal', test('ArgVal')) self.assertInQLog('ArgVal') self.assertInQLog('RetVal') unittest.main()
#!/usr/bin/env python # vim: set ts=4 sw=4 et sts=4 ai: # # Test some basic functionality. # import unittest import os import sys sys.path.append('..') class TestQBasic(unittest.TestCase): def setUp(self): if os.path.exists('/tmp/q'): os.remove('/tmp/q') def tearDown(self): self.setUp() def assertInQLog(self, string): self.assertTrue(os.path.exists('/tmp/q')) logdata = open('/tmp/q', 'r').read() try: self.assertIn(string, logdata) except AttributeError: self.assertTrue(string in logdata) def test_q_log_message(self): import q q.q('Test message') self.assertInQLog('Test message') def test_q_function_call(self): import q @q.t def test(arg): return 'RetVal' self.assertEqual('RetVal', test('ArgVal')) self.assertInQLog('ArgVal') self.assertInQLog('RetVal') unittest.main()
Update sounds list data view
from flask import Flask, request, jsonify, send_from_directory import os import uuid app = Flask(__name__) UPLOAD_FOLDER = "uploads/" @app.route("/") def index(): return send_from_directory('static/', 'index.html') @app.route("/<path:path>") def serve_static_files(path): return send_from_directory('static/', path) @app.route("/sounds") def get_sounds_list(): if not os.path.isdir(UPLOAD_FOLDER): os.mkdir(UPLOAD_FOLDER) sounds = os.listdir(UPLOAD_FOLDER) _sounds = [] for sound in sounds: _sounds.append({'title': sound, 'filename': sound}) return jsonify({'sounds': _sounds}) @app.route("/sounds/<path:path>") def serve_static(path): return send_from_directory(UPLOAD_FOLDER, path) @app.route("/upload", methods=["POST"]) def upload_file(): file = request.files["file"] if file: if not os.path.isdir(UPLOAD_FOLDER): os.mkdir(UPLOAD_FOLDER) filename = uuid.uuid4().__str__() file.save(os.path.join(UPLOAD_FOLDER, filename)) return filename + "\n" if __name__ == "__main__": app.run(host = "0.0.0.0", debug=True)
from flask import Flask, request, jsonify, send_from_directory import os import uuid app = Flask(__name__) UPLOAD_FOLDER = "uploads/" @app.route("/") def index(): return send_from_directory('static/', 'index.html') @app.route("/<path:path>") def serve_static_files(path): return send_from_directory('static/', path) @app.route("/sounds") def get_sounds_list(): if not os.path.isdir(UPLOAD_FOLDER): os.mkdir(UPLOAD_FOLDER) sounds = os.listdir(UPLOAD_FOLDER) return jsonify({'sounds': sounds}) @app.route("/sounds/<path:path>") def serve_static(path): return send_from_directory(UPLOAD_FOLDER, path) @app.route("/upload", methods=["POST"]) def upload_file(): file = request.files["sound"] if file: if not os.path.isdir(UPLOAD_FOLDER): os.mkdir(UPLOAD_FOLDER) filename = uuid.uuid4().__str__() file.save(os.path.join(UPLOAD_FOLDER, filename)) return filename + "\n" if __name__ == "__main__": app.run(host = "0.0.0.0", debug=True)
Fix min hp and mp
class Status { constructor(currentHp, maxHp, currentMp, maxMp) { currentHp = Math.min(currentHp, maxHp); currentHp = Math.max(currentHp, 0); currentMp = Math.min(currentMp, maxMp); currentMp = Math.max(currentMp, 0); this.currentHp = isNaN(currentHp) ? 0 : currentHp; this.currentMp = isNaN(currentMp) ? 0 : currentMp; this.maxHp = isNaN(maxHp) ? Infinity : maxHp; this.maxMp = isNaN(maxMp) ? Infinity : maxMp; Object.freeze(this); }; changeHp(nextHp) { return new Status(nextHp, this.maxHp, this.currentMp, this.maxMp); } changeMp(nextMp) { return new Status(this.currentHp, this.maxHp, nextMp, this.maxMp); } canCast(spell) { return spell.requiredMp <= this.currentMp; }; isDead() { return this.currentHp <= this.minHp; }; } module.exports = Status;
class Status { constructor(currentHp, maxHp, currentMp, maxMp) { currentHp = Math.min(currentHp, maxHp); currentMp = Math.min(currentMp, maxMp); this.currentHp = isNaN(currentHp) ? 0 : currentHp; this.currentMp = isNaN(currentMp) ? 0 : currentMp; this.maxHp = isNaN(maxHp) ? Infinity : maxHp; this.maxMp = isNaN(maxMp) ? Infinity : maxMp; Object.freeze(this); }; changeHp(nextHp) { return new Status(nextHp, this.maxHp, this.currentMp, this.maxMp); } changeMp(nextMp) { return new Status(this.currentHp, this.maxHp, nextMp, this.maxMp); } canCast(spell) { return spell.requiredMp <= this.currentMp; }; isDead() { return this.currentHp <= this.minHp; }; } module.exports = Status;
Make functional testing compatible with selenium 3.141.0
from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium import webdriver from selenium.webdriver.common.keys import Keys from system_maintenance.tests.utilities import populate_test_db class FunctionalTest(StaticLiveServerTestCase): def setUp(self): populate_test_db() self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) self.username_inputbox = None self.password_inputbox = None self.login_button = None def tearDown(self): self.browser.quit() def find_authentication_elements(self): self.username_inputbox = self.browser.find_element_by_id('id_username') self.password_inputbox = self.browser.find_element_by_id('id_password') self.login_button = self.browser.find_element_by_tag_name('button') def login_as(self, username): self.find_authentication_elements() self.username_inputbox.send_keys(username) self.password_inputbox.send_keys(username) self.login_button.click() def system_maintenance_url(self, url_stem=''): return '{}/system_maintenance/{}'.format( self.live_server_url, url_stem)
from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium import webdriver from selenium.webdriver.common.keys import Keys from system_maintenance.tests.utilities import populate_test_db class FunctionalTest(StaticLiveServerTestCase): def setUp(self): populate_test_db() self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) self.username_inputbox = None self.password_inputbox = None self.login_button = None def tearDown(self): self.browser.quit() def find_authentication_elements(self): self.username_inputbox = self.browser.find_element_by_id('id_username') self.password_inputbox = self.browser.find_element_by_id('id_password') self.login_button = self.browser.find_element_by_tag_name('button') def login_as(self, username): self.find_authentication_elements() self.username_inputbox.send_keys(username) self.password_inputbox.send_keys(username) self.password_inputbox.send_keys(Keys.ENTER) def system_maintenance_url(self, url_stem=''): return '{}/system_maintenance/{}'.format( self.live_server_url, url_stem)
Fix obtaining current URL when using mod_rewrite
<?php /** * Copyright 2016 The Ranger <ranger@risk.ee> * * 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. */ set_include_path(dirname(__FILE__)."/lib"); include_once "config.php"; include_once "Settings.php"; include_once "net/Request.php"; include_once "net/Router.php"; $cwd = getcwd(); chdir(dirname(__FILE__)); $settings = new Settings($GLOBALS["settings"]); $router = new Router($settings); // When invoking with PHP built-in server using router script, REDIRECT_URL is not set // Using Apache mod_rewrite, PHP_SELF would be set to index.php $request = new Request(isset($_SERVER["REDIRECT_URL"]) ? $_SERVER["REDIRECT_URL"] : $_SERVER["PHP_SELF"], $settings); $router->route($request); chdir($cwd);
<?php /** * Copyright 2016 The Ranger <ranger@risk.ee> * * 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. */ set_include_path(dirname(__FILE__)."/lib"); include_once "config.php"; include_once "Settings.php"; include_once "net/Request.php"; include_once "net/Router.php"; $cwd = getcwd(); chdir(dirname(__FILE__)); $settings = new Settings($GLOBALS["settings"]); $router = new Router($settings); $request = new Request($_SERVER["PHP_SELF"], $settings); $router->route($request); chdir($cwd);
Add check for castling in valid moves
import Reflux from 'reflux'; import GameActions from '../actions/GameActions'; var GameStore = Reflux.createStore({ init() { getGameFEN() { return this.fen; }, getActivePlayer() { return this.fen.split(' ')[1] === 'w' ? "White" : "Black"; }, getAllValidMoves() { return this.valid_moves; }, getValidMoves(pos) { var valid = []; for (var move in this.valid_moves) { var to_from = this.valid_moves[move].Move.substr(1).replace('x','-').split('-'); if (to_from[0] === pos) { valid.push(to_from[1]); } else if (to_from[0] === 'O' && pos[0] === 'e') { if (to_from.length === 2) { valid.push(this.getActivePlayer() === "White" ? "g1" : "g8"); } else if (to_from.length === 3) { valid.push(this.getActivePlayer() === "White" ? "c1" : "c8"); } } } return valid; }, getGameHistory() { return this.history; } }); export default GameStore;
import Reflux from 'reflux'; import GameActions from '../actions/GameActions'; var GameStore = Reflux.createStore({ init() { getGameFEN() { return this.fen; }, getActivePlayer() { return this.fen.split(' ')[1] === 'w' ? "White" : "Black"; }, getAllValidMoves() { return this.valid_moves; }, getValidMoves(pos) { var valid = []; for (var move in this.valid_moves) { var to_from = this.valid_moves[move].Move.substr(1).replace('x','-').split('-'); if (to_from[0] === pos) { valid.push(to_from[1]); } } return valid; }, getGameHistory() { return this.history; } }); export default GameStore;
Reorder inputs and use unsignedInteger() in migration
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class ChangeDominionsWizardSpyStrengthType extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('dominions', function (Blueprint $table) { $table->float('spy_strength')->change(); $table->float('wizard_strength')->change(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('dominions', function (Blueprint $table) { $table->unsignedInteger('spy_strength')->change(); $table->unsignedInteger('wizard_strength')->change(); }); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class ChangeDominionsWizardSpyStrengthType extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('dominions', function (Blueprint $table) { $table->float('spy_strength')->change(); $table->float('wizard_strength')->change(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('dominions', function (Blueprint $table) { $table->integer('spy_strength')->unsigned()->change(); $table->integer('wizard_strength')->unsigned()->change(); }); } }
Allow to set render samples
import bpy class Scene: """Scene object""" def __init__(self, filepath, render_engine='CYCLES'): self.filepath = filepath self.render_engine = 'CYCLES' def setup(self): self._cleanup() bpy.context.scene.render.filepath = self.filepath bpy.context.scene.render.engine = self.render_engine bpy.context.scene.frame_start = 1 bpy.context.scene.frame_end = 1 def render(self, samples=50): bpy.context.scene.cycles.samples = samples bpy.ops.render.render(animation=True) def _cleanup(self): """Delete everything""" bpy.ops.object.delete(use_global=False)
import bpy class Scene: """Scene object""" def __init__(self, filepath, render_engine='CYCLES'): self.filepath = filepath self.render_engine = 'CYCLES' def setup(self): self._cleanup() bpy.context.scene.render.filepath = self.filepath bpy.context.scene.render.engine = self.render_engine bpy.context.scene.frame_start = 1 bpy.context.scene.frame_end = 1 def render(self): bpy.ops.render.render(animation=True) def _cleanup(self): """Delete everything""" bpy.ops.object.delete(use_global=False)
Fix concurrency modification exception that could happen in the reactive messaging tests. The emission and the retrieval of the list are done on different thread. While checking the content of the retrieved list, new items can be added to the list leading to a concurrency exception.
package io.quarkus.smallrye.reactivemessaging.blocking.beans; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import javax.enterprise.context.ApplicationScoped; import org.eclipse.microprofile.reactive.messaging.Incoming; import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams; import org.eclipse.microprofile.reactive.streams.operators.SubscriberBuilder; @ApplicationScoped public class InfiniteSubscriber { private final List<Integer> payloads = new CopyOnWriteArrayList<>(); private final List<Integer> messages = new CopyOnWriteArrayList<>(); @Incoming("infinite-producer-payload") public SubscriberBuilder<Integer, Void> consumeFourItems() { return ReactiveStreams .<Integer> builder() .limit(4) .forEach(payloads::add); } @Incoming("infinite-producer-msg") public SubscriberBuilder<Integer, Void> consumeFourMessages() { return ReactiveStreams .<Integer> builder() .limit(4) .forEach(messages::add); } public List<Integer> payloads() { return payloads; } public List<Integer> messages() { return messages; } }
package io.quarkus.smallrye.reactivemessaging.blocking.beans; import java.util.ArrayList; import java.util.List; import javax.enterprise.context.ApplicationScoped; import org.eclipse.microprofile.reactive.messaging.Incoming; import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams; import org.eclipse.microprofile.reactive.streams.operators.SubscriberBuilder; @ApplicationScoped public class InfiniteSubscriber { private final List<Integer> payloads = new ArrayList<>(); private final List<Integer> messages = new ArrayList<>(); @Incoming("infinite-producer-payload") public SubscriberBuilder<Integer, Void> consumeFourItems() { return ReactiveStreams .<Integer> builder() .limit(4) .forEach(payloads::add); } @Incoming("infinite-producer-msg") public SubscriberBuilder<Integer, Void> consumeFourMessages() { return ReactiveStreams .<Integer> builder() .limit(4) .forEach(messages::add); } public List<Integer> payloads() { return payloads; } public List<Integer> messages() { return messages; } }