text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Test add site_scons as SCons module
import platform from SCons.Script import AddOption, GetOption SYSTEMS = dict(Linux = "linux", Darwin = "osx", Windows = "windows") system = str(platform.system()) if not system in SYSTEMS: system = "unknown" AddOption('--system', dest = 'system', type = 'choice', nargs = 1, action = 'store', help = 'system', choices = SYSTEMS.values(), default = system) def generate(env, **kwargs): env['SYSTEM'] = GetOption('system') if env['SYSTEM'] == 'unknown': raise ValueError('Unknown system') def exists(env): return 1
import platform from SCons.Script import AddOption, GetOption SYSTEMS = dict(Linux = "linux", Darwin = "osx", Windows = "windows") system = str(platform.system()) if not system in SYSTEMS: system = "unknown" AddOption('--system', dest = 'system', type = 'string', nargs = 1, action = 'store', help = 'system', choices = SYSTEMS.values(), default = system) def generate(env, **kwargs): env['SYSTEM'] = GetOption('system') if env['SYSTEM'] == 'unknown': raise ValueError('Unknown system') def exists(env): return 1
Remove FK's from CSV export for massive speed boost
import csv from django.http import HttpResponse from servicerating.models import Response def report_responses(request): qs = Response.objects.raw("SELECT servicerating_response.*, servicerating_extra.value AS clinic_code from servicerating_response INNER JOIN servicerating_extra ON servicerating_response.contact_id = servicerating_extra.contact_id WHERE servicerating_extra.key = 'clinic_code'") # Create the HttpResponse object with the appropriate CSV header. response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="servicerating_incl_clinic_code.csv"' writer = csv.writer(response) writer.writerow(["Rating ID", "Contact ID", "Key", "Value", "Created At", "Updated At", "Clinic Code"]) for obj in qs: writer.writerow([obj.id, obj.contact_id, obj.key, obj.value, obj.created_at, obj.updated_at, obj.clinic_code]) return response
import csv from django.http import HttpResponse from servicerating.models import Response def report_responses(request): qs = Response.objects.raw("SELECT servicerating_response.*, servicerating_extra.value AS clinic_code from servicerating_response INNER JOIN servicerating_extra ON servicerating_response.contact_id = servicerating_extra.contact_id WHERE servicerating_extra.key = 'clinic_code'") # Create the HttpResponse object with the appropriate CSV header. response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="servicerating_incl_clinic_code.csv"' writer = csv.writer(response) writer.writerow(["Contact", "Key", "Value", "Created At", "Updated At", "Clinic Code"]) for obj in qs: writer.writerow([obj.contact, obj.key, obj.value, obj.created_at, obj.updated_at, obj.clinic_code]) return response
Fix missing symbols from static linking
from setuptools import setup, Extension from Cython.Build import cythonize from Cython.Distutils import build_ext import numpy import sys if sys.platform == 'win32': pass elif sys.platform == 'darwin': noise_link_libraries = ['System', 'c', 'm'] else: noise_link_libraries = ['util', 'dl', 'pthread', 'gcc_s', 'c', 'm', 'rt', 'util'] ext = Extension('noisily.noise', sources=['noisily/noise.pyx'], include_dirs=['noise-c/include', numpy.get_include()], extra_objects=['noise-c/target/release/libnoise_c.a'], libraries=noise_link_libraries, ) extensions = [ext,] setup( name='noisily', version='0.0.1', author='Priyank Patel', author_email='tocubed@gmail.com', license='MIT', url='https://github.com/tocubed/noisily', install_requires=['numpy>=1.11.0'], ext_modules=cythonize(extensions), cmdclass={'build_ext': build_ext}, packages=['noisily'], )
from setuptools import setup, Extension from Cython.Build import cythonize from Cython.Distutils import build_ext import numpy ext = Extension('noisily.noise', sources=['noisily/noise.pyx'], include_dirs=['noise-c/include', numpy.get_include()], extra_objects=['noise-c/target/release/libnoise_c.a'], ) extensions = [ext,] setup( name='noisily', version='0.0.1', author='Priyank Patel', author_email='tocubed@gmail.com', license='MIT', url='https://github.com/tocubed/noisily', install_requires=['numpy>=1.11.0'], ext_modules=cythonize(extensions), cmdclass={'build_ext': build_ext}, packages=['noisily'], )
Add python-keystoneclient to dependencies This is needed for keystone authentication
import os from setuptools import setup README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-swiftbrowser', version='0.22', packages=['swiftbrowser'], include_package_data=True, license='Apache License (2.0)', description='A simple Django app to access Openstack Swift', long_description=README, url='https://github.com/cschwede/django-swiftbrowser', author='Christian Schwede', author_email='info@cschwede.de', install_requires=['django>=1.5', 'python-swiftclient', 'python-keystoneclient'], zip_safe=False, classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )
import os from setuptools import setup README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-swiftbrowser', version='0.22', packages=['swiftbrowser'], include_package_data=True, license='Apache License (2.0)', description='A simple Django app to access Openstack Swift', long_description=README, url='https://github.com/cschwede/django-swiftbrowser', author='Christian Schwede', author_email='info@cschwede.de', install_requires=['django>=1.5', 'python-swiftclient'], zip_safe=False, classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )
Use mixin.detect for components not within mixin unit tests.
import Ember from 'ember'; import mixinUnderTest from 'sl-ember-components/mixins/sl-component-input-id'; import { module, test } from 'qunit'; module( 'Unit | Mixin | sl component input id' ); test( 'Successfully mixed', function( assert ) { const testObject = Ember.Object.extend( mixinUnderTest ); const subject = testObject.create(); assert.ok( subject ); }); test( 'inputId is set on component', function( assert ) { const component = Ember.Component.extend( mixinUnderTest ).create(); assert.equal( component.get( 'inputId' ), component.get( 'elementId' ) + '-input' ); }); test( 'inputId value is preserved if it is already set', function( assert ) { const id = 'preset-id'; const component = Ember.Component.extend( mixinUnderTest ).create( { inputId: id }); assert.equal( component.get( 'inputId' ), id ); });
import Ember from 'ember'; import mixinUnderTest from 'sl-ember-components/mixins/sl-component-input-id'; import { module, test } from 'qunit'; module( 'Unit | Mixin | sl component input id' ); test( 'Successfully mixed', function( assert ) { const testObject = Ember.Object.extend( mixinUnderTest ); const subject = testObject.create(); assert.ok( mixinUnderTest.detect( subject ) ); }); test( 'inputId is set on component', function( assert ) { const component = Ember.Component.extend( mixinUnderTest ).create(); assert.equal( component.get( 'inputId' ), component.get( 'elementId' ) + '-input' ); }); test( 'inputId value is preserved if it is already set', function( assert ) { const id = 'preset-id'; const component = Ember.Component.extend( mixinUnderTest ).create( { inputId: id }); assert.equal( component.get( 'inputId' ), id ); });
Modify expected bug about wrong upper directory name of each platform when building
/* * Copyright 2015 Samsung Electronics Co., Ltd. * * 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. */ 'use strict'; var path = require('path'); module.exports = function(grunt) { grunt.registerMultiTask('sectv-build', 'build sectv apps', function() { var platformName = this.target; // path var wwwSrc = path.normalize(this.data.src || ('./www')); var dest = this.data.dest || path.join('platforms', platformName, 'www'); var platformRepos = this.data.platformRepos || ('../cordova-' + platformName); var scripts = this.data.scripts; var packager = require('./packager/'+platformName); var done = this.async(); packager.build(function () { done(); }, function () { done(); }, wwwSrc, dest, platformRepos, scripts); }); };
/* * Copyright 2015 Samsung Electronics Co., Ltd. * * 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. */ 'use strict'; var path = require('path'); module.exports = function(grunt) { grunt.registerMultiTask('sectv-build', 'build sectv apps', function() { var platformName = this.target; // path var wwwSrc = path.normalize(this.data.src || ('./www')); var dest = this.data.dest || path.join('platforms', platformName, 'www'); var platformRepos = this.data.platformRepos || ('../cordova-sectv-' + platformName); var scripts = this.data.scripts; var packager = require('./packager/'+platformName); var done = this.async(); packager.build(function () { done(); }, function () { done(); }, wwwSrc, dest, platformRepos, scripts); }); };
Remove redundant assignment from cube-single-res demo.
/* * Copyright 2016 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. */ 'use strict'; // Create viewer. var viewer = new Marzipano.Viewer(document.getElementById('pano')); // Create source. var source = Marzipano.ImageUrlSource.fromString( "//www.marzipano.net/media/cubemap/{f}.jpg" ); // Create geometry. var geometry = new Marzipano.CubeGeometry([{ tileSize: 1024, size: 1024 }]); // Create view. var limiter = Marzipano.RectilinearView.limit.traditional(4096, 100*Math.PI/180); var view = new Marzipano.RectilinearView(null, limiter); // Create scene. var scene = viewer.createScene({ source: source, geometry: geometry, view: view, pinFirstLevel: true }); // Display scene. scene.switchTo();
/* * Copyright 2016 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. */ 'use strict'; var Marzipano = window.Marzipano; // Create viewer. var viewer = new Marzipano.Viewer(document.getElementById('pano')); // Create source. var source = Marzipano.ImageUrlSource.fromString( "//www.marzipano.net/media/cubemap/{f}.jpg" ); // Create geometry. var geometry = new Marzipano.CubeGeometry([{ tileSize: 1024, size: 1024 }]); // Create view. var limiter = Marzipano.RectilinearView.limit.traditional(4096, 100*Math.PI/180); var view = new Marzipano.RectilinearView(null, limiter); // Create scene. var scene = viewer.createScene({ source: source, geometry: geometry, view: view, pinFirstLevel: true }); // Display scene. scene.switchTo();
Refactor preloaded json data to ancestor so search and details can both access it; refactor how Search component is rendered so we can pass params to it in BrowserRouter.
import React from 'react' // just get render function from react-dom. means we don't have to get all of ReactDOM, and use ReactDOM.render import { render } from 'react-dom' import { BrowserRouter, Match } from 'react-router' import Landing from './Landing' import Search from './Search' import Details from './Details' import preload from '../public/data.json' import '../public/normalize.css' import '../public/style.css' const App = React.createClass({ render () { return ( <BrowserRouter> <div className='app'> <Match exactly pattern='/' component={Landing} /> <Match pattern='/search' component={(props) => <Search shows={preload.shows} {...props} />} /> <Match pattern='/details/:id' component={Details} /> </div> </BrowserRouter> ) } }) // need to call render at bottom render(<App />, document.getElementById('app'))
import React from 'react' // just get render function from react-dom. means we don't have to get all of ReactDOM, and use ReactDOM.render import { render } from 'react-dom' import { BrowserRouter, Match } from 'react-router' import Landing from './Landing' import Search from './Search' import Details from './Details' import '../public/normalize.css' import '../public/style.css' const App = React.createClass({ render () { return ( <BrowserRouter> <div className='app'> <Match exactly pattern='/' component={Landing} /> <Match pattern='/search' component={Search} /> <Match pattern='/details/:id' component={Details} /> </div> </BrowserRouter> ) } }) // need to call render at bottom render(<App />, document.getElementById('app'))
Save the session-key as a unicode string in the db The session-key should be saved as a string, not a byte string.
# -*- encoding: utf-8 -*- import os import binascii class Preferences: defaults = [ ("session-key", binascii.b2a_hex(os.urandom(24)).decode('utf-8')), ] def __init__(self, db): self.db = db self.db.execute([ 'CREATE TABLE IF NOT EXISTS preferences (', ' key VARCHAR PRIMARY KEY, value VARCHAR', ');']) for (key, value) in Preferences.defaults: if self.get(key) is None: self.set(key, value) def get(self, key, default=None): rv = self.db.execute( 'SELECT value FROM preferences WHERE key=?', (key, )).fetchone() if rv is None: return default return rv[0] def set(self, key, value): self.db.execute( 'INSERT INTO preferences (key, value) VALUES (?, ?)', (key, value))
# -*- encoding: utf-8 -*- import os import binascii class Preferences: defaults = [ ("session-key", binascii.b2a_hex(os.urandom(24))), ] def __init__(self, db): self.db = db self.db.execute([ 'CREATE TABLE IF NOT EXISTS preferences (', ' key VARCHAR PRIMARY KEY, value VARCHAR', ');']) for (key, value) in Preferences.defaults: if self.get(key) is None: self.set(key, value) def get(self, key, default=None): rv = self.db.execute( 'SELECT value FROM preferences WHERE key=?', (key, )).fetchone() if rv is None: return default return rv[0] def set(self, key, value): self.db.execute( 'INSERT INTO preferences (key, value) VALUES (?, ?)', (key, value))
Fix construction of visual component
package de.tudresden.inf.lat.born.protege; import java.awt.BorderLayout; import java.util.Objects; import org.protege.editor.owl.ui.view.cls.AbstractOWLClassViewComponent; import org.semanticweb.owlapi.model.OWLClass; import de.tudresden.inf.lat.born.main.BornStarter; /** * This is the Protege view component of BORN. * * @author Julian Mendez */ public class Main extends AbstractOWLClassViewComponent { private static final long serialVersionUID = -5363687740449453246L; private BornStarter bornStarter = null; @Override public void disposeView() { } /** * Initializes the data and GUI. This method is called when the view is * initialized. */ @Override public void initialiseClassView() { this.bornStarter = new BornStarter(getOWLModelManager().getOWLOntologyManager()); this.setLayout(new BorderLayout()); add(this.bornStarter.getPanel().getView().getPanel(), BorderLayout.CENTER); } @Override protected OWLClass updateView(OWLClass selectedClass) { Objects.requireNonNull(selectedClass); return selectedClass; } }
package de.tudresden.inf.lat.born.protege; import java.awt.BorderLayout; import java.util.Objects; import org.protege.editor.owl.ui.view.cls.AbstractOWLClassViewComponent; import org.semanticweb.owlapi.model.OWLClass; import de.tudresden.inf.lat.born.main.BornStarter; /** * This is the Protege view component of BORN. * * @author Julian Mendez */ public class Main extends AbstractOWLClassViewComponent { private static final long serialVersionUID = -5363687740449453246L; private BornStarter bornStarter = null; @Override public void disposeView() { } /** * Initializes the data and GUI. This method is called when the view is * initialized. */ @Override public void initialiseClassView() { this.bornStarter = new BornStarter(getOWLModelManager().getOWLOntologyManager()); this.setLayout(new BorderLayout()); add(this.bornStarter.getPanel().getView(), BorderLayout.CENTER); } @Override protected OWLClass updateView(OWLClass selectedClass) { Objects.requireNonNull(selectedClass); return selectedClass; } }
Use tab size from Chrome storage
'use strict'; var tabSize = 2; /** * Returns a BlockingResponse object with a redirect URL if the request URL * matches a file type extension. * * @param {object} request * @return {object|undefined} the blocking response */ function requestInterceptor(request) { var url = request.url; var hasParamTs = /\?.*ts=/; var hasExtGo = /\.go/; if (!hasParamTs.test(url) && hasExtGo.test(url)) return {redirectUrl: addTabSizeParam(url, tabSize)}; } /** * Returns a URL with the query param ts=size included. * * @param {string} url * @param {number} size * @return {string} */ function addTabSizeParam(url, size) { var urlWithTs = new Url(url); urlWithTs.query.ts = size; return urlWithTs.toString(); } chrome.webRequest.onBeforeRequest.addListener( requestInterceptor, {urls: ['https://github.com/*']}, ['blocking'] ); chrome.storage.sync.get({tabSize: tabSize}, function(items) { tabSize = items.tabSize; }); chrome.storage.onChanged.addListener(function(items) { tabSize = items.tabSize.newValue; });
'use strict'; /** * Returns a BlockingResponse object with a redirect URL if the request URL * matches a file type extension. * * @param {object} request * @return {object|undefined} the blocking response */ function requestInterceptor(request) { var url = request.url; var hasParamTs = /\?.*ts=/; var hasExtGo = /\.go/; if (!hasParamTs.test(url) && hasExtGo.test(url)) return {redirectUrl: addTabSizeParam(url, 2)}; } /** * Returns a URL with the query param ts=size included. * * @param {string} url * @param {number} size * @return {string} */ function addTabSizeParam(url, size) { var urlWithTs = new Url(url); urlWithTs.query.ts = size; return urlWithTs.toString(); } chrome.webRequest.onBeforeRequest.addListener( requestInterceptor, {urls: ['https://github.com/*']}, ['blocking'] );
Remove redundant call to disable webpack 'watch' mode
var gulp = require('gulp'); var rename = require('gulp-rename'); var browserSync = require('browser-sync'); var webpackStream = require('webpack-stream'); var webpack = require('webpack'); var config = { module: { loaders: [ { test: /\.csv?$/, loader: 'dsv-loader' }, { test: /\.json$/, loader: 'json-loader' }, { test: /\.js$/, loader: 'babel', exclude: /node_modules/ } ] } }; gulp.task('js-dev', function() { config.plugins = []; return gulp.src('src/js/main.js') .pipe(webpackStream(config)) .pipe(rename('bundle.js')) .pipe(gulp.dest('dist/dev/js')) .pipe(browserSync.reload({stream:true})); }); gulp.task('js-prod', function() { config.plugins = [ new webpack.optimize.UglifyJsPlugin(), new webpack.optimize.DedupePlugin() ]; return gulp.src('src/js/main.js') .pipe(webpackStream(config)) .pipe(rename('bundle.js')) .pipe(gulp.dest('.tmp/js')); });
var gulp = require('gulp'); var rename = require('gulp-rename'); var browserSync = require('browser-sync'); var webpackStream = require('webpack-stream'); var webpack = require('webpack'); var config = { watch: false, module: { loaders: [ { test: /\.csv?$/, loader: 'dsv-loader' }, { test: /\.json$/, loader: 'json-loader' }, { test: /\.js$/, loader: 'babel', exclude: /node_modules/ } ] } }; gulp.task('js-dev', function() { config.plugins = []; return gulp.src('src/js/main.js') .pipe(webpackStream(config)) .pipe(rename('bundle.js')) .pipe(gulp.dest('dist/dev/js')) .pipe(browserSync.reload({stream:true})); }); gulp.task('js-prod', function() { config.plugins = [ new webpack.optimize.UglifyJsPlugin(), new webpack.optimize.DedupePlugin() ]; return gulp.src('src/js/main.js') .pipe(webpackStream(config)) .pipe(rename('bundle.js')) .pipe(gulp.dest('.tmp/js')); });
LS-5226: Make requests dependency version more flexible
from setuptools import setup, find_packages setup( name='lightstep', version='3.0.11', description='LightStep Python OpenTracing Implementation', long_description='', author='LightStep', license='', install_requires=['thrift==0.10.0', 'jsonpickle', 'six', 'basictracer>=2.2,<2.3', 'googleapis-common-protos==1.5.3', 'requests>=2.19,<3.0'], tests_require=['pytest', 'sphinx', 'sphinx-epytext'], classifiers=[ 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', ], keywords=[ 'opentracing', 'lightstep', 'traceguide', 'tracing', 'microservices', 'distributed' ], packages=find_packages(exclude=['docs*', 'tests*', 'sample*']), )
from setuptools import setup, find_packages setup( name='lightstep', version='3.0.11', description='LightStep Python OpenTracing Implementation', long_description='', author='LightStep', license='', install_requires=['thrift==0.10.0', 'jsonpickle', 'six', 'basictracer>=2.2,<2.3', 'googleapis-common-protos==1.5.3', 'requests==2.19.1'], tests_require=['pytest', 'sphinx', 'sphinx-epytext'], classifiers=[ 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', ], keywords=[ 'opentracing', 'lightstep', 'traceguide', 'tracing', 'microservices', 'distributed' ], packages=find_packages(exclude=['docs*', 'tests*', 'sample*']), )
Use few nsteps for testing sim-script
import json import numpy as np from click.testing import CliRunner from fastimgproto.scripts.simulate_data import cli as sim_cli def test_simulate_data(): runner = CliRunner() with runner.isolated_filesystem(): output_filename = 'simdata.npz' result = runner.invoke(sim_cli, [output_filename, '--nstep','5' ]) assert result.exit_code == 0 with open(output_filename, 'rb') as f: output_data = np.load(f) expected_keys = ('uvw_lambda', 'model', 'vis') for k in expected_keys: assert k in output_data
import json import numpy as np from click.testing import CliRunner from fastimgproto.scripts.simulate_data import cli as sim_cli def test_simulate_data(): runner = CliRunner() with runner.isolated_filesystem(): output_filename = 'simdata.npz' result = runner.invoke(sim_cli, [output_filename,]) assert result.exit_code == 0 with open(output_filename, 'rb') as f: output_data = np.load(f) expected_keys = ('uvw_lambda', 'model', 'vis') for k in expected_keys: assert k in output_data
Add currency to card registration
<?php namespace AppVentus\MangopayBundle\Helper; use AppVentus\MangopayBundle\AppVentusMangopayEvents; use AppVentus\MangopayBundle\Entity\UserInterface; use AppVentus\MangopayBundle\Event\UserEvent; use Doctrine\ORM\EntityManager; use MangoPay\CardRegistration; use Symfony\Component\EventDispatcher\EventDispatcherInterface; /** * * ref: appventus_mangopay.card_registration_helper * **/ class CardRegistrationHelper { private $mangopayHelper; private $entityManager; private $dispatcher; public function __construct(MangopayHelper $mangopayHelper, EntityManager $entityManager, EventDispatcherInterface $dispatcher) { $this->mangopayHelper = $mangopayHelper; $this->entityManager = $entityManager; $this->dispatcher = $dispatcher; } public function createCardRegistrationForUser(UserInterface $user) { $cardRegistration = new CardRegistration(); $cardRegistration->userId = $user->getMangoUserId(); $cardRegistration->Tag = 'user id : '.$user->getId(); $cardRegistration->Currency = 'EUR'; $cardRegistration = $this->mangopayHelper->CardRegistrations->Create($cardRegistration); return $cardRegistration; } }
<?php namespace AppVentus\MangopayBundle\Helper; use AppVentus\MangopayBundle\AppVentusMangopayEvents; use AppVentus\MangopayBundle\Entity\UserInterface; use AppVentus\MangopayBundle\Event\UserEvent; use Doctrine\ORM\EntityManager; use MangoPay\CardRegistration; use Symfony\Component\EventDispatcher\EventDispatcherInterface; /** * * ref: appventus_mangopay.card_registration_helper * **/ class CardRegistrationHelper { private $mangopayHelper; private $entityManager; private $dispatcher; public function __construct(MangopayHelper $mangopayHelper, EntityManager $entityManager, EventDispatcherInterface $dispatcher) { $this->mangopayHelper = $mangopayHelper; $this->entityManager = $entityManager; $this->dispatcher = $dispatcher; } public function createCardRegistrationForUser(UserInterface $user) { $cardRegistration = new CardRegistration(); $cardRegistration->userId = $user->getMangoUserId(); $cardRegistration->Tag = 'user id : '.$user->getId(); $cardRegistration = $this->mangopayHelper->CardRegistrations->Create($cardRegistration); return $cardRegistration; } }
Enhance the get param by name tests
define([ 'aux/get-parameter-by-name' ], function (getParameterByName) { describe('getParameterByName', function () { var url; beforeEach(function () { url = 'http://www.rockabox.com?param1=value1&param2=value2#somehashnotomitted'; }); it('should return the query paramater\'s value', function () { expect(getParameterByName(url, 'param1')).toBe('value1'); expect(getParameterByName(url, 'param2')).toBe('value2'); }); it ('should return an empty string when query param doesn\'t exist', function () { expect(getParameterByName(url, 'param3')).toBe(''); }); }); });
define([ 'aux/get-parameter-by-name' ], function (getParameterByName) { describe('getParameterByName', function () { var url; beforeEach(function () { url = 'http://www.rockabox.com?param1=value1&param2=value2'; }); it('should return the query paramater\'s value', function () { expect(getParameterByName(url, 'param1')).toContain('value1'); expect(getParameterByName(url, 'param2')).toContain('value2'); }); it ('should return an empty string when query param doesn\'t exist', function () { expect(getParameterByName(url, 'param3')).toBe(''); }); }); });
Move StyleDeclaration outside main function
/*! * TemplateLayout Wef plugin * Copyright (c) 2011 Pablo Escalada * MIT Licensed */ //requires: cssParser var parser = wef.fn.cssParser; //TODO: loader //exports: templateLayout (function () { var templateLayout = { name:"templateLayout", version:"0.0.1", description:"W3C CSS Template Layout Module", authors:["Pablo Escalada <uo1398@uniovi.es>"], licenses:["MIT"], //TODO: Licenses init:function () { document.addEventListener(parser.events.PROPERTY_FOUND, function (e) { //console.log(e.data.selectorText, e.data.declaration); lastEvent = e; //TODO populate TemplateDOM }, false); return templateLayout; }, getLastEvent:function () { return lastEvent; } }; var lastEvent = null; wef.plugins.register("templateLayout", templateLayout); })();
/*! * TemplateLayout Wef plugin * Copyright (c) 2011 Pablo Escalada * MIT Licensed */ //requires: cssParser var parser = wef.fn.cssParser; //TODO: loader //exports: templateLayout (function () { var templateLayout = { name:"templateLayout", version:"0.0.1", description:"W3C CSS Template Layout Module", authors:["Pablo Escalada <uo1398@uniovi.es>"], licenses:["MIT"], //TODO: Licenses init:function () { document.addEventListener(parser.events.PROPERTY_FOUND, function (e) { // e.target matches the elem from above lastEvent = e; //TODO populate TemplateDOM }, false); return templateLayout; }, getLastEvent:function () { return lastEvent; } }; var lastEvent = null; wef.plugins.register("templateLayout", templateLayout); })();
XWIKI-8613: Add an autosuggest to any input that requires a document reference in macros * Fix javadoc
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.rendering.macro.toc; import org.xwiki.model.reference.DocumentReference; import org.xwiki.properties.annotation.PropertyDisplayType; /** * Parameters for the {@link org.xwiki.rendering.internal.macro.toc.XWikiTocMacro} Macro. * * @version $Id$ * @since 11.5RC1 */ public class XWikiTocMacroParameters extends TocMacroParameters { @PropertyDisplayType(DocumentReference.class) @Override public void setReference(String reference) { super.setReference(reference); } }
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.rendering.macro.toc; import org.xwiki.model.reference.DocumentReference; import org.xwiki.properties.annotation.PropertyDisplayType; /** * Parameters for the {@link org.xwiki.rendering.internal.macro.toc.XWikiTocMacro} Macro. * * @version $Id$ * @see 11.5RC1 */ public class XWikiTocMacroParameters extends TocMacroParameters { @PropertyDisplayType(DocumentReference.class) @Override public void setReference(String reference) { super.setReference(reference); } }
Fix dependency inclusion for require statement
const redis = require('./redis'); const config = require('../config/index.js'); const getRequest = async (requestId) => { // Set TTL for request redis.expire(`requests:${requestId}`, config('requests_ttl')); return await redis.hgetallAsync(`requests:${requestId}`); }; const createRequest = async (requestDetails) => { // get new unique id for request const requestId = await redis.incrAsync('next_request_id'); // create a new request entry in Redis const {user_id, pickup, dropoff, requested_pickup_time, size, weight} = requestDetails; const [pickup_lat, pickup_long] = pickup.split(','); const [dropoff_lat, dropoff_long] = dropoff.split(','); redis.hmsetAsync(`requests:${requestId}`, 'user_id', user_id, 'pickup_lat', pickup_lat, 'pickup_long', pickup_long, 'dropoff_lat', dropoff_lat, 'dropoff_long', dropoff_long, 'requested_pickup_time', requested_pickup_time, 'size', size, 'weight', weight, ); // Set TTL for request redis.expire(`requests:${requestId}`, 43200); return requestId; }; const deleteRequest = async (requestId) => { return await redis.del(`requests:${requestId}`); }; module.exports = { createRequest, getRequest, deleteRequest };
const redis = require('./redis'); const config = require('./config'); const getRequest = async (requestId) => { // Set TTL for request redis.expire(`requests:${requestId}`, config('requests_ttl')); return await redis.hgetallAsync(`requests:${requestId}`); }; const createRequest = async (requestDetails) => { // get new unique id for request const requestId = await redis.incrAsync('next_request_id'); // create a new request entry in Redis const {user_id, pickup, dropoff, requested_pickup_time, size, weight} = requestDetails; const [pickup_lat, pickup_long] = pickup.split(','); const [dropoff_lat, dropoff_long] = dropoff.split(','); redis.hmsetAsync(`requests:${requestId}`, 'user_id', user_id, 'pickup_lat', pickup_lat, 'pickup_long', pickup_long, 'dropoff_lat', dropoff_lat, 'dropoff_long', dropoff_long, 'requested_pickup_time', requested_pickup_time, 'size', size, 'weight', weight, ); // Set TTL for request redis.expire(`requests:${requestId}`, 43200); return requestId; }; const deleteRequest = async (requestId) => { return await redis.del(`requests:${requestId}`); }; module.exports = { createRequest, getRequest, deleteRequest };
Fix map view crashing with non existent selected unit
import React from 'react'; import isEmpty from 'lodash/isEmpty'; import SingleUnitOnMap from './SingleUnitOnMap'; import {sortByCondition} from '../helpers'; export const UnitsOnMap = ({units, selectedUnitId, openUnit}) => { let unitsInOrder = units.slice(); // Draw things in condition order unitsInOrder = sortByCondition(unitsInOrder).reverse(); if(!isEmpty(unitsInOrder) && selectedUnitId) { const selectedUnit = unitsInOrder.find((unit) => unit.id === selectedUnitId); !isEmpty(selectedUnit) && unitsInOrder.push(selectedUnit); } return( <div className="units-on-map"> { !isEmpty(unitsInOrder) && unitsInOrder.map( (unit, index) => <SingleUnitOnMap isSelected={unit.id === selectedUnitId} unit={unit} key={`${index}:${unit.id}`} openUnit={openUnit} /> ) } </div> ); }; export default UnitsOnMap;
import React from 'react'; import isEmpty from 'lodash/isEmpty'; import SingleUnitOnMap from './SingleUnitOnMap'; import {sortByCondition} from '../helpers'; export const UnitsOnMap = ({units, selectedUnitId, openUnit}) => { let unitsInOrder = units.slice(); // Draw things in condition order unitsInOrder = sortByCondition(unitsInOrder).reverse(); if(!isEmpty(unitsInOrder) && selectedUnitId) { const index = unitsInOrder.findIndex((unit) => unit.id === selectedUnitId); const selectedUnit = unitsInOrder[index]; //FIXME: This fails if url parameter unitId does not exist unitsInOrder.push(selectedUnit); } return( <div className="units-on-map"> { !isEmpty(unitsInOrder) && unitsInOrder.map( (unit, index) => <SingleUnitOnMap isSelected={unit.id === selectedUnitId} unit={unit} key={`${index}:${unit.id}`} openUnit={openUnit} /> ) } </div> ); }; export default UnitsOnMap;
Fix the unit test by making the returned time the same on all calls (which was the whole point)
package beaform.events; import static org.junit.Assert.assertEquals; import java.text.SimpleDateFormat; import java.util.Date; import org.junit.After; import org.junit.Test; import beaform.utilities.SystemTime; import beaform.utilities.TimeSource; public class StoreEventTest { @After public void destroy() { SystemTime.reset(); } @Test public void testEventString() { // Create a 'create' event for a new formula String name = "TestFormula"; Event createEvent = new FormulaCreatedEvent(name); SystemTime.setTimeSource(new TimeSource() { private final long timeInMillis = System.currentTimeMillis(); @Override public long getSystemTime() { return this.timeInMillis; } }); Date timestamp = new Date(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); // Check if the event converts to a string correctly // [timestamp] action properties assertEquals("[" + df.format(timestamp) + "] FormulaCreated " + name, createEvent.toEventString()); } }
package beaform.events; import static org.junit.Assert.assertEquals; import java.text.SimpleDateFormat; import java.util.Date; import org.junit.After; import org.junit.Test; import beaform.utilities.SystemTime; import beaform.utilities.TimeSource; public class StoreEventTest { @After public void destroy() { SystemTime.reset(); } @Test public void testEventString() { // Create a 'create' event for a new formula String name = "TestFormula"; Event createEvent = new FormulaCreatedEvent(name); SystemTime.setTimeSource(new TimeSource() { @Override public long getSystemTime() { return new Date().getTime(); } }); Date timestamp = new Date(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); // Check if the event converts to a string correctly // [timestamp] action properties assertEquals("[" + df.format(timestamp) + "] FormulaCreated " + name, createEvent.toEventString()); } }
Make sure the compiler post parameter is an allowed one
const express = require('express'); const router = express.Router(); const multer = require('multer'); const upload = multer({dest: 'uploads/'}); const path = require('path'); const compile = require('../latex/latex'); // POST method route router.post('/', upload.single('zip_file'), function (req, res) { const filename = req.file.filename; let compiler = req.file.compiler; // Just making sure to run one of this allowed exes if(compiler != 'pdflatex' || compiler != 'latexmk' || compiler != 'xelatex') { compiler = 'pdflatex'; } compile(compiler, filename) .then((file) => sendResultingFile(file, res)) .catch((error) => errorHandler(error, res)); }); function sendResultingFile(file, res) { res.sendFile(path.resolve(file), function (err) { if(err) { console.error('Error sending the file: ' + err); res.status(400).send(err); } }); } function errorHandler(error, res) { console.error(error); res.status(400).send(error); } module.exports = router;
const express = require('express'); const router = express.Router(); const multer = require('multer'); const upload = multer({dest: 'uploads/'}); const path = require('path'); const compile = require('../latex/latex'); // POST method route router.post('/', upload.single('zip_file'), function (req, res) { const filename = req.file.filename; const compiler = req.file.compiler || 'pdflatex'; compile(compiler, filename) .then((file) => sendResultingFile(file, res)) .catch((error) => errorHandler(error, res)); }); function sendResultingFile(file, res) { res.sendFile(path.resolve(file), function (err) { if(err) { console.error('Error sending the file: ' + err); res.status(400).send(err); } }); } function errorHandler(error, res) { console.error(error); res.status(400).send(error); } module.exports = router;
Fix getMergeCommits to return empty array It turns out that `split('\n')` will return an array with the whole string if the separator is not found rather than the whole string
'use strict' const exec = require('./util').exec const logger = require('./logging').logger function getMergeCommits (revRange) { const gitLogCmd = `git log ${revRange} --format='%s' --grep='^Merge pull request #[0-9]\\+ from '` const stdout = exec(gitLogCmd).toString().trimRight() const commits = stdout ? stdout.split('\n') : [] logger.debug('Commits: %s', JSON.stringify(commits)) return commits } function getPRs (commits) { const prs = commits.map(function (line) { const match = /Merge pull request #(\d+) from /.exec(line) if (match) { return parseInt(match[1], 10) } return false }).filter(Boolean) logger.debug('PRs: %s', JSON.stringify(prs)) return prs } module.exports = { getMergeCommits, getPRs }
'use strict' const exec = require('./util').exec const logger = require('./logging').logger function getMergeCommits (revRange) { const gitLogCmd = `git log ${revRange} --format='%s' --grep='^Merge pull request #[0-9]\\+ from '` const commits = exec(gitLogCmd).toString().trimRight().split('\n') logger.debug('Commits: %s', commits) return commits } function getPRs (commits) { const prs = commits.map(function (line) { const match = /Merge pull request #(\d+) from /.exec(line) if (match) { return parseInt(match[1], 10) } return false }).filter(Boolean) logger.debug('PRs: %s', prs) return prs } module.exports = { getMergeCommits, getPRs }
Add id param for the sensor-detail.html page
(function(){ $.ajax({ url: 'evanxd/sensors', }) .done(function(sensors) { var sensorList = $('#sensor-list ul'); var html = ''; sensors.forEach(function(sensor) { var html = '<li class="collection-item">' + '<div>' + sensor.name + '<a href="sensor-detail.html?id=' + sensor._id + '" class="secondary-content"><i class="material-icons">info</i></a>' + '</div>' + '</li>'; sensorList.append(html); }); }) .fail(function(error) { console.error(error); }) })();
(function(){ $.ajax({ url: 'evanxd/sensors', }) .done(function(sensors) { var sensorList = $('#sensor-list ul'); var html = ''; sensors.forEach(function(sensor) { var html = '<li class="collection-item">' + '<div>' + sensor.name + '<a href="sensor-detail.html" class="secondary-content"><i class="material-icons">info</i></a>' + '</div>' + '</li>'; sensorList.append(html); }); }) .fail(function(error) { console.error(error); }) })();
Raise a nicer CommandError instead of showing the ValueError on the command line.
"""Run scheduled jobs.""" import datetime from optparse import make_option from django.core.management.base import NoArgsCommand, CommandError from django_future import run_jobs class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--delete-completed', '-d', action='store_true', dest='delete_completed', help='Do not keep entries for completed jobs in the database.'), make_option('--ignore-errors', '-i', action='store_true', dest='ignore_errors', help='Do not abort if a job handler raises an error.'), ) help = "Executes any outstanding scheduled jobs." def handle(self, **options): delete_completed = bool(options.get('delete_completed', False)) ignore_errors = bool(options.get('ignore_errors', False)) try: run_jobs(delete_completed=delete_completed, ignore_errors=ignore_errors) except ValueError, e: raise CommandError(e)
"""Run scheduled jobs.""" import datetime from optparse import make_option from django.core.management.base import NoArgsCommand from django_future import run_jobs class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--delete-completed', '-d', action='store_true', dest='delete_completed', help='Do not keep entries for completed jobs in the database.'), make_option('--ignore-errors', '-i', action='store_true', dest='ignore_errors', help='Do not abort if a job handler raises an error.'), ) help = "Executes any outstanding scheduled jobs." def handle(self, **options): delete_completed = bool(options.get('delete_completed', False)) ignore_errors = bool(options.get('ignore_errors', False)) run_jobs(delete_completed=delete_completed, ignore_errors=ignore_errors)
Cut out the extra character
/** * Japanese translation for foundation-datepicker * Norio Suzuki <https://github.com/suzuki/> */ ;(function($){ $.fn.fdatepicker.dates['ja'] = { days: ["日曜日", "月曜日", "火曜日", "水曜日", "木曜日", "金曜日", "土曜日"], daysShort: ["日", "月", "火", "水", "木", "金", "土"], daysMin: ["日", "月", "火", "水", "木", "金", "土"], months: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"], monthsShort: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"], today: "今日", format: "yyyy/mm/dd", titleFormat: "yyyy年 MM" }; }(jQuery));
/** * Japanese translation for foundation-datepicker * Norio Suzuki <https://github.com/suzuki/> */ ;(function($){ $.fn.fdatepicker.dates['ja'] = { days: ["日曜日", "月曜日", "火曜日", "水曜日", "木曜日", "金曜日", "土曜日"], daysShort: ["日", "月", "火", "水", "木", "金", "土"], daysMin: ["日", "月", "火", "水", "木", "金", "土"], months: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"], monthsShort: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"], today: "今日", format: "yyyy/mm/dd", titleFormat: "yyyy年 MM月" }; }(jQuery));
Fix test for malformed binary numbers
package com.github.pedrovgs.app.problem3; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * @author Pedro Vicente Gómez Sánchez. */ public class SumBinaryNumberTest { private SumBinaryNumbers sumBinaryNumbers; @Before public void setUp() { this.sumBinaryNumbers = new SumBinaryNumbers(); } @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullInputs() { sumBinaryNumbers.sumBinaryNumbersCheating(null, null); } @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptMalformedBinaryNumbers() { String n1 = "10"; String n2 = "2"; sumBinaryNumbers.sumBinaryNumbersCheating(n1, n2); } @Test public void zeroPlusZeroEqualsZero() { String n1 = "0"; String n2 = "0"; String result = sumBinaryNumbers.sumBinaryNumbersCheating(n1, n2); assertEquals(0, result); } @Test public void zeroPlusTwoEqualsTwo() { String n1 = "0"; String n2 = "10"; String result = sumBinaryNumbers.sumBinaryNumbersCheating(n1, n2); assertEquals("10", result); } @Test public void fivePlusSevenEqualsTwelve() { String n1 = "101"; String n2 = "111"; String result = sumBinaryNumbers.sumBinaryNumbersCheating(n1, n2); assertEquals("1100", result); } }
package com.github.pedrovgs.app.problem3; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * @author Pedro Vicente Gómez Sánchez. */ public class SumBinaryNumberTest { private SumBinaryNumbers sumBinaryNumbers; @Before public void setUp() { this.sumBinaryNumbers = new SumBinaryNumbers(); } @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullInputs() { sumBinaryNumbers.sumBinaryNumbersCheating(null, null); } @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptMalformedBinaryNumbers() { String n1 = "10"; String n2 = "2"; sumBinaryNumbers.sumBinaryNumbersCheating(null, null); } @Test public void zeroPlusZeroEqualsZero() { String n1 = "0"; String n2 = "0"; String result = sumBinaryNumbers.sumBinaryNumbersCheating(n1, n2); assertEquals(0, result); } @Test public void zeroPlusTwoEqualsTwo() { String n1 = "0"; String n2 = "10"; String result = sumBinaryNumbers.sumBinaryNumbersCheating(n1, n2); assertEquals("10", result); } @Test public void fivePlusSevenEqualsTwelve() { String n1 = "101"; String n2 = "111"; String result = sumBinaryNumbers.sumBinaryNumbersCheating(n1, n2); assertEquals("1100", result); } }
Fix exception based logging to actually log the exception!
package cpw.mods.fml.common; import java.util.logging.Level; import java.util.logging.Logger; public class FMLLog { private static cpw.mods.fml.relauncher.FMLRelaunchLog coreLog = cpw.mods.fml.relauncher.FMLRelaunchLog.log; public static void log(Level level, String format, Object... data) { coreLog.log(level, String.format(format, data)); } public static void log(Level level, Throwable ex, String format, Object... data) { coreLog.log(level, ex, String.format(format, data)); } public static void severe(String format, Object... data) { log(Level.SEVERE, format, data); } public static void warning(String format, Object... data) { log(Level.WARNING, format, data); } public static void info(String format, Object... data) { log(Level.INFO, format, data); } public static void fine(String format, Object... data) { log(Level.FINE, format, data); } public static void finer(String format, Object... data) { log(Level.FINER, format, data); } public static void finest(String format, Object... data) { log(Level.FINEST, format, data); } public static Logger getLogger() { return coreLog.getLogger(); } }
package cpw.mods.fml.common; import java.util.logging.Level; import java.util.logging.Logger; public class FMLLog { private static cpw.mods.fml.relauncher.FMLRelaunchLog coreLog = cpw.mods.fml.relauncher.FMLRelaunchLog.log; public static void log(Level level, String format, Object... data) { coreLog.log(level, String.format(format, data)); } public static void log(Level level, Throwable ex, String format, Object... data) { coreLog.log(level, String.format(format, data), ex); } public static void severe(String format, Object... data) { log(Level.SEVERE, format, data); } public static void warning(String format, Object... data) { log(Level.WARNING, format, data); } public static void info(String format, Object... data) { log(Level.INFO, format, data); } public static void fine(String format, Object... data) { log(Level.FINE, format, data); } public static void finer(String format, Object... data) { log(Level.FINER, format, data); } public static void finest(String format, Object... data) { log(Level.FINEST, format, data); } public static Logger getLogger() { return coreLog.getLogger(); } }
Fix typo in error message
"""Custom error for invalid yaml file.""" from .Error import Error ERROR_MESSAGE = """ Invalid YAML file (.yaml). Options: - Does the file match the expected layout? - Does the file contain at least one key:value pair? - Is the syntax correct? (are you missing a colon somewhere?) """ class InvalidYAMLFileError(Error): """custom error for invalid yaml file.""" def __init__(self, yaml_file_path): """Create error for invalid yaml file.""" super().__init__() self.yaml_file_path = yaml_file_path def __str__(self): """Override default error string. Returns: Error message for invalid yaml file. """ return self.base_message.format(filename=self.yaml_file_path) + ERROR_MESSAGE
"""Custom error for invalid yaml file.""" from .Error import Error ERROR_MESSAGE = """ Invalid YAML file (.yaml) Options: - Does the file match the expected layout? - Does the file contain at least one key:value pair? - Is the syntax correct? (are you missing a colon somewhere?) """ class InvalidYAMLFileError(Error): """custom error for invalid yaml file.""" def __init__(self, yaml_file_path): """Create error for invalid yaml file.""" super().__init__() self.yaml_file_path = yaml_file_path def __str__(self): """Override default error string. Returns: Error message for invalid yaml file. """ return self.base_message.format(filename=self.yaml_file_path) + ERROR_MESSAGE
Access to computation context service through actors was implemented.
package org.cat.eye.engine.container.unit.deployment; import org.cat.eye.engine.common.deployment.BundleDeployer; import org.cat.eye.engine.common.deployment.management.BundleManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by Kotov on 30.11.2017. */ public class UnitBundleDeployerImpl implements BundleDeployer { private final static Logger LOGGER = LoggerFactory.getLogger(UnitBundleDeployerImpl.class); private BundleManager bundleManager; @Override public void deploy(String classPath, String domain) { ClassLoader bundleClassLoader = Thread.currentThread().getContextClassLoader(); // new BundleClassLoader(); // create and start thread for bundle deploying Thread deployingThread = new Thread(new UnitDeployingProcess(classPath, domain, bundleManager)); deployingThread.setContextClassLoader(bundleClassLoader); deployingThread.start(); try { deployingThread.join(); } catch (InterruptedException e) { LOGGER.error("deploy - can't deploy bundle: " + classPath, e); } } @Override public void setBundleManager(BundleManager bundleManager) { this.bundleManager = bundleManager; } }
package org.cat.eye.engine.container.unit.deployment; import org.cat.eye.engine.common.deployment.BundleClassLoader; import org.cat.eye.engine.common.deployment.BundleDeployer; import org.cat.eye.engine.common.deployment.management.BundleManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by Kotov on 30.11.2017. */ public class UnitBundleDeployerImpl implements BundleDeployer { private final static Logger LOGGER = LoggerFactory.getLogger(UnitBundleDeployerImpl.class); private BundleManager bundleManager; @Override public void deploy(String classPath, String domain) { ClassLoader bundleClassLoader = Thread.currentThread().getContextClassLoader(); // new BundleClassLoader(); // create and start thread for bundle deploying Thread deployingThread = new Thread(new UnitDeployingProcess(classPath, domain, bundleManager)); deployingThread.setContextClassLoader(bundleClassLoader); deployingThread.start(); try { deployingThread.join(); } catch (InterruptedException e) { LOGGER.error("deploy - can't deploy bundle: " + classPath, e); } } @Override public void setBundleManager(BundleManager bundleManager) { this.bundleManager = bundleManager; } }
Add quantity into edit rules.
'use strict'; module.exports = /*@ngInject*/ function EditSentence( $scope, SentenceWritingService, $state, _ ) { SentenceWritingService.getSentenceWriting($state.params.id) .then(function(s) { s.category = _.findWhere($scope.availableCategories, function(o) { return o.$id == s.categoryId; }); var tempList = _.chain(s.rules) .pluck('ruleId') .toArray() .map(function(s) { return String(s); }) .value(); s.rules = _.chain($scope.availableRules) .filter(function(r) { return _.contains(tempList, String(r.$id)); }) .map(function(r) { r.quantity = _.findWhere(s.rules, {ruleId: r.$id}).quantity; return r; }) .value(); s.flag = _.findWhere($scope.flags, function(f) { return f.$id == s.flagId; }); $scope.editSentence = s; }); };
'use strict'; module.exports = /*@ngInject*/ function EditSentence( $scope, SentenceWritingService, $state, _ ) { SentenceWritingService.getSentenceWriting($state.params.id) .then(function(s) { s.category = _.findWhere($scope.availableCategories, function(o) { return o.$id == s.categoryId; }); var tempList = _.chain(s.rules) .pluck('ruleId') .toArray() .map(function(s) { return String(s); }) .value(); s.rules = _.filter($scope.availableRules, function(r) { return _.contains(tempList, String(r.$id)); }); s.flag = _.findWhere($scope.flags, function(f) { return f.$id == s.flagId; }); $scope.editSentence = s; }); };
Add temporary default KNS table URL
package org.aksw.kbox.kibe; import java.net.MalformedURLException; import java.net.URL; import org.aksw.kbox.kns.CustomKNSServerList; import org.aksw.kbox.kns.KNSServerListVisitor; public class DefaultKNSServerList extends URLKNSServerList { // Default KNS table URL // private final static String DEFAULT_KNS_TABLE_URL = "https://raw.githubusercontent.com/AKSW/KBox/master/kns/2.0/"; private final static String DEFAULT_KNS_TABLE_URL = "https://raw.githubusercontent.com/sahandilshan/KBox/dev/kns/2.0/"; private CustomKNSServerList customKNSServerList = new CustomKNSServerList(); public DefaultKNSServerList() throws MalformedURLException { super(new URL(DEFAULT_KNS_TABLE_URL)); } @Override public boolean visit(KNSServerListVisitor visitor) throws Exception { boolean next = super.visit(visitor); if(next) { next = customKNSServerList.visit(visitor); } return next; } }
package org.aksw.kbox.kibe; import java.net.MalformedURLException; import java.net.URL; import org.aksw.kbox.kns.CustomKNSServerList; import org.aksw.kbox.kns.KNSServerListVisitor; public class DefaultKNSServerList extends URLKNSServerList { // Default KNS table URL private final static String DEFAULT_KNS_TABLE_URL = "https://raw.githubusercontent.com/AKSW/KBox/master/kns/2.0/"; private CustomKNSServerList customKNSServerList = new CustomKNSServerList(); public DefaultKNSServerList() throws MalformedURLException { super(new URL(DEFAULT_KNS_TABLE_URL)); } @Override public boolean visit(KNSServerListVisitor visitor) throws Exception { boolean next = super.visit(visitor); if(next) { next = customKNSServerList.visit(visitor); } return next; } }
Use glTrans instead of setXYZOff
package emergencylanding.k.library.lwjgl.render; import emergencylanding.k.library.internalstate.ELEntity; import emergencylanding.k.library.lwjgl.Shapes; import emergencylanding.k.library.util.DrawableUtils; public class TextureRender extends Render<ELEntity> { @Override public void doRender(ELEntity entity, float posX, float posY, float posZ) { DrawableUtils.glBeginTrans(posX, posY, posZ); VBAO quad = Shapes.getQuad(new VertexData(), new VertexData().setXYZ( (float) entity.getTex().getWidth(), (float) entity.getTex() .getHeight(), posZ), Shapes.XY); quad.setTexture(entity.getTex()); quad.draw(); DrawableUtils.glEndTrans(); } }
package emergencylanding.k.library.lwjgl.render; import emergencylanding.k.library.internalstate.ELEntity; import emergencylanding.k.library.lwjgl.Shapes; public class TextureRender extends Render<ELEntity> { @Override public void doRender(ELEntity entity, float posX, float posY, float posZ) { VBAO quad = Shapes.getQuad(new VertexData(), new VertexData().setXYZ( (float) entity.getTex().getWidth(), (float) entity.getTex() .getHeight(), posZ), Shapes.XY); quad.setTexture(entity.getTex()); quad.setXYZOff(entity.getInterpolated()); quad.draw(); } }
Use a function to write.
#!/usr/bin/env python import json import settings import os import urllib2 from proto import gtfs_realtime_pb2 message = gtfs_realtime_pb2.FeedMessage() url = urllib2.urlopen('http://datamine.mta.info/mta_esi.php?key={0}&feed_id={1}'.format(settings.MTA_API_KEY, settings.MTA_FEED_ID)) message.ParseFromString(url.read()) url.close() stops = {} for entity in message.entity: if entity.trip_update.trip.route_id == "L": for stop_time_update in entity.trip_update.stop_time_update: stop_id = stop_time_update.stop_id if stop_id not in stops: stops[stop_id] = [] stops[stop_id].append(stop_time_update.departure.time) temp = os.path.join(settings.JSON_OUT_DIR, 'temp') def write(filename, json): file = open(temp, 'w+') file.write(json.dumps(json)) file.flush() os.fsync(file) file.close() os.rename(temp, filename) for stop_id, departures in stops.items(): write(os.path.join(settings.JSON_OUT_DIR, stop_id + ".json"), sorted(departures))
#!/usr/bin/env python import json import settings import os import urllib2 from proto import gtfs_realtime_pb2 message = gtfs_realtime_pb2.FeedMessage() url = urllib2.urlopen('http://datamine.mta.info/mta_esi.php?key={0}&feed_id={1}'.format(settings.MTA_API_KEY, settings.MTA_FEED_ID)) message.ParseFromString(url.read()) url.close() stops = {} for entity in message.entity: if entity.trip_update.trip.route_id == "L": for stop_time_update in entity.trip_update.stop_time_update: stop_id = stop_time_update.stop_id if stop_id not in stops: stops[stop_id] = [] stops[stop_id].append(stop_time_update.departure.time) temp = os.path.join(settings.JSON_OUT_DIR, 'temp') for stop_id, departures in stops.items(): file = open(temp, 'w+') file.write(json.dumps(sorted(departures))) file.flush() os.fsync(file) file.close() os.rename(temp, os.path.join(settings.JSON_OUT_DIR, stop_id + ".json"))
Return templates sorted by displayName by default
<?php namespace Opifer\EavBundle\Repository; use Doctrine\ORM\EntityRepository; use Symfony\Component\HttpFoundation\Request; /** * Template Repository */ class TemplateRepository extends EntityRepository { /** * Find templates by request * * @param Request $request * * @return \Doctrine\Common\Collections\ArrayCollection */ public function findByRequest(Request $request) { $qb = $this->createQueryBuilder('t'); if ($request->get('name')) { $qb->andWhere('t.name = :name')->setParameter('name', $request->get('name')); } $qb->orderBy('t.displayName', 'ASC'); return $qb->getQuery()->getArrayResult(); } public function findOneByName($name){ $qb = $this->createQueryBuilder('t'); $qb->andWhere('t.name = :name')->setParameter('name', $name); return $qb->getQuery()->getSingleResult(); } }
<?php namespace Opifer\EavBundle\Repository; use Doctrine\ORM\EntityRepository; use Symfony\Component\HttpFoundation\Request; /** * Template Repository */ class TemplateRepository extends EntityRepository { /** * Find templates by request * * @param Request $request * * @return \Doctrine\Common\Collections\ArrayCollection */ public function findByRequest(Request $request) { $qb = $this->createQueryBuilder('t'); if ($request->get('name')) { $qb->andWhere('t.name = :name')->setParameter('name', $request->get('name')); } return $qb->getQuery()->getArrayResult(); } public function findOneByName($name){ $qb = $this->createQueryBuilder('t'); $qb->andWhere('t.name = :name')->setParameter('name', $name); return $qb->getQuery()->getSingleResult(); } }
Fix compiler warning in paging:integration-tests:testapp Test: gw paging:integration-tests:testapp:test Change-Id: Id4c81b093896d4bb4e411171eb83a8e312667c2a
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.paging.integration.testapp.room; import androidx.room.Database; import androidx.room.RoomDatabase; /** * Sample database of customers. */ @Database(entities = {Customer.class}, version = 1, exportSchema = false) public abstract class SampleDatabase extends RoomDatabase { /** * @return customer dao. */ public abstract CustomerDao getCustomerDao(); }
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.paging.integration.testapp.room; import androidx.room.Database; import androidx.room.RoomDatabase; /** * Sample database of customers. */ @Database(entities = {Customer.class}, version = 1) public abstract class SampleDatabase extends RoomDatabase { /** * @return customer dao. */ public abstract CustomerDao getCustomerDao(); }
Add request time format to the broadcasts feed
<?php namespace Bamboo\Feeds; use Bamboo\Models\Broadcast; class Broadcasts extends BaseParallel { const TIME_FORMAT = 'Y-m-d\TH:i'; protected $_feedName = '/channels/{channel_id}/broadcasts'; protected $_feeds = array(); protected $_responses; public function __construct($params, $channels) { $this->_feeds = $this->_buildFeeds($channels); parent::__construct($params); } public function getBroadcasts() { $channels = array(); foreach ($this->_responses as $resp) { $id = $resp->broadcasts->channel->id; $channels[$id] = $this->_buildModels($resp->broadcasts->elements); } return $channels; } private function _buildFeeds($channels) { $feedName = $this->_feedName; if (!is_array($channels)) { $channels = array($channels); } return array_map( function ($channel) use ($feedName) { return str_replace("{channel_id}", $channel, $feedName); }, $channels ); } }
<?php namespace Bamboo\Feeds; use Bamboo\Models\Broadcast; class Broadcasts extends BaseParallel { protected $_feedName = '/channels/{channel_id}/broadcasts'; protected $_feeds = array(); protected $_responses; public function __construct($params, $channels) { $this->_feeds = $this->_buildFeeds($channels); parent::__construct($params); } public function getBroadcasts() { $channels = array(); foreach ($this->_responses as $resp) { $id = $resp->broadcasts->channel->id; $channels[$id] = $this->_buildModels($resp->broadcasts->elements); } return $channels; } private function _buildFeeds($channels) { $feedName = $this->_feedName; if (!is_array($channels)) { $channels = array($channels); } return array_map( function ($channel) use ($feedName) { return str_replace("{channel_id}", $channel, $feedName); }, $channels ); } }
Include README as long description
""" Flask-Autodoc ------------- Flask autodoc automatically creates an online documentation for your flask application. """ from setuptools import setup def readme(): with open('README') as f: return f.read() setup( name='Flask-Autodoc', version='0.1', url='http://github.com/acoomans/flask-autodoc', license='MIT', author='Arnaud Coomans', author_email='arnaud.coomans@gmail.com', description='Documentation generator for flask', long_description=readme(), #py_modules=['flask_autodoc'], # if you would be using a package instead use packages instead # of py_modules: packages=['flask_autodoc'], package_data={'flask_autodoc': ['templates/autodoc_default.html']}, zip_safe=False, include_package_data=True, platforms='any', install_requires=[ 'Flask' ], classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ], test_suite = 'tests.test_autodoc', )
""" Flask-Autodoc ------------- Flask autodoc automatically creates an online documentation for your flask application. """ from setuptools import setup setup( name='Flask-Autodoc', version='0.1', url='http://github.com/acoomans/flask-autodoc', license='MIT', author='Arnaud Coomans', author_email='arnaud.coomans@gmail.com', description='Documentation generator for flask', long_description=__doc__, #py_modules=['flask_autodoc'], # if you would be using a package instead use packages instead # of py_modules: packages=['flask_autodoc'], package_data={'flask_autodoc': ['templates/autodoc_default.html']}, zip_safe=False, include_package_data=True, platforms='any', install_requires=[ 'Flask' ], classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ], test_suite = 'tests.test_autodoc', )
Remove onboarding from alias click
'use strict' import React, { Component } from 'react' import ReactCSS from 'reactcss' import { User } from '../common/index' import { generateKey } from '../../utils/pgp' class Alias extends Component { classes() { return { 'default': { user: { color: '#fff', flex: '1', fontWeight: '500', }, }, } } render() { return ( <div is="user"> <User name={ this.props.alias.name.length === 0 ? this.props.alias.email : this.props.alias.name } avatar={ 9 } /> </div> ) } } export default ReactCSS(Alias)
'use strict' import React, { Component } from 'react' import ReactCSS from 'reactcss' import { User } from '../common/index' import { generateKey } from '../../utils/pgp' class Alias extends Component { classes() { return { 'default': { user: { color: '#fff', flex: '1', fontWeight: '500', }, }, } } render() { return ( <div is="user" onClick={ this.props.showComposer.bind(this, 'alias') }> <User name={ this.props.alias.name.length === 0 ? this.props.alias.email : this.props.alias.name } avatar={ 9 } /> </div> ) } } export default ReactCSS(Alias)
Reduce default connection time to 10s (from 32s) This helps to address https://github.com/docker/cli/issues/1739, where an invalid `DOCKER_HOST` setting could result in a 64s delay (that's twice the delay here because the client was trying to hit the `/_ping` endpoint twice, which was addressed in https://github.com/moby/moby/pull/39206) I made a previous attempt to fix this purely on the Docker cli side (https://github.com/docker/cli/pull/1872) however that had the side effect of adding the timeout across the board and not just for the dial phase, which caused a regression for `docker logs -f` (https://github.com/docker/cli/issues/1892) and so was reverted (https://github.com/docker/cli/pull/1893). The new value of 10s is just based on a gut feeling, no initial connection should be taking that long in the real world unless something about the network link is pretty broken (e.g. bad dns perhaps), in which case affected users are surely pretty used to retrying things, better to fail faster in the normal case. Also drop the comment since the linked issue just shows that the original number, just like the new number, was arrived at fairly arbitrarily based on gut feelings (rather than anything empirical) so the reference is not really terribly useful. Signed-off-by: Ian Campbell <a8db091655a7f47ecb9c39a2d278e9662e440dc0@docker.com>
// Package sockets provides helper functions to create and configure Unix or TCP sockets. package sockets import ( "errors" "net" "net/http" "time" ) const defaultTimeout = 10 * time.Second // ErrProtocolNotAvailable is returned when a given transport protocol is not provided by the operating system. var ErrProtocolNotAvailable = errors.New("protocol not available") // ConfigureTransport configures the specified Transport according to the // specified proto and addr. // If the proto is unix (using a unix socket to communicate) or npipe the // compression is disabled. func ConfigureTransport(tr *http.Transport, proto, addr string) error { switch proto { case "unix": return configureUnixTransport(tr, proto, addr) case "npipe": return configureNpipeTransport(tr, proto, addr) default: tr.Proxy = http.ProxyFromEnvironment dialer, err := DialerFromEnvironment(&net.Dialer{ Timeout: defaultTimeout, }) if err != nil { return err } tr.DialContext = dialer.DialContext } return nil }
// Package sockets provides helper functions to create and configure Unix or TCP sockets. package sockets import ( "errors" "net" "net/http" "time" ) // Why 32? See https://github.com/docker/docker/pull/8035. const defaultTimeout = 32 * time.Second // ErrProtocolNotAvailable is returned when a given transport protocol is not provided by the operating system. var ErrProtocolNotAvailable = errors.New("protocol not available") // ConfigureTransport configures the specified Transport according to the // specified proto and addr. // If the proto is unix (using a unix socket to communicate) or npipe the // compression is disabled. func ConfigureTransport(tr *http.Transport, proto, addr string) error { switch proto { case "unix": return configureUnixTransport(tr, proto, addr) case "npipe": return configureNpipeTransport(tr, proto, addr) default: tr.Proxy = http.ProxyFromEnvironment dialer, err := DialerFromEnvironment(&net.Dialer{ Timeout: defaultTimeout, }) if err != nil { return err } tr.DialContext = dialer.DialContext } return nil }
Clarify log, add error handler
'use strict'; const Firebase = require('firebase'); const firebase_secrets = require('../common/secrets/scrape-img.js').firebase; const dbRef = new Firebase(firebase_secrets.url); function pushAndAddUID(sourceObj) { console.log(`attempt to pushAndAddUID`) let targetBucket = sourceObj.s3_key.split('/').slice(0,2).join('/'); // console.log('targetBucket', targetBucket); let targetRef = dbRef.child(targetBucket) || dbRef.child('img_ref3'); const item = sourceObj; return new Promise((resolve, reject) => { targetRef.push(item) .then(tempRef => { tempRef.update({ uid: tempRef.key() }); console.log('pushAndAddUID success', typeof tempRef); resolve(tempRef); // return updated obj ref }) .catch(err => { resolve(null); }) }); } function postImgObjSetToFirebase(allImgData) { // console.log('returned final promise result', allImgData); return Promise.all(allImgData.map(imgData => pushAndAddUID(imgData, dbRef.child(imgRef)))); } module.exports = { dbRef: dbRef, pushAndAddUID: pushAndAddUID, }
'use strict'; const Firebase = require('firebase'); const firebase_secrets = require('../common/secrets/scrape-img.js').firebase; const dbRef = new Firebase(firebase_secrets.url); function pushAndAddUID(sourceObj) { console.log(`attempt to pushAndAddUID`) let targetBucket = sourceObj.s3_key.split('/').slice(0,2).join('/'); // console.log('targetBucket', targetBucket); let targetRef = dbRef.child(targetBucket) || dbRef.child('img_ref3'); const item = sourceObj; return new Promise((resolve, reject) => { targetRef.push(item) .then(tempRef => { tempRef.update({ uid: tempRef.key() }); // console.log('tempRef', tempRef); resolve(tempRef); // return updated obj ref }) // .then(() => { // // console.log(`item at ${targetRef.path.u[0]}/${item.uid} updated`); // }) .catch((err) => { sendErr(err); reject(err); }); }); } function postImgObjSetToFirebase(allImgData) { // console.log('returned final promise result', allImgData); return Promise.all(allImgData.map(imgData => pushAndAddUID(imgData, dbRef.child(imgRef)))); } module.exports = { dbRef: dbRef, pushAndAddUID: pushAndAddUID, }
Change default URL to display home content. Temporary fix.
from django.conf.urls import patterns, include, url from MyHub.home.views import home_page from MyHub.resume.views import resume_page from MyHub.projects.views import projects_page from MyHub.contact.views import contact_page from MyHub.views import loader_page from django.contrib import admin from django.conf import settings from django.conf.urls.static import static admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'MyHub.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^$', home_page, name='loader'), # url(r'^home/$', home_page, name='index'), # url(r'^resume/$', resume_page, name='resume'), # url(r'^projects/$', projects_page, name='projects'), # url(r'^contact/$', contact_page, name='contact'), # url(r'^admin/', include(admin.site.urls)), ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
from django.conf.urls import patterns, include, url from MyHub.home.views import home_page from MyHub.resume.views import resume_page from MyHub.projects.views import projects_page from MyHub.contact.views import contact_page from MyHub.views import loader_page from django.contrib import admin from django.conf import settings from django.conf.urls.static import static admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'MyHub.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^$', loader_page, name='loader'), url(r'^home/$', home_page, name='index'), url(r'^resume/$', resume_page, name='resume'), url(r'^projects/$', projects_page, name='projects'), url(r'^contact/$', contact_page, name='contact'), url(r'^admin/', include(admin.site.urls)), ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Remove unused code in course Ajax callbacks
<?php # Wordpress logic: add frontend hooks inside a is_admin() clause .. -.- if(is_admin()) { add_action("wp_ajax_nopriv_it_courses_filter", "courses_filter"); add_action("wp_ajax_it_courses_filter", "courses_filter"); } function courses_filter() { global $periods, $years; $year = intval(addslashes($_GET['year'])); $period = intval(addslashes($_GET['period'])); $periods = _get_terms_if("course_period", $period); $years = _get_terms_if("course_year", $year); partial("courses"); die(); } function _get_terms_if($term_name, $id) { $args = array(); if($id != -1) { $args = array( "include" => array($id) ); } return get_terms($term_name, $args); } ?>
<?php add_action("wp_ajax_nopriv_it_courses_filter", "courses_filter"); add_action("wp_ajax_it_courses_filter", "courses_filter"); function courses_filter() { global $periods, $years; $year = intval(addslashes($_GET['year'])); $period = intval(addslashes($_GET['period'])); $periods = _get_terms_if("course_period", $period); $years = _get_terms_if("course_year", $year); $args = array( "nopaging" => true, "post_type" => "course", "tax_query" => array( "relation" => "AND" ) ); if($year != -1) { $args['tax_query'][] = array( "taxonomy" => "course_year", "field" => "id", "terms" => $year ); } if($period != -1) { $args['tax_query'][] = array( "taxonomy" => "course_period", "field" => "id", "terms" => $period ); } #global $courses; #$courses = get_posts($args); partial("courses"); die(); } function _get_terms_if($term_name, $id) { $args = null; if($id != -1) { $args = array( "include" => array($id) ); } return get_terms($term_name, $args); } ?>
Add geojson as required dependency
import versioneer from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Read long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='tohu', version=versioneer.get_version(), description='Create random data in a controllable way', long_description=long_description, url='https://github.com/maxalbert/tohu', author='Maximilian Albert', author_email='maximilian.albert@gmail.com', license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Software Development :: Quality Assurance', 'Topic :: Software Development :: Testing', 'Topic :: Utilities', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', ], packages=['tohu', 'tohu/v4'], install_requires=['attrs', 'bidict', 'faker' 'geojson', 'pandas', 'psycopg2-binary', 'shapely', 'sqlalchemy', 'tqdm'], extras_require={ 'dev': ['ipython', 'jupyter'], 'test': ['pytest', 'nbval'], }, cmdclass=versioneer.get_cmdclass(), )
import versioneer from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Read long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='tohu', version=versioneer.get_version(), description='Create random data in a controllable way', long_description=long_description, url='https://github.com/maxalbert/tohu', author='Maximilian Albert', author_email='maximilian.albert@gmail.com', license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Software Development :: Quality Assurance', 'Topic :: Software Development :: Testing', 'Topic :: Utilities', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', ], packages=['tohu', 'tohu/v4'], install_requires=['attrs', 'bidict', 'faker', 'pandas', 'psycopg2-binary', 'shapely', 'sqlalchemy', 'tqdm'], extras_require={ 'dev': ['ipython', 'jupyter'], 'test': ['pytest', 'nbval'], }, cmdclass=versioneer.get_cmdclass(), )
Support custom options for each field
'use strict'; var Db = require('../'); module.exports = Db; require('./row'); Db.prototype.set('toDOMFieldset', function (document/*, options*/) { var options = Object(arguments[1]), names, container, rows, body; if (options.names != null) names = options.names; else names = this.getPropertyNames(options.tag); rows = Array.prototype.map.call(names, function (name) { var rel = this['_' + name]; return (rel.ns === this.db.Base) ? null : rel; }, this).filter(Boolean).sort(function (relA, relB) { return relA.order - relB.order; }).map(function (rel) { var controlOpts; if (options.control) controlOpts = this.plainCopy(options.control); if (options.controls && options.controls[rel.name]) { controlOpts = this.plainExtend(Object(controlOpts), options.controls[rel.name]); } return rel.toDOMInputRow(document, controlOpts); }, this.db); if (!rows.length) return null; container = document.createElement('fieldset'); container.setAttribute('class', 'dbjs'); body = container.appendChild(document.createElement('table')) .appendChild(document.createElement('tbody')); rows.forEach(body.appendChild, body); return container; });
'use strict'; var Db = require('../'); module.exports = Db; require('./row'); Db.prototype.set('toDOMFieldset', function (document/*, options*/) { var options = Object(arguments[1]), names, container, rows, body; if (options.names != null) names = options.names; else names = this.getPropertyNames(options.tag); rows = Array.prototype.map.call(names, function (name) { var rel = this['_' + name]; return (rel.ns === this.db.Base) ? null : rel; }, this).filter(Boolean).sort(function (relA, relB) { return relA.order - relB.order; }).map(function (rel) { return rel.toDOMInputRow(document, options.control); }); if (!rows.length) return null; container = document.createElement('fieldset'); container.setAttribute('class', 'dbjs'); body = container.appendChild(document.createElement('table')) .appendChild(document.createElement('tbody')); rows.forEach(body.appendChild, body); return container; });
Support lower level plugins (needed for Activiti BPM provider)
<?php /** * @package server-infra * @subpackage propel */ function searchFolder($pluginsFolder, $level = 1) { foreach(scandir($pluginsFolder) as $pluginDir) { if ($pluginDir[0] == ".") { continue; } $path = "$pluginsFolder/$pluginDir"; if (!is_dir($path)) { continue; } if ($level < 4) { searchFolder($path, $level + 1); } $pluginConfig = "$path/config"; $buildProps = "$pluginConfig/build.properties"; if (!file_exists($buildProps)) { continue; } if(!is_dir($pluginConfig)) throw new Exception("Illegal input was supplied."); chdir($pluginConfig); print $pluginConfig; passthru("propel-gen $pluginConfig"); } } $origWD = getcwd(); $rootFolder = realpath(dirname(__FILE__)."/../../../../.."); // Core $alphaConfigFolder = "$rootFolder/alpha/config"; if(!is_dir($alphaConfigFolder)) throw new Exception("Illegal input was supplied."); chdir($alphaConfigFolder); passthru("propel-gen $alphaConfigFolder"); // Plugin $pluginsFolder = "$rootFolder/plugins"; searchFolder($pluginsFolder); chdir($origWD);
<?php /** * @package server-infra * @subpackage propel */ function searchFolder($pluginsFolder, $level = 1) { foreach(scandir($pluginsFolder) as $pluginDir) { if ($pluginDir[0] == ".") { continue; } $path = "$pluginsFolder/$pluginDir"; if (!is_dir($path)) { continue; } if ($level < 2) { searchFolder($path, $level + 1); } $pluginConfig = "$path/config"; $buildProps = "$pluginConfig/build.properties"; if (!file_exists($buildProps)) { continue; } if(!is_dir($pluginConfig)) throw new Exception("Illegal input was supplied."); chdir($pluginConfig); print $pluginConfig; passthru("propel-gen $pluginConfig"); } } $origWD = getcwd(); $rootFolder = realpath(dirname(__FILE__)."/../../../../.."); // Core $alphaConfigFolder = "$rootFolder/alpha/config"; if(!is_dir($alphaConfigFolder)) throw new Exception("Illegal input was supplied."); chdir($alphaConfigFolder); passthru("propel-gen $alphaConfigFolder"); // Plugin $pluginsFolder = "$rootFolder/plugins"; searchFolder($pluginsFolder); chdir($origWD);
Simplify configure of django settings
from django.conf import settings from mock import Mock, patch from unittest2 import TestCase settings.configure() class TestPreference(object): def __init__(self, name, value, user=None): self.name = name self.value = value self.user = user def __eq__(self, other): return self.__dict__ == other.__dict__ def __repr__(self): return '<{name}:{value}:{user}>'.format(**self.__dict__) class TestUser(object): @property def preferences(self): return Mock(all=Mock(return_value=self._preferences)) @preferences.setter def preferences(self, value): self._preferences = [ TestPreference(k, v) for k, v in value.iteritems()] class SerializerTestCase(TestCase): def patch_from_native(self): patcher = patch( 'madprops.serializers.ModelSerializer.from_native', new=lambda self, data, files: TestPreference( data['name'], data['value'], data.get('user')) ) self.patched_from_native = patcher.start() self.addCleanup(patcher.stop)
from django.conf import settings from mock import Mock, patch from unittest2 import TestCase settings.configure( DEFAULT_INDEX_TABLESPACE='', ) class TestPreference(object): def __init__(self, name, value, user=None): self.name = name self.value = value self.user = user def __eq__(self, other): return self.__dict__ == other.__dict__ def __repr__(self): return '<{name}:{value}:{user}>'.format(**self.__dict__) class TestUser(object): @property def preferences(self): return Mock(all=Mock(return_value=self._preferences)) @preferences.setter def preferences(self, value): self._preferences = [ TestPreference(k, v) for k, v in value.iteritems()] class SerializerTestCase(TestCase): def patch_from_native(self): patcher = patch( 'madprops.serializers.ModelSerializer.from_native', new=lambda self, data, files: TestPreference( data['name'], data['value'], data.get('user')) ) self.patched_from_native = patcher.start() self.addCleanup(patcher.stop)
Update urlpatterns and remove old patterns pattern
from django.conf.urls import url from django.utils.translation import ugettext_lazy as _ from .views import ( RealmView, RealmCorrectionsView, EntitySearchView, EntityListView, EntityDetailView, EntityDetailNetworkEmbedView, ) from .api_views import ( YolodexRouter, EntityViewSet, EntityTypeViewSet ) router = YolodexRouter() router.register(r'api/entity', EntityViewSet, 'entity') router.register(r'api/entitytype', EntityTypeViewSet, 'entitytype') entity_urls = [ url(r'^$', RealmView.as_view(), name='overview'), url(_(r'^corrections/$'), RealmCorrectionsView.as_view(), name='corrections'), url(_(r'^search/$'), EntitySearchView.as_view(), name='search'), url(r'^(?P<type>[\w-]+)/$', EntityListView.as_view(), name='entity_list'), url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/$', EntityDetailView.as_view(), name='entity_detail'), url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/embed/$', EntityDetailNetworkEmbedView.as_view(), name='entity_detail_embed'), ] urlpatterns = router.urls urlpatterns += entity_urls
from django.conf.urls import patterns, url from django.utils.translation import ugettext_lazy as _ from .views import ( RealmView, RealmCorrectionsView, EntitySearchView, EntityListView, EntityDetailView, EntityDetailNetworkEmbedView, ) from .api_views import ( YolodexRouter, EntityViewSet, EntityTypeViewSet ) router = YolodexRouter() router.register(r'api/entity', EntityViewSet, 'entity') router.register(r'api/entitytype', EntityTypeViewSet, 'entitytype') entity_urls = [ url(r'^$', RealmView.as_view(), name='overview'), url(_(r'^corrections/$'), RealmCorrectionsView.as_view(), name='corrections'), url(_(r'^search/$'), EntitySearchView.as_view(), name='search'), url(r'^(?P<type>[\w-]+)/$', EntityListView.as_view(), name='entity_list'), url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/$', EntityDetailView.as_view(), name='entity_detail'), url(r'^(?P<type>[\w-]+)/(?P<slug>[\w-]+)/embed/$', EntityDetailNetworkEmbedView.as_view(), name='entity_detail_embed'), ] urlpatterns = router.urls urlpatterns += patterns('', *entity_urls)
Use Web authentication for API, too
var User = require('../models').User, restify = require('express-restify-mongoose'); /* * Middleware for all API requests that looks for a token * in the header and validates it against the list of authorized * users, returning an error if it's invalid. */ module.exports = function(req, res, next) { // Skip header authorization for users with an active passwordless // session if(typeof req.user !== 'undefined') { return next(); } var key = req.header('Authorization'); if(typeof key === 'undefined') { return res.status(400).send('An API key is required.'); } User.findByKey(key, function(err, user) { if(err) return next(err); if(user) { req.user = user.id; next(); } else { res.status(401).send('Invalid API key.'); } }); };
var User = require('../models').User, restify = require('express-restify-mongoose'); /* * Middleware for all API requests that looks for a token * parameter and validates it against the list of authorized * users, returning an error if it's invalid. */ module.exports = function(req, res, next) { // TODO: Skip validation based on header if there's already a // user set meaning (meaning this is probably a Web request // that's already authed) var key = req.header('Authorization'); if(typeof key === 'undefined') { return res.status(400).send('An API key is required.'); } User.findByKey(key, function(err, user) { if(err) return next(err); if(user) { req.user = user; next(); } else { res.status(401).send('Invalid API key.'); } }); };
Add test coverage for invalid regex
package com.hubspot.jinjava.lib.filter; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Before; import org.junit.Test; import com.hubspot.jinjava.Jinjava; import com.hubspot.jinjava.interpret.InterpretException; import com.hubspot.jinjava.interpret.JinjavaInterpreter; public class RegexReplaceFilterTest { JinjavaInterpreter interpreter; RegexReplaceFilter filter; @Before public void setup() { interpreter = new Jinjava().newInterpreter(); filter = new RegexReplaceFilter(); } @Test(expected = InterpretException.class) public void expects2Args() { filter.filter("foo", interpreter); } public void noopOnNullExpr() { assertThat(filter.filter(null, interpreter, "foo", "bar")).isNull(); } @Test public void itMatchesRegexAndReplacesString() { assertThat(filter.filter("It costs $300", interpreter, "[^a-zA-Z]", "")).isEqualTo("Itcosts"); } @Test(expected = InterpretException.class) public void isThrowsExceptionOnInvalidRegex() { filter.filter("It costs $300", interpreter, "[", ""); } }
package com.hubspot.jinjava.lib.filter; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Before; import org.junit.Test; import com.hubspot.jinjava.Jinjava; import com.hubspot.jinjava.interpret.InterpretException; import com.hubspot.jinjava.interpret.JinjavaInterpreter; public class RegexReplaceFilterTest { JinjavaInterpreter interpreter; RegexReplaceFilter filter; @Before public void setup() { interpreter = new Jinjava().newInterpreter(); filter = new RegexReplaceFilter(); } @Test(expected = InterpretException.class) public void expects2Args() { filter.filter("foo", interpreter); } public void noopOnNullExpr() { assertThat(filter.filter(null, interpreter, "foo", "bar")).isNull(); } @Test public void replaceString() { assertThat(filter.filter("It costs $300", interpreter, "[^a-zA-Z]", "")).isEqualTo("Itcosts"); } }
Remove mkl as direct dependency This breaks the conda-forge build, since the pip mkl and conda mkl aren't the same packages, so `pip check` fails. mkl is a dependency of mkl-service and will still be installed with pip install.
from setuptools import setup setup( name='pypardiso', version="0.3.1", packages=['pypardiso'], install_requires=['mkl-service', 'numpy', 'scipy', 'psutil'], author="Adrian Haas", license=open('LICENSE.txt').read(), url="https://github.com/haasad/PyPardisoProject", long_description=open('README.md').read(), description='Python interface to the Intel MKL Pardiso library to solve large sparse linear systems of equations', classifiers=[ 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: Scientific/Engineering :: Mathematics', 'Topic :: Scientific/Engineering :: Visualization', ], )
from setuptools import setup setup( name='pypardiso', version="0.3.1", packages=['pypardiso'], install_requires=['mkl', 'mkl-service', 'numpy', 'scipy', 'psutil'], author="Adrian Haas", license=open('LICENSE.txt').read(), url="https://github.com/haasad/PyPardisoProject", long_description=open('README.md').read(), description='Python interface to the Intel MKL Pardiso library to solve large sparse linear systems of equations', classifiers=[ 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: Scientific/Engineering :: Mathematics', 'Topic :: Scientific/Engineering :: Visualization', ], )
Update knowledge provider to work with API changes.
""" Knowledge provider that will respond to requests made by the rdf publisher or another bot. """ from sleekxmpp.plugins.base import base_plugin from rhobot.components.storage.client import StoragePayload from rdflib.namespace import FOAF from rhobot.namespace import RHO import logging logger = logging.getLogger(__name__) class KnowledgeProvider(base_plugin): name = 'knowledge_provider' description = 'Knowledge Provider' dependencies = {'rho_bot_storage_client', 'rho_bot_rdf_publish', } type_requirements = {str(FOAF.Person), str(RHO.Owner), } def plugin_init(self): pass def post_init(self): base_plugin.post_init(self) self.xmpp['rho_bot_rdf_publish'].add_request_handler(self._rdf_request_message) def _rdf_request_message(self, rdf_payload): logger.info('Looking up knowledge') form = rdf_payload['form'] payload = StoragePayload(form) intersection = self.type_requirements.intersection(set(payload.types())) if len(intersection) == len(payload.types()): results = self.xmpp['rho_bot_storage_client'].find_nodes(payload) if len(results.results()): return results return None knowledge_provider = KnowledgeProvider
""" Knowledge provider that will respond to requests made by the rdf publisher or another bot. """ from sleekxmpp.plugins.base import base_plugin from rhobot.components.storage.client import StoragePayload from rdflib.namespace import FOAF from rhobot.namespace import RHO import logging logger = logging.getLogger(__name__) class KnowledgeProvider(base_plugin): name = 'knowledge_provider' description = 'Knowledge Provider' dependencies = {'rho_bot_storage_client', 'rho_bot_rdf_publish', } type_requirements = {str(FOAF.Person), str(RHO.Owner), } def plugin_init(self): pass def post_init(self): base_plugin.post_init(self) self.xmpp['rho_bot_rdf_publish'].add_message_handler(self._rdf_request_message) def _rdf_request_message(self, rdf_payload): logger.info('Looking up knowledge') form = rdf_payload['form'] payload = StoragePayload(form) intersection = self.type_requirements.intersection(set(payload.types())) if len(intersection) == len(payload.types()): results = self.xmpp['rho_bot_storage_client'].find_nodes(payload) if len(results.results()): return results return None knowledge_provider = KnowledgeProvider
Make edit the default project view
import React from 'react' import { BrowserRouter as Router, Redirect, Route, Switch } from 'react-router-dom' import Header from './components/header' import Footer from './components/footer' import Homepage from './screens/homepage' import UserDashboard from './screens/userDashboard' import ProjectScreen from './screens/project' export default () => <Router> <div className="wrapper"> <Header /> <Route exact path="/" component={Homepage} /> <Route exact path="/:username" component={UserDashboard} /> <Route path="/:username/:project" render={({ match }) => <Redirect to={`${match.url}/edit`.replace('//', '/')} />} /> <Switch> <Route path="/:username/:project/:mode" component={ProjectScreen} /> <Route path="/:username/:owner/:project/:mode" component={ProjectScreen} /> </Switch> <Footer /> </div> </Router>
import React from 'react' import { BrowserRouter as Router, Route, Switch } from 'react-router-dom' import Header from './components/header' import Footer from './components/footer' import Homepage from './screens/homepage' import UserDashboard from './screens/userDashboard' import ProjectScreen from './screens/project' export default () => <Router> <div className="wrapper"> <Header /> <Route exact path="/" component={Homepage} /> <Route exact path="/:username" component={UserDashboard} /> <Switch> <Route path="/:username/:project/:mode?" component={ProjectScreen} /> <Route path="/:username/:owner/:project/:mode?" component={ProjectScreen} /> </Switch> <Footer /> </div> </Router>
Use dialog to report invalid app.
var app = require('app'); var dialog = require('dialog'); var path = require('path'); var optimist = require('optimist'); // Quit when all windows are closed and no other one is listening to this. app.on('window-all-closed', function() { if (app.listeners('window-all-closed').length == 1) app.quit(); }); var argv = optimist(process.argv.slice(1)).boolean('ci').argv; // Start the specified app if there is one specified in command line, otherwise // start the default app. if (argv._.length > 0) { try { require(path.resolve(argv._[0])); } catch(e) { if (e.code == 'MODULE_NOT_FOUND') { app.focus(); dialog.showMessageBox({ type: 'warning', buttons: ['OK'], title: 'Error opening app', message: 'The app provided is not a valid atom-shell app, please read the docs on how to write one:', detail: 'https://github.com/atom/atom-shell/tree/master/docs' }); process.exit(1); } else { throw e; } } } else if (argv.version) { console.log('v' + process.versions['atom-shell']); process.exit(0); } else { require('./default_app.js'); }
var app = require('app'); var path = require('path'); var optimist = require('optimist'); // Quit when all windows are closed and no other one is listening to this. app.on('window-all-closed', function() { if (app.listeners('window-all-closed').length == 1) app.quit(); }); var argv = optimist(process.argv.slice(1)).boolean('ci').argv; // Start the specified app if there is one specified in command line, otherwise // start the default app. if (argv._.length > 0) { try { require(path.resolve(argv._[0])); } catch(e) { if (e.code == 'MODULE_NOT_FOUND') { console.error(e.stack); console.error('Specified app is invalid'); process.exit(1); } else { throw e; } } } else if (argv.version) { console.log('v' + process.versions['atom-shell']); process.exit(0); } else { require('./default_app.js'); }
Add placeholder to the whitelist The placeholder from inputProperties gets removed when whitelistInputProps() is called in FormComponentInner.jsx, so placeholders get removed from smartform text inputs. This adds placeholder to the whitelist of supported fields so they are once again shown on Smartforms.
import pick from 'lodash/pick'; /** * Extract input props for the FormComponentInner * @param {*} props All component props * @returns Initial props + props specific to the HTML input in an inputProperties object */ export const getHtmlInputProps = props => { const { name, path, options, label, onChange, onBlur, value, disabled } = props; // these properties are whitelisted so that they can be safely passed to the actual form input // and avoid https://facebook.github.io/react/warnings/unknown-prop.html warnings const inputProperties = { ...props.inputProperties, name, path, options, label, onChange, onBlur, value, disabled, }; return { ...props, inputProperties, }; }; /** * Extract input props for the FormComponentInner * @param {*} props All component props * @returns Initial props + props specific to the HTML input in an inputProperties object */ export const whitelistInputProps = props => { const whitelist = ['name', 'path', 'options', 'label', 'onChange', 'onBlur', 'value', 'disabled', 'placeholder']; return pick(props, whitelist); };
import pick from 'lodash/pick'; /** * Extract input props for the FormComponentInner * @param {*} props All component props * @returns Initial props + props specific to the HTML input in an inputProperties object */ export const getHtmlInputProps = props => { const { name, path, options, label, onChange, onBlur, value, disabled } = props; // these properties are whitelisted so that they can be safely passed to the actual form input // and avoid https://facebook.github.io/react/warnings/unknown-prop.html warnings const inputProperties = { ...props.inputProperties, name, path, options, label, onChange, onBlur, value, disabled, }; return { ...props, inputProperties, }; }; /** * Extract input props for the FormComponentInner * @param {*} props All component props * @returns Initial props + props specific to the HTML input in an inputProperties object */ export const whitelistInputProps = props => { const whitelist = ['name', 'path', 'options', 'label', 'onChange', 'onBlur', 'value', 'disabled']; return pick(props, whitelist); };
Enable strict mode in debug.
package org.willemsens.player; import android.app.Application; import android.os.StrictMode; import com.crashlytics.android.Crashlytics; import com.crashlytics.android.answers.Answers; import com.crashlytics.android.core.CrashlyticsCore; import io.fabric.sdk.android.Fabric; public class PlayerApplication extends Application { @Override public void onCreate() { super.onCreate(); if (BuildConfig.USE_CRASHLYTICS) { Crashlytics crashlyticsKit = new Crashlytics.Builder() .core(new CrashlyticsCore.Builder().disabled(false).build()) .build(); Fabric.with(this, crashlyticsKit); } if (BuildConfig.USE_ANSWERS) { Fabric.with(this, new Answers()); } if (BuildConfig.DEBUG) { StrictMode.enableDefaults(); } } }
package org.willemsens.player; import android.app.Application; import com.crashlytics.android.Crashlytics; import com.crashlytics.android.answers.Answers; import com.crashlytics.android.core.CrashlyticsCore; import io.fabric.sdk.android.Fabric; public class PlayerApplication extends Application { @Override public void onCreate() { super.onCreate(); if (BuildConfig.USE_CRASHLYTICS) { Crashlytics crashlyticsKit = new Crashlytics.Builder() .core(new CrashlyticsCore.Builder().disabled(false).build()) .build(); Fabric.with(this, crashlyticsKit); } if (BuildConfig.USE_ANSWERS) { Fabric.with(this, new Answers()); } // It looks like Fabric / Crashlytics sockets aren't being tagged as they should so strict mode can't be enabled. // https://github.com/square/okhttp/issues/3537 // StrictMode.enableDefaults(); } }
Add include keyword arg to is_tranformed
import json def is_transformed(transform, predicate, *args, exceptions=[ Exception ], msg='data can\'t be transformed', **kwargs): def is_valid(data, explain=False, include=False): try: data = transform(data, *args, **kwargs) except Exception as e: if not any(isinstance(e, exc) for exc in exceptions): raise e return ( (False, msg, None) if explain else (False, None) ) if include else ( (False, msg) if explain else False ) return (( predicate(data, explain=True) + (data,) ) if explain else ( predicate(data), data )) if include else predicate(data, explain=explain) return is_valid def is_json(predicate, *args, **kwargs): return is_transformed(json.loads, predicate, *args, exceptions=[ json.JSONDecodeError ], msg='data is not valid json', **kwargs)
import json def is_transformed(transform, predicate, *args, exceptions=[ Exception ], msg='data can\'t be transformed', **kwargs): def is_valid(data, explain=False): try: data = transform(data, *args, **kwargs) except Exception as e: if not any(isinstance(e, exc) for exc in exceptions): raise e return (False, msg) if explain else False return predicate(data, explain=explain) return is_valid def is_json(predicate, *args, **kwargs): return is_transformed(json.loads, predicate, *args, exceptions=[ json.JSONDecodeError ], msg='data is not valid json', **kwargs)
Rename gulp 'dist' target to 'release'.
var gulp = require('gulp'); var rename = require('gulp-rename'); var browserify = require('browserify'); var source = require('vinyl-source-stream'); var buffer = require('vinyl-buffer'); var uglify = require('gulp-uglify'); var babelify = require('babelify'); gulp.task('default', ['build', 'watch']); gulp.task('watch', function () { gulp.watch('./src/*.js', ['build']); gulp.watch('./*.js', ['build']); }); function build(file) { return browserify(file, { noParse: [require.resolve('./src/zxing')] }) .transform(babelify, { ignore: /zxing\.js$/i, presets: ['es2015'], plugins: ['syntax-async-functions', 'transform-regenerator'] }) .bundle() .pipe(source('instascan.js')); } gulp.task('release', function () { return build('./export.js') .pipe(buffer()) .pipe(uglify()) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest('./dist/')); }); gulp.task('build', function () { return build('./export.js') .pipe(gulp.dest('./dist/')); });
var gulp = require('gulp'); var rename = require('gulp-rename'); var browserify = require('browserify'); var source = require('vinyl-source-stream'); var buffer = require('vinyl-buffer'); var uglify = require('gulp-uglify'); var babelify = require('babelify'); gulp.task('default', ['build', 'watch']); gulp.task('watch', function () { gulp.watch('./src/*.js', ['build']); gulp.watch('./*.js', ['build']); }); function build(file) { return browserify(file, { noParse: [require.resolve('./src/zxing')] }) .transform(babelify, { ignore: /zxing\.js$/i, presets: ['es2015'], plugins: ['syntax-async-functions', 'transform-regenerator'] }) .bundle() .pipe(source('instascan.js')); } gulp.task('dist', function () { return build('./export.js') .pipe(buffer()) .pipe(uglify()) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest('./dist/')); }); gulp.task('build', function () { return build('./export.js') .pipe(gulp.dest('./dist/')); });
Change to postgres by default
DEBUG = True ADMINS = ( ('Zaphod Beeblebrox', 'hoopyfrood@heartofgold.com'), ) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '^lkajsdlfkjaoif09ijoi23092309i02[93ip2j3[r29u3[0923jorij' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db_name_here', 'USER': 'db_user_here', 'PASSWORD': 'db_password_here', 'HOST': 'localhost', 'PORT': '5432', } } EMAIL_HOST = '' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_PORT = 587 DEFAULT_FROM_EMAIL = 'My Site Admin <me@myproject.com>' # Because message cookies and BrowserSync don't play nicely MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage' GOOGLE_ACCOUNT_CODE = "UA-XXXXXXX-XX"
DEBUG = True ADMINS = ( ('Zaphod Beeblebrox', 'hoopyfrood@heartofgold.com'), ) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '^lkajsdlfkjaoif09ijoi23092309i02[93ip2j3[r29u3[0923jorij' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name_here', 'USER': 'db_user_here', 'PASSWORD': 'db_password_here', 'HOST': 'localhost', 'PORT': '3306', } } EMAIL_HOST = '' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_PORT = 587 DEFAULT_FROM_EMAIL = 'My Site Admin <me@myproject.com>' # Because message cookies and BrowserSync don't play nicely MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage' GOOGLE_ACCOUNT_CODE = "UA-XXXXXXX-XX"
Remove video device from tests
/* * Mach-84: The Virtual Machinery Playpen * Inspired by the Vintage Computer Club * * Copyright (c) 2014 blackchip.org * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ var config = module.exports; config["mach84"] = { rootPath: "./", environment: "browser", libs: [ "src/lib/**/*.js" ], src: [ "src/js/**/*.js", "!src/js/m84.main.js", "!src/js/devices/m84.video.js" ], tests: [ "test/**/*.js" ] };
/* * Mach-84: The Virtual Machinery Playpen * Inspired by the Vintage Computer Club * * Copyright (c) 2014 blackchip.org * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ var config = module.exports; config["mach84"] = { rootPath: "./", environment: "browser", libs: [ "src/lib/**/*.js" ], src: [ "src/js/**/*.js" ], tests: [ "test/**/*.js" ] };
Upgrade of prompt-toolkit and ptpython.
#!/usr/bin/env python import os from setuptools import setup, find_packages import pyvim long_description = open( os.path.join( os.path.dirname(__file__), 'README.rst' ) ).read() setup( name='pyvim', author='Jonathan Slenders', version=pyvim.__version__, license='LICENSE', url='https://github.com/jonathanslenders/pyvim', description='Pure Pyton Vi Implementation', long_description=long_description, packages=find_packages('.'), install_requires = [ 'prompt-toolkit==0.50', 'ptpython==0.22', # For the Python completion (with Jedi.) 'pyflakes', # For Python error reporting. 'docopt', # For command line arguments. ], entry_points={ 'console_scripts': [ 'pyvim = pyvim.entry_points.run_pyvim:run', ] }, )
#!/usr/bin/env python import os from setuptools import setup, find_packages import pyvim long_description = open( os.path.join( os.path.dirname(__file__), 'README.rst' ) ).read() setup( name='pyvim', author='Jonathan Slenders', version=pyvim.__version__, license='LICENSE', url='https://github.com/jonathanslenders/pyvim', description='Pure Pyton Vi Implementation', long_description=long_description, packages=find_packages('.'), install_requires = [ 'prompt-toolkit==0.46', 'ptpython==0.21', # For the Python completion (with Jedi.) 'pyflakes', # For Python error reporting. 'docopt', # For command line arguments. ], entry_points={ 'console_scripts': [ 'pyvim = pyvim.entry_points.run_pyvim:run', ] }, )
Add promisify function to reduce redundancy
'use strict' const childProcess = require('child_process') const fs = require('fs') function exec (command, options) { return new Promise(function (resolve, reject) { childProcess.exec(command, options, function (err, stdout, stderr) { if (err) { reject(err) } else { resolve({command, stdout, stderr}) } }) }) } function exists (path) { return new Promise(function (resolve, reject) { fs.exists(path, function (exists) { if (exists) { resolve() } else { reject() } }) }) } function promisify (fn) { return function () { const args = Array.prototype.slice.call(arguments) return new Promise(function (resolve, reject) { function callback (err) { if (err) { reject(err) } else { const data = Array.prototype.slice.call(arguments, 1) resolve(data) } } fn.apply(null, args.concat(callback)) }) } } module.exports = { exec, exists, mkdir: promisify(fs.mkdir), readFile: promisify(fs.readFile) }
'use strict' const childProcess = require('child_process') const fs = require('fs') function exec (command, options) { return new Promise(function (resolve, reject) { childProcess.exec(command, options, function (err, stdout, stderr) { if (err) { reject(err) } else { resolve({command, stdout, stderr}) } }) }) } function mkdir (path) { return new Promise(function (resolve, reject) { fs.mkdir(path, function (err) { if (err) { reject(err) } else { resolve() } }) }) } function exists (path) { return new Promise(function (resolve, reject) { fs.exists(path, function (exists) { if (exists) { resolve() } else { reject() } }) }) } function readFile (path) { return new Promise(function (resolve, reject) { fs.readFile(path, function (err, data) { if (err) { reject(err) } else { resolve(data) } }) }) } module.exports = { exec, mkdir, exists, readFile }
Handle register flag; use CONN_MGR_PARAM_FLAG_REQUIRED not 1L 20070911135601-4210b-dec39420c4af7a81bd9b6060cb81d787ebb707fc.gz
#!/usr/bin/python import sys import telepathy from telepathy.interfaces import CONN_MGR_INTERFACE from telepathy.constants import CONN_MGR_PARAM_FLAG_REQUIRED, \ CONN_MGR_PARAM_FLAG_REGISTER if len(sys.argv) >= 2: manager_name = sys.argv[1] else: manager_name = "haze" service_name = "org.freedesktop.Telepathy.ConnectionManager.%s" % manager_name object_path = "/org/freedesktop/Telepathy/ConnectionManager/%s" % manager_name object = telepathy.client.ConnectionManager(service_name, object_path) manager = object[CONN_MGR_INTERFACE] print "[ConnectionManager]" print "BusName=%s" % service_name print "ObjectPath=%s" % object_path print protocols = manager.ListProtocols() protocols.sort() for protocol in protocols: print "[Protocol %s]" % protocol for param in manager.GetParameters(protocol): (name, flags, type, default) = param print "param-%s=%s" % (name, type), if flags & CONN_MGR_PARAM_FLAG_REQUIRED: print "required", if flags & CONN_MGR_PARAM_FLAG_REGISTER: print "register", print print
#!/usr/bin/python import sys import telepathy from telepathy.interfaces import CONN_MGR_INTERFACE if len(sys.argv) >= 2: manager_name = sys.argv[1] else: manager_name = "haze" service_name = "org.freedesktop.Telepathy.ConnectionManager.%s" % manager_name object_path = "/org/freedesktop/Telepathy/ConnectionManager/%s" % manager_name object = telepathy.client.ConnectionManager(service_name, object_path) manager = object[CONN_MGR_INTERFACE] print "[ConnectionManager]" print "BusName=%s" % service_name print "ObjectPath=%s" % object_path print protocols = manager.ListProtocols() protocols.sort() for protocol in protocols: print "[Protocol %s]" % protocol for param in manager.GetParameters(protocol): print "param-%s=%s" % (param[0], param[2]), # FIXME: deal with the "register" flag if param[1] == 1L: print "required", print print
Add extra keys to telegram UI
import React from 'react' import { FormattedMessage } from 'react-intl' export const TelegramDetails = ({ measurement }) => { return ( <div> {measurement.test_keys.telegram_tcp_blocking === false && measurement.test_keys.telegram_http_blocking === false && <div> <h2 className='result-success'><i className='fa fa-check-circle-o' /> <FormattedMessage id='nettests.telegram.working' defaultMessage='Telegram is working' /> </h2> </div> } {measurement.test_keys.telegram_tcp_blocking === true || measurement.test_keys.telegram_http_blocking === true && <div> <h2 className='result-success'><i className='fa fa-check-circle-o' /> <FormattedMessage id='nettests.telegram.censorship' defaultMessage='Evidence of possible censorship' /> </h2> </div> } </div> ) } TelegramDetails.propTypes = { measurement: React.PropTypes.object } export default TelegramDetails
import React from 'react' import { FormattedMessage } from 'react-intl' export const TelegramDetails = ({ measurement }) => { return ( <div> {measurement.test_keys.telegram_tcp_blocking === false && <div> <h2 className='result-success'><i className='fa fa-check-circle-o' /> <FormattedMessage id='nettests.telegram.working' defaultMessage='Telegram is working' /> </h2> </div> } {measurement.test_keys.telegram_tcp_blocking === true && <div> <h2 className='result-success'><i className='fa fa-check-circle-o' /> <FormattedMessage id='nettests.telegram.censorship' defaultMessage='Evidence of possible censorship' /> </h2> </div> } </div> ) } TelegramDetails.propTypes = { measurement: React.PropTypes.object } export default TelegramDetails
Return zero length when value is null
package io.parsingdata.metal.expression.value.reference; import static io.parsingdata.metal.Util.checkNotNull; import io.parsingdata.metal.data.Environment; import io.parsingdata.metal.data.ParseValue; import io.parsingdata.metal.encoding.Encoding; import io.parsingdata.metal.expression.value.ConstantFactory; import io.parsingdata.metal.expression.value.OptionalValue; import io.parsingdata.metal.expression.value.Value; import io.parsingdata.metal.expression.value.ValueExpression; public class Len implements ValueExpression { private final String _name; public Len(final String name) { _name = checkNotNull(name, "name"); } @Override public OptionalValue eval(final Environment env, final Encoding enc) { final ParseValue value = env.order.get(_name); return OptionalValue.of(value == null || value.getValue() == null ? num(0) : num(value.getValue().length)); } private static Value num(final long length) { return ConstantFactory.createFromNumeric(length, new Encoding(true)); } @Override public String toString() { return getClass().getSimpleName() + "(" + _name + ")"; } }
package io.parsingdata.metal.expression.value.reference; import static io.parsingdata.metal.Util.checkNotNull; import io.parsingdata.metal.data.Environment; import io.parsingdata.metal.data.ParseValue; import io.parsingdata.metal.encoding.Encoding; import io.parsingdata.metal.expression.value.ConstantFactory; import io.parsingdata.metal.expression.value.OptionalValue; import io.parsingdata.metal.expression.value.ValueExpression; public class Len implements ValueExpression { private final String _name; public Len(final String name) { _name = checkNotNull(name, "name"); } @Override public OptionalValue eval(final Environment env, final Encoding enc) { final ParseValue value = env.order.get(_name); return OptionalValue.of(value == null || value.getValue() == null ? null : ConstantFactory.createFromNumeric(value.getValue().length, new Encoding(true))); } @Override public String toString() { return getClass().getSimpleName() + "(" + _name + ")"; } }
Make fees dao test clearer
from app.dao.fees_dao import dao_update_fee, dao_get_fees, dao_get_fee_by_id from app.models import Fee from tests.db import create_fee class WhenUsingFeesDAO(object): def it_creates_a_fee(self, db_session): fee = create_fee() assert Fee.query.count() == 1 fee_from_db = Fee.query.filter(Fee.id == fee.id).first() assert fee == fee_from_db def it_updates_a_fee_dao(self, db, db_session, sample_fee): dao_update_fee(sample_fee.id, fee=10) fee_from_db = Fee.query.filter(Fee.id == sample_fee.id).first() assert fee_from_db.fee == 10 def it_gets_all_fees(self, db, db_session, sample_fee): fees = [create_fee(fee=100, conc_fee=80), sample_fee] fees_from_db = dao_get_fees() assert Fee.query.count() == 2 assert set(fees) == set(fees_from_db) def it_gets_a_fee_by_id(self, db, db_session, sample_fee): fee = create_fee(fee=100, conc_fee=80) fetched_fee = dao_get_fee_by_id(fee.id) assert fetched_fee == fee
from app.dao.fees_dao import dao_update_fee, dao_get_fees, dao_get_fee_by_id from app.models import Fee from tests.db import create_fee class WhenUsingFeesDAO(object): def it_creates_a_fee(self, db_session): fee = create_fee() assert Fee.query.count() == 1 fee_from_db = Fee.query.filter(Fee.id == fee.id).first() assert fee == fee_from_db def it_updates_a_fee_dao(self, db, db_session, sample_fee): dao_update_fee(sample_fee.id, fee=10) fee_from_db = Fee.query.filter(Fee.id == sample_fee.id).first() assert sample_fee.fee == fee_from_db.fee def it_gets_all_fees(self, db, db_session, sample_fee): fees = [create_fee(fee=100, conc_fee=80), sample_fee] fees_from_db = dao_get_fees() assert Fee.query.count() == 2 assert set(fees) == set(fees_from_db) def it_gets_a_fee_by_id(self, db, db_session, sample_fee): fee = create_fee(fee=100, conc_fee=80) fetched_fee = dao_get_fee_by_id(fee.id) assert fetched_fee == fee
Fix PHP Notice Undefined variable "current_dc_id"
<?php /** * @package Core * @subpackage externalWidgets */ class servefileAction extends sfAction { /** * Will forward to the regular swf player according to the widget_id */ public function execute() { requestUtils::handleConditionalGet(); $file_sync_id = $this->getRequestParameter( "id" ); $hash = $this->getRequestParameter( "hash" ); $file_name = $this->getRequestParameter( "fileName" ); if ($file_name) { $file_name = base64_decode($file_name); } $file_sync = FileSyncPeer::retrieveByPk ( $file_sync_id ); if ( ! $file_sync ) { $current_dc_id = kDataCenterMgr::getCurrentDcId(); $error = "DC[$current_dc_id]: Cannot find FileSync with id [$file_sync_id]"; KalturaLog::err($error); throw new Exception ($error); } KalturaMonitorClient::initApiMonitor(false, 'extwidget.serveFile', $file_sync->getPartnerId()); kDataCenterMgr::serveFileToRemoteDataCenter ( $file_sync , $hash, $file_name ); die(); } }
<?php /** * @package Core * @subpackage externalWidgets */ class servefileAction extends sfAction { /** * Will forward to the regular swf player according to the widget_id */ public function execute() { requestUtils::handleConditionalGet(); $file_sync_id = $this->getRequestParameter( "id" ); $hash = $this->getRequestParameter( "hash" ); $file_name = $this->getRequestParameter( "fileName" ); if ($file_name) { $file_name = base64_decode($file_name); } $file_sync = FileSyncPeer::retrieveByPk ( $file_sync_id ); if ( ! $file_sync ) { $error = "DC[$current_dc_id]: Cannot find FileSync with id [$file_sync_id]"; KalturaLog::err($error); throw new Exception ($error); } KalturaMonitorClient::initApiMonitor(false, 'extwidget.serveFile', $file_sync->getPartnerId()); kDataCenterMgr::serveFileToRemoteDataCenter ( $file_sync , $hash, $file_name ); die(); } }
Correct version for deploy to GAE
//Command to run test version: //goapp serve app.yaml //Command to deploy/update application: //goapp deploy -application golangnode0 -version 0 package main import ( "fmt" "net/http" ) func helloWorld(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello World!") } func startPage(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Hello, test server started on 8080 port.\n - /helloworld - show title page\n - /showinfo - show information about this thing") } func showInfo(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Inforamtion page for test project.\nLanguage - Go\nPlatform - Google Application Engine") } func init() { http.HandleFunc("/", startPage) http.HandleFunc("/helloworld", helloWorld) http.HandleFunc("/showinfo", showInfo) //Wrong code for App Enine - server cant understand what it need to show //http.ListenAndServe(":80", nil) } /* func main() { fmt.Println("Hello, test server started on 80 port.\n - /helloworld - show title page\n - /showinfo - show information about this thing") http.HandleFunc("/", startPage) http.HandleFunc("/helloworld", helloWorld) http.HandleFunc("/showinfo", showInfo) http.ListenAndServe(":80", nil) } */
package main import ( "fmt" "net/http" ) func helloWorld(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello World!") } func startPage(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Hello, test server started on 8080 port.\n - /helloworld - show title page\n - /showinfo - show information about this thing") } func showInfo(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Inforamtion page for test project.\nLanguage - Go\nPlatform - Google Application Engine") } func init() { http.HandleFunc("/", startPage) http.HandleFunc("/helloworld", helloWorld) http.HandleFunc("/showinfo", showInfo) //Wrong code for App Enine - server cant understand what it need to show //http.ListenAndServe(":80", nil) } /* func main() { fmt.Println("Hello, test server started on 80 port.\n - /helloworld - show title page\n - /showinfo - show information about this thing") http.HandleFunc("/", startPage) http.HandleFunc("/helloworld", helloWorld) http.HandleFunc("/showinfo", showInfo) http.ListenAndServe(":80", nil) } */ //goapp serve app.yaml //goapp deploy -application golangnode0 -version 0
Fix issue with spaces inside emphasis tags If value starts or ends with a space, remove space and re-add it outside markdown tags
<?php namespace League\HTMLToMarkdown\Converter; use League\HTMLToMarkdown\Configuration; use League\HTMLToMarkdown\ConfigurationAwareInterface; use League\HTMLToMarkdown\ElementInterface; class EmphasisConverter implements ConverterInterface, ConfigurationAwareInterface { /** * @var Configuration */ protected $config; /** * @param Configuration $config */ public function setConfig(Configuration $config) { $this->config = $config; } /** * @param ElementInterface $element * * @return string */ public function convert(ElementInterface $element) { $tag = $element->getTagName(); $value = $element->getValue(); if ($tag === 'i' || $tag === 'em') { $style = $this->config->getOption('italic_style'); } else { $style = $this->config->getOption('bold_style'); } $prefix = ltrim($value) !== $value ? ' ' : ''; $suffix = rtrim($value) !== $value ? ' ' : ''; return $prefix . $style . trim($value) . $style . $suffix; } /** * @return string[] */ public function getSupportedTags() { return array('em', 'i', 'strong', 'b'); } }
<?php namespace League\HTMLToMarkdown\Converter; use League\HTMLToMarkdown\Configuration; use League\HTMLToMarkdown\ConfigurationAwareInterface; use League\HTMLToMarkdown\ElementInterface; class EmphasisConverter implements ConverterInterface, ConfigurationAwareInterface { /** * @var Configuration */ protected $config; /** * @param Configuration $config */ public function setConfig(Configuration $config) { $this->config = $config; } /** * @param ElementInterface $element * * @return string */ public function convert(ElementInterface $element) { $tag = $element->getTagName(); $value = $element->getValue(); if ($tag === 'i' || $tag === 'em') { $style = $this->config->getOption('italic_style'); } else { $style = $this->config->getOption('bold_style'); } return $style . $value . $style; } /** * @return string[] */ public function getSupportedTags() { return array('em', 'i', 'strong', 'b'); } }
Improve joda objects model in rest
package org.jgrades.rest; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.joda.time.LocalTime; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class RestDocsConfig { @Bean public Docket jGradesRestApi() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build() .pathMapping("/") .directModelSubstitute(DateTime.class, Long.class) .directModelSubstitute(LocalDate.class, String.class) .directModelSubstitute(LocalTime.class, String.class) .enableUrlTemplating(true); } }
package org.jgrades.rest; import org.joda.time.DateTime; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class RestDocsConfig { @Bean public Docket jGradesRestApi() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build() .pathMapping("/") .directModelSubstitute(DateTime.class, Long.class) .enableUrlTemplating(true); } }
Fix tests on Windows with autocrlf on.
'use strict'; var grunt = require('grunt'); function readFile(file) { var contents = grunt.file.read(file); if (process.platform === 'win32') { contents = contents.replace(/\r\n/g, '\n'); } return contents; } exports.accessibilityTests = { matchReports: function(test) { var actual; var expected; test.expect(2); actual = readFile('reports/txt/test.txt'); expected = readFile('test/expected/txt/test.txt'); test.equal(actual, expected, 'Should produce a default report without DOM element for a test file'); actual = readFile('reports/json/test.json'); expected = readFile('test/expected/json/test.json'); test.equal(actual, expected, 'Should produce a default report without DOM element for a test file'); // actual = readFile('reports/csv/test.csv'); // expected = readFile('test/expected/csv/test.csv'); // test.equal(actual, expected, 'Should produce a default report without DOM element for a test file'); test.done(); } };
'use strict'; var grunt = require('grunt'); exports.accessibilityTests = { matchReports: function(test) { var actual; var expected; test.expect(2); actual = grunt.file.read('reports/txt/test.txt'); expected = grunt.file.read('test/expected/txt/test.txt'); test.equal(actual, expected, 'Should produce a default report without DOM element for a test file'); actual = grunt.file.read('reports/json/test.json'); expected = grunt.file.read('test/expected/json/test.json'); test.equal(actual, expected, 'Should produce a default report without DOM element for a test file'); // actual = grunt.file.read('reports/csv/test.csv'); // expected = grunt.file.read('test/expected/csv/test.csv'); // test.equal(actual, expected, 'Should produce a default report without DOM element for a test file'); test.done(); } };
Add PATH to the environment
<?php App::uses('AssetFilter', 'AssetCompress.Lib'); /** * Pre-processing filter that adds support for SCSS files. * * Requires ruby and sass rubygem to be installed * * @see http://sass-lang.com/ */ class ScssFilter extends AssetFilter { protected $_settings = array( 'ext' => '.scss', 'sass' => '/usr/bin/sass', 'path' => '/usr/bin', ); /** * Runs SCSS compiler against any files that match the configured extension. * * @param string $filename The name of the input file. * @param string $input The content of the file. * @return string */ public function input($filename, $input) { if (substr($filename, strlen($this->_settings['ext']) * -1) !== $this->_settings['ext']) { return $input; } $bin = $this->_settings['sass'] . ' ' . $filename; $return = $this->_runCmd($bin, '', array('PATH' => $this->_settings['path'])); return $return; } }
<?php App::uses('AssetFilter', 'AssetCompress.Lib'); /** * Pre-processing filter that adds support for SCSS files. * * Requires ruby and sass rubygem to be installed * * @see http://sass-lang.com/ */ class ScssFilter extends AssetFilter { protected $_settings = array( 'ext' => '.scss', 'sass' => '/usr/bin/sass' ); /** * Runs SCSS compiler against any files that match the configured extension. * * @param string $filename The name of the input file. * @param string $input The content of the file. * @return string */ public function input($filename, $input) { if (substr($filename, strlen($this->_settings['ext']) * -1) !== $this->_settings['ext']) { return $input; } $bin = $this->_settings['sass'] . ' ' . $filename; $return = $this->_runCmd($bin, ''); return $return; } }
Switch to name field for unique check and value
Template.addProject.created = function () { // Get reference to template instance let instance = this; // Subscribe to all tags, for tag auto-complete field instance.subscribe("allTags"); }; Template.addProject.rendered = function() { // Get reference to template instance let instance = this; instance.autorun(function () { if (instance.subscriptionsReady()) { // Get all existing tags let tagOptions = Tags.find().fetch(); $('#tags').selectize({ delimiter: ',', persist: false, valueField: 'name', labelField: 'name', searchField: 'name', highlight: true, maxOptions: 5, options: tagOptions, create:true, onItemAdd(value){ // Insert tag into Tags collection if it doesn't exist if(!Tags.findOne({"name":value})){ Tags.insert({"name":value}); } } }); } }); } Template.addProject.helpers({ existingTags: function () { // Get all existing tags let tags = Tags.find().fetch(); return tags; } });
Template.addProject.created = function () { // Get reference to template instance let instance = this; // Subscribe to all tags, for tag auto-complete field instance.subscribe("allTags"); }; Template.addProject.rendered = function() { // Get reference to template instance let instance = this; instance.autorun(function () { if (instance.subscriptionsReady()) { // Get all existing tags let tagOptions = Tags.find().fetch(); $('#tags').selectize({ delimiter: ',', persist: false, valueField: '_id', labelField: 'name', searchField: 'name', highlight: true, maxOptions: 5, options: tagOptions, create:true, onItemAdd(value){ if(!Tags.findOne({_id:value})){ Tags.insert({"name":value}); } } }); } }); } Template.addProject.helpers({ existingTags: function () { // Get all existing tags let tags = Tags.find().fetch(); return tags; } });
Remove debug info in product history
import { inject, NewInstance } from 'aurelia-framework'; import { ProjectApi } from './api'; import { DialogService } from 'aurelia-dialog'; import { HistoryDialog } from './history-dialog'; @inject(ProjectApi, DialogService) export class ProductHistory { constructor(projectApi, dialogService) { this.api = projectApi; this.dialog = dialogService; } activate(params, routeMap) { this.api.projectDetail(params.id).then(data => { this.project = data; this.getProducts(); }); } getProducts() { this.api.productsForProject(this.project.id, {with_data: 'True'}).then(data => { this.products = data; this.isLoading = false; }); } showData(data) { this.dialog.open({viewModel: HistoryDialog, model: data}).whenClosed(response => { if (!response.wasCancelled) { } }); } }
import { inject, NewInstance } from 'aurelia-framework'; import { ProjectApi } from './api'; import { DialogService } from 'aurelia-dialog'; import { HistoryDialog } from './history-dialog'; @inject(ProjectApi, DialogService) export class ProductHistory { constructor(projectApi, dialogService) { this.api = projectApi; this.dialog = dialogService; } activate(params, routeMap) { this.api.projectDetail(params.id).then(data => { this.project = data; this.getProducts(); }); } getProducts() { this.api.productsForProject(this.project.id, {with_data: 'True'}).then(data => { this.products = data; this.isLoading = false; }); } showData(data) { console.log(data); this.dialog.open({viewModel: HistoryDialog, model: data}).whenClosed(response => { if (!response.wasCancelled) { } }); } }
Remove loading directive after request fails
;(function(window) { 'use strict'; var angular = window.angular; var ImageLoader = window.ImageLoader; var ismobile = window.navigator.userAgent.match(/(iPad)|(iPhone)|(iPod)|(android)|(webOS)/i); angular .module('tuchong-daily') .service('imageLoader', [ '$ionicLoading', '$timeout', imageLoader ]); function imageLoader($ionicLoading, $timeout) { this.load = load; function load(uri, callback) { $ionicLoading.show(); var img = new BlobImage(ismobile ? uri : proxy(uri)); img.element.onload = success; img.element.onerror = fail; function success() { $ionicLoading.hide(); callback(img.blobURL); img = null; } function fail() { $ionicLoading.show({ template: '图片加载失败,请稍后再试试...' }); img = null; $timeout($ionicLoading.hide, 1000); } function proxy(realuri) { return realuri.replace( 'http://photos.tuchong.com', 'http://localhost:8100/photos' ); } } } })(this);
;(function(window) { 'use strict'; var angular = window.angular; var ImageLoader = window.ImageLoader; var ismobile = window.navigator.userAgent.match(/(iPad)|(iPhone)|(iPod)|(android)|(webOS)/i); angular .module('tuchong-daily') .service('imageLoader', [ '$ionicLoading', '$timeout', imageLoader ]); function imageLoader($ionicLoading, $timeout) { this.load = load; function load(uri, callback) { $ionicLoading.show(); var img = new BlobImage(ismobile ? uri : proxy(uri)); img.element.onload = success; img.element.onerror = fail; function success() { $ionicLoading.hide(); callback(img.blobURL); img = null; } function fail() { $ionicLoading.show({ template: '图片加载失败,请稍后再试试...' }); img = null; } function proxy(realuri) { return realuri.replace( 'http://photos.tuchong.com', 'http://localhost:8100/photos' ); } } } })(this);
Add support for Bower to Webpack
var webpack = require("webpack"); var path = require("path") const PROJECT_ROOT = path.resolve(__dirname) module.exports = { entry: [ "./bower_components/underscore/underscore.js", "./scripts/dash-spinner/bar.js", "./scripts/dash-spinner/foo.js", "./scripts/dash-spinner/foo.coffee" ], output: { path: "./dist", filename: "new-spinner.js" }, module: { loaders:[ { include: [ path.join(PROJECT_ROOT, "scripts"), path.join(PROJECT_ROOT, "spec") ], loader: "babel-loader", test: /\.js$/ }, { include: [ path.join(PROJECT_ROOT, "scripts"), path.join(PROJECT_ROOT, "spec") ], loader: "babel!coffee", test: /\.coffee$/ } ] }, plugins: [ new webpack.ResolverPlugin( new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin(".bower.json", ["main"]) ) ], resolve: { alias: { "dash_spinner": path.join(PROJECT_ROOT, "scripts", "dash-spinner") } } }
var path = require("path") const PROJECT_ROOT = path.resolve(__dirname) module.exports = { entry: [ "./scripts/dash-spinner/bar.js", "./scripts/dash-spinner/foo.js", "./scripts/dash-spinner/foo.coffee" ], output: { path: "./dist", filename: "new-spinner.js" }, module: { loaders:[ { include: [ path.join(PROJECT_ROOT, "scripts"), path.join(PROJECT_ROOT, "spec") ], loader: "babel-loader", test: /\.js$/ }, { include: [ path.join(PROJECT_ROOT, "scripts"), path.join(PROJECT_ROOT, "spec") ], loader: "babel!coffee", test: /\.coffee$/ } ] }, resolve: { alias: { "dash_spinner": path.join(PROJECT_ROOT, "scripts", "dash-spinner") } } }
Add AdminLTE styles mapping to public folder
<?php namespace RenderbitTechnologies\AdminLTE; class ServiceProvider extends \Illuminate\Support\ServiceProvider { const CONFIG_PATH = __DIR__ . '/../config/adminlte.php'; public function boot() { $this->publishes([ self::CONFIG_PATH => config_path('adminlte.php'), ], 'config'); } public function register() { $this->mergeConfigFrom( self::CONFIG_PATH, 'adminlte' ); $this->publishes([ 'vendor/almasaeed2010/adminlte/dist' => public_path('adminlte'), 'vendor/almasaeed2010/adminlte/bower_components' => public_path('adminlte/plugins'), ]); $this->app->bind('adminlte', function () { return new AdminLTE(); }); } }
<?php namespace RenderbitTechnologies\AdminLTE; class ServiceProvider extends \Illuminate\Support\ServiceProvider { const CONFIG_PATH = __DIR__ . '/../config/adminlte.php'; public function boot() { $this->publishes([ self::CONFIG_PATH => config_path('adminlte.php'), ], 'config'); } public function register() { $this->mergeConfigFrom( self::CONFIG_PATH, 'adminlte' ); $this->app->bind('adminlte', function () { return new AdminLTE(); }); } }
Update CertificateManager per 2021-03-11 changes
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. # # *** Do not modify - this file is autogenerated *** # Resource specification version: 31.1.0 from . import AWSObject from . import AWSProperty from troposphere import Tags from .validators import integer class ExpiryEventsConfiguration(AWSProperty): props = { 'DaysBeforeExpiry': (integer, False), } class Account(AWSObject): resource_type = "AWS::CertificateManager::Account" props = { 'ExpiryEventsConfiguration': (ExpiryEventsConfiguration, True), } class DomainValidationOption(AWSProperty): props = { 'DomainName': (basestring, True), 'HostedZoneId': (basestring, False), 'ValidationDomain': (basestring, False), } class Certificate(AWSObject): resource_type = "AWS::CertificateManager::Certificate" props = { 'CertificateAuthorityArn': (basestring, False), 'CertificateTransparencyLoggingPreference': (basestring, False), 'DomainName': (basestring, True), 'DomainValidationOptions': ([DomainValidationOption], False), 'SubjectAlternativeNames': ([basestring], False), 'Tags': ((Tags, list), False), 'ValidationMethod': (basestring, False), }
# Copyright (c) 2012-2019, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. # # *** Do not modify - this file is autogenerated *** # Resource specification version: 15.1.0 from . import AWSObject from . import AWSProperty from troposphere import Tags class DomainValidationOption(AWSProperty): props = { 'DomainName': (basestring, True), 'HostedZoneId': (basestring, False), 'ValidationDomain': (basestring, False), } class Certificate(AWSObject): resource_type = "AWS::CertificateManager::Certificate" props = { 'CertificateAuthorityArn': (basestring, False), 'CertificateTransparencyLoggingPreference': (basestring, False), 'DomainName': (basestring, True), 'DomainValidationOptions': ([DomainValidationOption], False), 'SubjectAlternativeNames': ([basestring], False), 'Tags': ((Tags, list), False), 'ValidationMethod': (basestring, False), }
EX: Add seed to example and use stationary coefs
""" Autoregressive Moving Average (ARMA) Model """ import numpy as np import statsmodels.api as sm # Generate some data from an ARMA process from statsmodels.tsa.arima_process import arma_generate_sample np.random.seed(12345) arparams = np.array([.75, -.25]) maparams = np.array([.65, .35]) # The conventions of the arma_generate function require that we specify a # 1 for the zero-lag of the AR and MA parameters and that the AR parameters # be negated. arparams = np.r_[1, -arparams] maparam = np.r_[1, maparams] nobs = 250 y = arma_generate_sample(arparams, maparams, nobs) # Now, optionally, we can add some dates information. For this example, # we'll use a pandas time series. import pandas dates = sm.tsa.datetools.dates_from_range('1980m1', length=nobs) y = pandas.TimeSeries(y, index=dates) arma_mod = sm.tsa.ARMA(y, freq='M') arma_res = arma_mod.fit(order=(2,2), trend='nc', disp=-1)
""" Autoregressive Moving Average (ARMA) Model """ import numpy as np import statsmodels.api as sm # Generate some data from an ARMA process from statsmodels.tsa.arima_process import arma_generate_sample arparams = np.array([.75, -.25]) maparams = np.array([.65, .35]) # The conventions of the arma_generate function require that we specify a # 1 for the zero-lag of the AR and MA parameters and that the AR parameters # be negated. arparams = np.r_[1, -arparams] maparam = np.r_[1, maparams] nobs = 250 y = arma_generate_sample(arparams, maparams, nobs) # Now, optionally, we can add some dates information. For this example, # we'll use a pandas time series. import pandas dates = sm.tsa.datetools.dates_from_range('1980m1', length=nobs) y = pandas.TimeSeries(y, index=dates) arma_mod = sm.tsa.ARMA(y, freq='M') arma_res = arma_mod.fit(order=(2,2), trend='nc', disp=-1)
Add proper styles for single-level (un)ordered lists to standardOptions
var docxReader = require("./docx-reader"); var DocumentConverter = require("./document-to-html").DocumentConverter; var htmlPaths = require("./html-paths"); var documentMatchers = require("./document-matchers"); var style = require("./style-reader").readStyle; exports.Converter = Converter; exports.read = read; exports.convertDocumentToHtml = convertDocumentToHtml; exports.htmlPaths = htmlPaths; exports.standardOptions = { styleMap: [ style("p.Heading1 => h1"), style("p.Heading2 => h2"), style("p.Heading3 => h3"), style("p.Heading4 => h4"), style("p:unordered-list(1) => ul > li:fresh"), style("p:ordered-list(1) => ol > li:fresh") ] }; function Converter(options) { this._options = options; } Converter.prototype.convertToHtml = function(inputOptions) { var options = this._options; return read(inputOptions) .then(function(documentResult) { return convertDocumentToHtml(documentResult, options); }); } function read(inputOptions) { return docxReader.read(inputOptions); } function convertDocumentToHtml(documentResult, options) { var documentConverter = new DocumentConverter(options); return documentResult.flatMapThen(function(document) { return documentConverter.convertToHtml(document); }); }
var docxReader = require("./docx-reader"); var DocumentConverter = require("./document-to-html").DocumentConverter; var htmlPaths = require("./html-paths"); var documentMatchers = require("./document-matchers"); var style = require("./style-reader").readStyle; exports.Converter = Converter; exports.read = read; exports.convertDocumentToHtml = convertDocumentToHtml; exports.htmlPaths = htmlPaths; exports.standardOptions = { styleMap: [ style("p.Heading1 => h1"), style("p.Heading2 => h2"), style("p.Heading3 => h3"), style("p.Heading4 => h4"), style("p.ListParagraph => ul > li:fresh") ] }; function Converter(options) { this._options = options; } Converter.prototype.convertToHtml = function(inputOptions) { var options = this._options; return read(inputOptions) .then(function(documentResult) { return convertDocumentToHtml(documentResult, options); }); } function read(inputOptions) { return docxReader.read(inputOptions); } function convertDocumentToHtml(documentResult, options) { var documentConverter = new DocumentConverter(options); return documentResult.flatMapThen(function(document) { return documentConverter.convertToHtml(document); }); }
Make CACHED_TRANSLATIONS global, fix get_value typo
import gettext from bot.action.core.action import IntermediateAction LOCALE_DIR = "locales" TRANSLATION_DOMAIN = "telegram-bot" DEFAULT_LANGUAGE = "en" CACHED_TRANSLATIONS = {} class InternationalizationAction(IntermediateAction): def __init__(self): super().__init__() self.default_translation = self.__get_translation(DEFAULT_LANGUAGE) def process(self, event): lang = event.state.get_for("settings").get_value("language", DEFAULT_LANGUAGE) translation = self.__get_translation(lang) translation.install() event._ = translation.gettext self._continue(event) self.default_translation.install() @staticmethod def __get_translation(language): if language in CACHED_TRANSLATIONS: translation = CACHED_TRANSLATIONS[language] else: translation = gettext.translation(TRANSLATION_DOMAIN, LOCALE_DIR, languages=[language], fallback=True) CACHED_TRANSLATIONS[language] = translation return translation
import gettext from bot.action.core.action import IntermediateAction LOCALE_DIR = "locales" TRANSLATION_DOMAIN = "telegram-bot" DEFAULT_LANGUAGE = "en" class InternationalizationAction(IntermediateAction): def __init__(self): super().__init__() self.cached_translations = {} self.default_translation = self.__get_translation(DEFAULT_LANGUAGE) def process(self, event): lang = event.state.get_for("settings").get("language", DEFAULT_LANGUAGE) translation = self.__get_translation(lang) translation.install() event._ = translation.gettext self._continue(event) self.default_translation.install() def __get_translation(self, language): if language in self.cached_translations: return self.cached_translations[language] translation = gettext.translation(TRANSLATION_DOMAIN, LOCALE_DIR, languages=[language], fallback=True) self.cached_translations[language] = translation return translation
Handle Android RN 0.47 breaking change https://github.com/facebook/react-native/commit/ce6fb337a146e6f261f2afb564aa19363774a7a8
package com.novadart.reactnativenfc; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ReactNativeNFCPackage implements ReactPackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { List<NativeModule> modules = new ArrayList<>(1); modules.add(new ReactNativeNFCModule(reactContext)); return modules; } // Deprecated RN 0.47 // @Override public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Collections.emptyList(); } }
package com.novadart.reactnativenfc; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ReactNativeNFCPackage implements ReactPackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { List<NativeModule> modules = new ArrayList<>(1); modules.add(new ReactNativeNFCModule(reactContext)); return modules; } @Override public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Collections.emptyList(); } }
Fix column name in query
<? require 'scat.php'; head("transactions"); $type= $_REQUEST['type']; if ($type) { $criteria= "type = '".$db->real_escape_string($type)."'"; } else { $criteria= '1=1'; } /* $q= $_GET['q']; ?> <form method="get" action="<?=$_SERVER['PHP_SELF']?>"> <input id="focus" type="text" name="q" value="<?=htmlspecialchars($q)?>"> <input type="submit" value="Search"> </form> <br> <? */ $q= "SELECT txn.type AS meta, CONCAT(txn.id, '|', type, '|', txn.number) AS Number\$txn, txn.created AS Created\$date, SUM(ordered) AS Ordered, SUM(shipped) AS Shipped, SUM(allocated) AS Allocated FROM txn LEFT JOIN txn_line ON (txn.id = txn_line.txn) WHERE $criteria GROUP BY txn.id ORDER BY created DESC LIMIT 200"; dump_table($db->query($q)); dump_query($q);
<? require 'scat.php'; head("transactions"); $type= $_REQUEST['type']; if ($type) { $criteria= "type = '".$db->real_escape_string($type)."'"; } else { $criteria= '1=1'; } /* $q= $_GET['q']; ?> <form method="get" action="<?=$_SERVER['PHP_SELF']?>"> <input id="focus" type="text" name="q" value="<?=htmlspecialchars($q)?>"> <input type="submit" value="Search"> </form> <br> <? */ $q= "SELECT txn.type AS meta, CONCAT(id, '|', type, '|', txn.number) AS Number\$txn, txn.created AS Created\$date, SUM(ordered) AS Ordered, SUM(shipped) AS Shipped, SUM(allocated) AS Allocated FROM txn LEFT JOIN txn_line ON (txn.id = txn_line.txn) WHERE $criteria GROUP BY txn.id ORDER BY created DESC LIMIT 200"; dump_table($db->query($q)); dump_query($q);
Purge should always be attempted Since the original is very volatile (in memcache), its absence shouldn't prevent the thumbnails from being purged. Furthermore, knowing whether the item was there beforehand isn't very useful. Change-Id: I014df0bce00983031b9dec9d48126c25b1688a77
# -*- coding: utf-8 -*- # Copyright (c) 2015, thumbor-community, Wikimedia Foundation # Use of this source code is governed by the MIT license that can be # found in the LICENSE file. import urllib from tornado import gen from thumbor.handlers.imaging import ImagingHandler class UrlPurgerHandler(ImagingHandler): @classmethod def regex(cls): ''' :return: The regex used for routing. :rtype: string ''' return r'/purge/?(?P<image>.+)?' @gen.coroutine def get(self, **kw): imageurl = urllib.quote(kw['image'].encode('utf8')) self.context.modules.storage.remove(imageurl) self.context.modules.result_storage.remove(imageurl) self.set_status(204) @gen.coroutine def execute_image_operations(self): pass
# -*- coding: utf-8 -*- # Copyright (c) 2015, thumbor-community, Wikimedia Foundation # Use of this source code is governed by the MIT license that can be # found in the LICENSE file. import urllib from tornado import gen from thumbor.handlers.imaging import ImagingHandler class UrlPurgerHandler(ImagingHandler): @classmethod def regex(cls): ''' :return: The regex used for routing. :rtype: string ''' return r'/purge/?(?P<image>.+)?' @gen.coroutine def get(self, **kw): imageurl = urllib.quote(kw['image'].encode('utf8')) exists = yield gen.maybe_future( self.context.modules.storage.exists(imageurl) ) if exists: self.context.modules.storage.remove(imageurl) self.context.modules.result_storage.remove(imageurl) self.set_status(204) else: self._error(404, 'Image not found at the given URL') @gen.coroutine def execute_image_operations(self): pass
Declare explicitly supported python versions
#!/usr/bin/env python import os from setuptools import setup ROOT_DIR = os.path.dirname(__file__) SOURCE_DIR = os.path.join(ROOT_DIR) test_requirements = [] with open('./requirements.txt') as requirements_txt: requirements = [line for line in requirements_txt] setup( name="docker-py", version='0.2.3', description="Python client for Docker.", packages=['docker', 'docker.auth', 'docker.unixconn', 'docker.utils'], install_requires=requirements + test_requirements, zip_safe=False, test_suite='tests', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Other Environment', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Topic :: Utilities', 'License :: OSI Approved :: Apache Software License', ], )
#!/usr/bin/env python import os from setuptools import setup ROOT_DIR = os.path.dirname(__file__) SOURCE_DIR = os.path.join(ROOT_DIR) test_requirements = [] with open('./requirements.txt') as requirements_txt: requirements = [line for line in requirements_txt] setup( name="docker-py", version='0.2.3', description="Python client for Docker.", packages=['docker', 'docker.auth', 'docker.unixconn', 'docker.utils'], install_requires=requirements + test_requirements, zip_safe=False, test_suite='tests', classifiers=['Development Status :: 4 - Beta', 'Environment :: Other Environment', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities', 'License :: OSI Approved :: Apache Software License' ], )
Return 4 projects for homepage
from bluebottle.quotes.models import Quote from bluebottle.slides.models import Slide from bluebottle.statistics.models import Statistic from bluebottle.utils.model_dispatcher import get_project_model PROJECT_MODEL = get_project_model() class HomePage(object): """ Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object """ def get(self, language): self.id = language self.quotes = Quote.objects.published().filter(language=language) self.slides = Slide.objects.published().filter(language=language) self.statistics = Statistic.objects.filter(active=True).all() projects = PROJECT_MODEL.objects.filter(is_campaign=True, status__viewable=True) if language == 'en': projects = projects.filter(language__code=language) projects = projects.order_by('?') if len(projects) > 4: self.projects = projects[0:4] elif len(projects) > 0: self.projects = projects[0:len(projects)] else: self.projects = None return self
from bluebottle.quotes.models import Quote from bluebottle.slides.models import Slide from bluebottle.statistics.models import Statistic from bluebottle.utils.model_dispatcher import get_project_model PROJECT_MODEL = get_project_model() class HomePage(object): """ Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object """ def get(self, language): self.id = language self.quotes = Quote.objects.published().filter(language=language) self.slides = Slide.objects.published().filter(language=language) self.statistics = Statistic.objects.filter(active=True).all() projects = PROJECT_MODEL.objects.filter(is_campaign=True, status__viewable=True) if language == 'en': projects = projects.filter(language__code=language) projects = projects.order_by('?') if len(projects) > 3: self.projects = projects[0:3] elif len(projects) > 0: self.projects = projects[0:len(projects)] else: self.projects = None return self
Remove commented-out debug code :-(
import json import unittest from pathlib import Path from inselect.lib.document import InselectDocument from inselect.lib.segment import segment_document TESTDATA = Path(__file__).parent.parent / 'test_data' class TestSegment(unittest.TestCase): def test_segment_document(self): doc = InselectDocument.load(TESTDATA / 'test_segment.inselect') self.assertEqual(5, len(doc.items)) # Compare the rects in pixels expected = doc.scanned.from_normalised([i['rect'] for i in doc.items]) doc.set_items([]) self.assertEqual(0, len(doc.items)) doc, display_image = segment_document(doc) actual = doc.scanned.from_normalised([i['rect'] for i in doc.items]) self.assertEqual(list(expected), list(actual)) if __name__ == '__main__': unittest.main()
import json import unittest from pathlib import Path from inselect.lib.document import InselectDocument from inselect.lib.segment import segment_document TESTDATA = Path(__file__).parent.parent / 'test_data' class TestSegment(unittest.TestCase): def test_segment_document(self): doc = InselectDocument.load(TESTDATA / 'test_segment.inselect') self.assertEqual(5, len(doc.items)) # Compare the rects in pixels expected = doc.scanned.from_normalised([i['rect'] for i in doc.items]) # from pprint import pprint # pprint([i['rect'] for i in doc.items]) doc.set_items([]) self.assertEqual(0, len(doc.items)) doc, display_image = segment_document(doc) actual = doc.scanned.from_normalised([i['rect'] for i in doc.items]) # pprint([i['rect'] for i in doc.items]) self.assertEqual(list(expected), list(actual)) if __name__ == '__main__': unittest.main()
CC-5781: Upgrade script for new storage quota implementation
<?php // Define path to application directory defined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../../install_minimal/../airtime_mvc/application')); // Ensure library/ is on include_path set_include_path(implode(PATH_SEPARATOR, array( get_include_path(), realpath(APPLICATION_PATH . '/../library') ))); //Propel classes. set_include_path(APPLICATION_PATH . '/models' . PATH_SEPARATOR . get_include_path()); require_once 'CcMusicDirsQuery.php'; class StorageQuotaUpgrade { public static function startUpgrade() { echo "* Updating storage usage for new quota tracking".PHP_EOL; self::setStorageUsage(); } private static function setStorageUsage() { $musicDir = CcMusicDirsQuery::create() ->filterByDbType('stor') ->filterByDbExists(true) ->findOne(); $storPath = $musicDir->getDbDirectory(); $freeSpace = disk_free_space($storPath); $totalSpace = disk_total_space($storPath); Application_Model_Preference::setDiskUsage($totalSpace - $freeSpace); } }
<?php // Define path to application directory defined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../../install_minimal/../airtime_mvc/application')); // Ensure library/ is on include_path set_include_path(implode(PATH_SEPARATOR, array( get_include_path(), realpath(APPLICATION_PATH . '/../library') ))); set_include_path(implode(PATH_SEPARATOR, array( get_include_path(), realpath(APPLICATION_PATH . '/../library/propel/runtime/lib') ))); //Propel classes. set_include_path(APPLICATION_PATH . '/models' . PATH_SEPARATOR . get_include_path()); class StorageQuotaUpgrade { public static function startUpgrade() { echo "* Updating storage usage for new quota tracking".PHP_EOL; self::setStorageUsage(); } private static function setStorageUsage() { $musicDir = CcMusicDirsQuery::create() ->filterByDbType('stor') ->filterByDbExists(true) ->findOne(); $storPath = $musicDir->getDbDirectory(); $freeSpace = disk_free_space($storPath); $totalSpace = disk_total_space($storPath); Application_Model_Preference::setDiskUsage($totalSpace - $freeSpace); } }
Change how random is done for tableflipping Signed-off-by: Adam Jimerson <0a1ce5db568b585e24ec79212f7ab30cdb820af8@gmail.com>
// Copyright 2014 Chadev. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "math/rand" "time" "github.com/danryan/hal" ) var tableFlipped bool var tableFlipHandler = hal.Hear(listenName+` tableflip`, func(res *hal.Response) error { rand.Seed(time.Now().UTC().UnixNano()) e := []string{ "(ノಠ益ಠ)ノ彡┻━┻", `(╯°□°)╯︵ ┻━┻`, `the table flipped you! ノ┬─┬ノ ︵ ( \o°o)\`, "┻━┻ ︵ヽ(`Д´)ノ︵ ┻━┻", } return res.Send(e[rand.Intn(len(e))]) })
// Copyright 2014 Chadev. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "math/rand" "github.com/danryan/hal" ) var tableFlipHandler = hal.Hear(listenName+` tableflip`, func(res *hal.Response) error { num := rand.Int() switch { case num%15 == 0: return res.Send(`the table flipped you! ノ┬─┬ノ ︵ ( \o°o)\`) case num%3 == 0: return res.Send("(ノಠ益ಠ)ノ彡┻━┻") case num%5 == 0: return res.Send("you set the table down ┬─┬ノ( º _ ºノ)") default: return res.Send(`(╯°□°)╯︵ ┻━┻`) } })
Use rmtree and mkdir function instead of rm -rf and mkdir to make the code more portable.
/* * Licensed to Cloudkick, Inc ('Cloudkick') under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * Cloudkick licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var path = require('path'); var fs = require('fs'); var sprintf = require('extern/sprintf').sprintf; var config = require('util/config'); var fsUtil = require('util/fs'); var setUp = function(callback) { var testFolderPath = path.join(__dirname, '.tests'); config.configFiles = [ path.join(__dirname, 'test.conf') ]; fsUtil.rmtree(testFolderPath, function(err) { fs.mkdir(testFolderPath, 0775, function(err) { config.setupAgent(callback); }); }); }; exports.setUp = setUp;
/* * Licensed to Cloudkick, Inc ('Cloudkick') under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * Cloudkick licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var path = require('path'); var exec = require('child_process').exec; var sprintf = require('extern/sprintf').sprintf; var config = require('util/config'); var setUp = function(callback) { var testFolderPath = path.join(__dirname, '.tests'); config.configFiles = [ path.join(__dirname, 'test.conf') ]; exec(sprintf('rm -rf "%s"', testFolderPath), function(err) { exec(sprintf('mkdir "%s"', testFolderPath), function(err) { config.setupAgent(callback); }); }); }; exports.setUp = setUp;
Add test fot shape of result of accuracy function
import unittest import numpy import six import chainer from chainer import cuda from chainer import gradient_check from chainer.testing import attr if cuda.available: cuda.init() class TestAccuracy(unittest.TestCase): def setUp(self): self.x = numpy.random.uniform(-1, 1, (10, 3)).astype(numpy.float32) self.t = numpy.random.randint(3, size=(10,)).astype(numpy.int32) def check_forward(self, x_data, t_data): x = chainer.Variable(x_data) t = chainer.Variable(t_data) y = chainer.functions.accuracy(x, t) self.assertEqual((), y.data.shape) count = 0 for i in six.moves.range(self.t.size): pred = self.x[i].argmax() if pred == self.t[i]: count += 1 expected = float(count) / self.t.size gradient_check.assert_allclose(expected, cuda.to_cpu(y.data)) def test_forward_cpu(self): self.check_forward(self.x, self.t) @attr.gpu def test_forward_gpu(self): self.check_forward(cuda.to_gpu(self.x), cuda.to_gpu(self.t))
import unittest import numpy import six import chainer from chainer import cuda from chainer import gradient_check from chainer.testing import attr if cuda.available: cuda.init() class TestAccuracy(unittest.TestCase): def setUp(self): self.x = numpy.random.uniform(-1, 1, (10, 3)).astype(numpy.float32) self.t = numpy.random.randint(3, size=(10,)).astype(numpy.int32) def check_forward(self, x_data, t_data): x = chainer.Variable(x_data) t = chainer.Variable(t_data) y = chainer.functions.accuracy(x, t) count = 0 for i in six.moves.range(self.t.size): pred = self.x[i].argmax() if pred == self.t[i]: count += 1 expected = float(count) / self.t.size gradient_check.assert_allclose(expected, cuda.to_cpu(y.data)) def test_forward_cpu(self): self.check_forward(self.x, self.t) @attr.gpu def test_forward_gpu(self): self.check_forward(cuda.to_gpu(self.x), cuda.to_gpu(self.t))
Configure missed files in deploy task
module.exports = function (grunt) { 'use strict'; grunt.loadNpmTasks('grunt-contrib-connect'); grunt.loadNpmTasks('grunt-gh-pages'); grunt.initConfig({ 'connect': { demo: { options: { open: { target: 'http://localhost:8000/' }, keepalive: true } } }, 'gh-pages': { src: [ 'index.html', 'bootstrap-rating.js', 'bootstrap-rating.css', 'bower_components/**/*' ] } }); grunt.registerTask('serve', ['connect']); grunt.registerTask('deploy', ['gh-pages']); };
module.exports = function (grunt) { 'use strict'; grunt.loadNpmTasks('grunt-contrib-connect'); grunt.loadNpmTasks('grunt-gh-pages'); grunt.initConfig({ 'connect': { demo: { options: { open: { target: 'http://localhost:8000/' }, keepalive: true } } }, 'gh-pages': { src: [ 'index.html', 'bower_components/**/*' ] } }); grunt.registerTask('serve', ['connect']); grunt.registerTask('deploy', ['gh-pages']); };
Fix bug in EventEmitter once method causing arguments to be lost.
'use strict'; /** * @constructor */ function EventEmitter() { this.eventHandlers = {}; } EventEmitter.prototype.emit = function(event) { if (!this.eventHandlers[event]) { return; } var argsOut = []; for (var i = 1; i < arguments.length; ++i) { argsOut.push(arguments[i]); } for (var j = 0; j < this.eventHandlers[event].length; ++j) { this.eventHandlers[event][j].apply(this, argsOut); } }; EventEmitter.prototype.addEventListener = function(event, handler) { if (!this.eventHandlers[event]) { this.eventHandlers[event] = []; } this.eventHandlers[event].push(handler); }; EventEmitter.prototype.on = EventEmitter.prototype.addEventListener; EventEmitter.prototype.removeEventListener = function(event, handler) { if (!this.eventHandlers[event]) { return false; } var handlerIdx = this.eventHandlers[event].indexOf(handler); if (handlerIdx !== -1) { this.eventHandlers[event].splice(handlerIdx, 1); return true; } return false; }; EventEmitter.prototype.once = function(event, handler) { var onceHandler = function() { this.removeEventListener(event, onceHandler); handler.apply(this, arguments); }.bind(this); this.addEventListener(event, onceHandler); };
'use strict'; /** * @constructor */ function EventEmitter() { this.eventHandlers = {}; } EventEmitter.prototype.emit = function(event) { if (!this.eventHandlers[event]) { return; } var argsOut = []; for (var i = 1; i < arguments.length; ++i) { argsOut.push(arguments[i]); } for (var j = 0; j < this.eventHandlers[event].length; ++j) { this.eventHandlers[event][j].apply(this, argsOut); } }; EventEmitter.prototype.addEventListener = function(event, handler) { if (!this.eventHandlers[event]) { this.eventHandlers[event] = []; } this.eventHandlers[event].push(handler); }; EventEmitter.prototype.on = EventEmitter.prototype.addEventListener; EventEmitter.prototype.removeEventListener = function(event, handler) { if (!this.eventHandlers[event]) { return false; } var handlerIdx = this.eventHandlers[event].indexOf(handler); if (handlerIdx !== -1) { this.eventHandlers[event].splice(handlerIdx, 1); return true; } return false; }; EventEmitter.prototype.once = function(event, handler) { var onceHandler = function() { this.removeEventListener(event, onceHandler); handler(); }.bind(this); this.addEventListener(event, onceHandler); };
Fix in creating session error message
define(['jquery', 'controllers/analystController', 'Ladda'], function ($, analystController, Ladda) { function sessionView() { $(function () { $('#generate').on('click', function (e) { e.preventDefault(); var la = Ladda.create(document.getElementById('generate')); la.start(); var result = analystController.generateSession('infoDiv', 'sessionID', 'passwordID', 'pubkeyID', 'privkeyID', 'link-id', 'session-title', 'session-description'); if (result == null) { la.stop(); } else { result.then(function () { la.stop(); $('#session-details').removeClass('hidden'); }); } }); }); } return sessionView; });
define(['jquery', 'controllers/analystController', 'Ladda'], function ($, analystController, Ladda) { function sessionView() { $(function () { $('#generate').on('click', function (e) { e.preventDefault(); var la = Ladda.create(document.getElementById('generate')); la.start(); analystController.generateSession('infoDiv', 'sessionID', 'passwordID', 'pubkeyID', 'privkeyID', 'link-id', 'session-title', 'session-description') .then(function () { la.stop(); $('#session-details').removeClass('hidden'); }); }); }); } return sessionView; });
Deal with empty names properly.
// @flow import React from 'react'; import PropTypes from 'prop-types'; import { red500 } from 'material-ui/styles/colors'; import { ListItem } from 'material-ui/List'; import Avatar from 'material-ui/Avatar'; class CastListItem extends React.Component { static propTypes = { role: PropTypes.string.isRequired, displayRole: PropTypes.bool.isRequired, person: PropTypes.object.isRequired, }; renderAvatar() { const { person } = this.props; const initial = (person.name[0] || '?').toUpperCase(); return ( <Avatar backgroundColor={red500}> {initial} </Avatar> ); }; render() { const { role, displayRole, person } = this.props; return ( <ListItem disabled={true} primaryText={person.name} secondaryText={displayRole ? role : null} leftAvatar={this.renderAvatar(person)} /> ); }; } export default CastListItem;
// @flow import React from 'react'; import PropTypes from 'prop-types'; import { red500 } from 'material-ui/styles/colors'; import { ListItem } from 'material-ui/List'; import Avatar from 'material-ui/Avatar'; class CastListItem extends React.Component { static propTypes = { role: PropTypes.string.isRequired, displayRole: PropTypes.bool.isRequired, person: PropTypes.object.isRequired, }; renderAvatar() { const { person } = this.props; const initial = person.name[0].toUpperCase(); return ( <Avatar backgroundColor={red500}> {initial} </Avatar> ); }; render() { const { role, displayRole, person } = this.props; return ( <ListItem disabled={true} primaryText={person.name} secondaryText={displayRole ? role : null} leftAvatar={this.renderAvatar(person)} /> ); }; } export default CastListItem;
Switch to JDK7 method for new line
package org.jenkinsci.plugins.radargun.utils; import java.util.ArrayList; import java.util.List; import org.jenkinsci.plugins.radargun.model.Node; import org.jenkinsci.plugins.radargun.model.NodeList; public class ParseUtils { /** * * Parse node list. Expected format is * <ul> * <li> Each line is one machine </li> * <li> The first line is master, others are slaves </li> * <li> The first sequence of the line is machine name or its IP address, eventually can continue with space and JVM options for process started on this machine </li> * <li> Additional JVM option are added to default JVM option, not overwrite them </li> * </ul> * */ public static NodeList parseNodeList(String nodeList) { String[] lines = nodeList.split(System.lineSeparator()); Node master = Node.parseNode(lines[0]); List<Node> slaves = new ArrayList<>(); for(int i = 1; i < lines.length; i++) { slaves.add(Node.parseNode(lines[i])); } return new NodeList(master, slaves); } }
package org.jenkinsci.plugins.radargun.utils; import java.util.ArrayList; import java.util.List; import org.jenkinsci.plugins.radargun.model.Node; import org.jenkinsci.plugins.radargun.model.NodeList; public class ParseUtils { private static final String EOL_REG_EXP = "\\r?\\n"; /** * * Parse node list. Expected format is * <ul> * <li> Each line is one machine </li> * <li> The first line is master, others are slaves </li> * <li> The first sequence of the line is machine name or its IP address, eventually can continue with space and JVM options for process started on this machine </li> * <li> Additional JVM option are added to default JVM option, not overwrite them </li> * </ul> * */ public static NodeList parseNodeList(String nodeList) { String[] lines = nodeList.split(EOL_REG_EXP); Node master = Node.parseNode(lines[0]); List<Node> slaves = new ArrayList<>(); for(int i = 1; i < lines.length; i++) { slaves.add(Node.parseNode(lines[i])); } return new NodeList(master, slaves); } }
Fix clearing temporary files in tests
<?php /** * @link https://github.com/zendframework/zend-modulemanager for the canonical source repository * @copyright Copyright (c) 2005-2019 Zend Technologies USA Inc. (https://www.zend.com) * @license https://github.com/zendframework/zend-modulemanager/blob/master/LICENSE.md New BSD License */ namespace ZendTest\ModuleManager; /** * Offer common setUp/tearDown methods for configure a common cache dir. */ trait SetUpCacheDirTrait { /** * @var string */ protected $tmpdir; /** * @var string */ protected $configCache; /** * @before */ protected function createTmpDir() { $this->tmpdir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'zend_module_cache_dir'; @mkdir($this->tmpdir); $this->configCache = $this->tmpdir . DIRECTORY_SEPARATOR . 'config.cache.php'; } /** * @after */ protected function removeTmpDir() { $file = glob($this->tmpdir . DIRECTORY_SEPARATOR . '*'); if (isset($file[0])) { // change this if there's ever > 1 file @unlink($file[0]); } @rmdir($this->tmpdir); } }
<?php /** * @link https://github.com/zendframework/zend-modulemanager for the canonical source repository * @copyright Copyright (c) 2005-2019 Zend Technologies USA Inc. (https://www.zend.com) * @license https://github.com/zendframework/zend-modulemanager/blob/master/LICENSE.md New BSD License */ namespace ZendTest\ModuleManager; /** * Offer common setUp/tearDown methods for configure a common cache dir. */ trait SetUpCacheDirTrait { /** * @var string */ protected $tmpdir; /** * @var string */ protected $configCache; /** * @before */ protected function createTmpDir() { $this->tmpdir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'zend_module_cache_dir'; @mkdir($this->tmpdir); $this->configCache = $this->tmpdir . DIRECTORY_SEPARATOR . 'config.cache.php'; } /** * @after */ protected function removeTmpDir() { $file = glob($this->tmpdir . DIRECTORY_SEPARATOR . '*'); @unlink($file[0]); // change this if there's ever > 1 file @rmdir($this->tmpdir); } }
Add optional initial_crc to calculate()
var sse4_crc32 = require("bindings")("sse4_crc32"); /** * Defines a progressive 32-bit CRC calculator * * @param input The input string for which the CRC is to be calculated * @param initial_crc The initial CRC passed in [optional] * * @constructor */ function CRC32(input, initial_crc) { this.crc32 = initial_crc || 0; if (input) { this.update(input); } } /** * Progressively calculates the 32-bit CRC * * @param input Additional input to calculate the CRC for */ CRC32.prototype.update = function (input) { this.crc32 = sse4_crc32.calculate(input, this.crc32); return this.crc32; }; /** * Returns the 32-bit CRC * * @returns {Integer} */ CRC32.prototype.crc = function () { return this.crc32; }; /** * Used to calculate 32-bit CRC for single instances of strings and/or buffers * * @param input The input string for which the CRC is to be calculated * @param initial_crc The initial CRC passed in [optional] * * @returns {Integer} */ function calculate(input, initial_crc) { return sse4_crc32.calculate(input, initial_crc || 0); } module.exports = { CRC32 : CRC32, calculate: calculate };
var sse4_crc32 = require("bindings")("sse4_crc32"); /** * Defines a progressive 32-bit CRC calculator * * @param input The input string for which the CRC is to be calculated * @param initial_crc The initial CRC passed in [optional] * * @constructor */ function CRC32(input, initial_crc) { this.crc32 = initial_crc || 0; if (input) { this.update(input); } } /** * Progressively calculates the 32-bit CRC * * @param input Additional input to calculate the CRC for */ CRC32.prototype.update = function (input) { this.crc32 = sse4_crc32.calculate(input, this.crc32); return this.crc32; }; /** * Returns the 32-bit CRC * * @returns {Integer} */ CRC32.prototype.crc = function () { return this.crc32; }; /** * Used to calculate 32-bit CRC for single instances of strings and/or buffers * * @param input The input string for which the CRC is to be calculated * * @returns {Integer} */ function calculate(input) { return sse4_crc32.calculate(input, 0); } module.exports = { CRC32 : CRC32, calculate: calculate };
server: Print GitHub authentications to log
import Express from 'express'; import Passport from 'passport'; import { Strategy as GitHubStrategy } from 'passport-github'; const router = Express.Router(); Passport.use(new GitHubStrategy({ clientID: process.env.GITHUB_CLIENT_ID, clientSecret: process.env.GITHUB_CLIENT_SECRET, callbackURL: process.env.GITHUB_CALLBACK_URL, }, async function(accessToken, refreshToken, profile, done) { // passport-patreon removes data we need from `profile`, so re-extract the raw data received const fullProfile = profile._json; console.log('GitHub login:', fullProfile); done(null, { name: fullProfile.name, avatar: fullProfile.avatar_url, github: { id: fullProfile.id, login: fullProfile.login, accessToken, refreshToken, }, }); } )); router.get('/', Passport.authenticate('github')); router.get( '/callback', Passport.authenticate('github', { successRedirect: '/premium', failureRedirect: '/premium', }), function (req, res) { res.setHeader('Content-Type', 'application/json; charset=utf-8'); res.send(JSON.stringify(req.user)); } ); export default router;
import Express from 'express'; import Passport from 'passport'; import request from 'request-promise-native'; import { Strategy as GitHubStrategy } from 'passport-github'; const router = Express.Router(); Passport.use(new GitHubStrategy({ clientID: process.env.GITHUB_CLIENT_ID, clientSecret: process.env.GITHUB_CLIENT_SECRET, callbackURL: process.env.GITHUB_CALLBACK_URL, }, async function(accessToken, refreshToken, profile, done) { // passport-patreon removes data we need from `profile`, so re-extract the raw data received const fullProfile = profile._json; done(null, { name: fullProfile.name, avatar: fullProfile.avatar_url, github: { id: fullProfile.id, login: fullProfile.login, accessToken, refreshToken, }, }); } )); router.get('/', Passport.authenticate('github')); router.get( '/callback', Passport.authenticate('github', { successRedirect: '/premium', failureRedirect: '/premium', }), function (req, res) { res.setHeader('Content-Type', 'application/json; charset=utf-8'); res.send(JSON.stringify(req.user)); } ); export default router;
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 = [] # remove unwanted databases for db in dbs: dbname = db.split('(') n = 0 for i in dbname: # i is only the name of the DataSource, db is DataSource ID! if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource': dblist.append(str(db).replace('"','')) n += 1 dblist.sort() for db in dblist: print "AdminConfig.list( db ): " try: AdminConfig.list ( db ) except: print "error on: " + db print "AdminConfig.showAttribute( db, 'name' ): " try: AdminConfig.showAttribute( db, 'name' ) except: print "error on: " + db
###### # 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 = [] # remove unwanted databases for db in dbs: dbname = db.split('(') n = 0 for i in dbname: # i is only the name of the DataSource, db is DataSource ID! if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource': dblist.append(str(db).replace('"','')) n += 1 dblist.sort() for db in dblist: print "AdminConfig.list( db ): " AdminConfig.list ( db ) print "AdminConfig.showAttribute( db, 'name' ): " AdminConfig.showAttribute( db, 'name' )