text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Move to hash history to allow refresh when on java server
|
// @flow
import 'bootstrap/dist/css/bootstrap.css';
import createHistory from 'history/createHashHistory'
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'react-router-redux';
import { createPersistor, getStoredState } from 'redux-persist';
import App from './App';
import './index.css';
import registerServiceWorker from './registerServiceWorker';
import configureStore from './store';
const history = createHistory();
const persistConfig = {};
async function bootstrap() {
const restoredState = await getStoredState(persistConfig);
const store = configureStore(history, restoredState);
createPersistor(store, persistConfig);
ReactDOM.render(<Provider store={store}>
<ConnectedRouter history={history}>
<App/>
</ConnectedRouter>
</Provider>, document.getElementById('root'));
registerServiceWorker();
}
bootstrap();
|
// @flow
import 'bootstrap/dist/css/bootstrap.css';
import createBrowserHistory from 'history/createBrowserHistory'
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'react-router-redux';
import { createPersistor, getStoredState } from 'redux-persist';
import App from './App';
import './index.css';
import registerServiceWorker from './registerServiceWorker';
import configureStore from './store';
const history = createBrowserHistory();
const persistConfig = {};
async function bootstrap() {
const restoredState = await getStoredState(persistConfig);
const store = configureStore(history, restoredState);
createPersistor(store, persistConfig);
ReactDOM.render(<Provider store={store}>
<ConnectedRouter history={history}>
<App/>
</ConnectedRouter>
</Provider>, document.getElementById('root'));
registerServiceWorker();
}
bootstrap();
|
Feature: Update request logger middleware implementation
|
<?php
namespace PhalconUtils\Middleware;
use Phalcon\Logger\Adapter\File;
use Phalcon\Mvc\Micro;
use PhalconUtils\Constants\Services;
use PhalconUtils\Util\Logger;
/**
* Class LoggerMiddleware
* @author Adeyemi Olaoye <yemi@cottacush.com>
* @package App\Middleware
*/
class RequestLoggerMiddleware extends BaseMiddleware
{
public function beforeExecuteRoute()
{
if ($this->isExcludedPath($this->getDI()->get(Services::CONFIG)->requestLogger->excluded_paths)) {
return true;
}
/** @var \Phalcon\Http\Request $request */
$request = $this->getDI()->get(Services::REQUEST);
$config = $this->getDI()->get(Services::CONFIG);
$fileTarget = new File($config->application->logsDir . 'requests.log');
$logger = new Logger([$fileTarget]);
$logger->info('Request URL:' . $request->getURI());
if ($request->isPost() || $request->isPut()) {
$rawBody = $request->getRawBody();
$logger->info('Request Body: ' . $rawBody);
}
}
public function call(Micro $application)
{
return true;
}
}
|
<?php
namespace PhalconUtils\Middleware;
use Phalcon\Mvc\Micro;
use PhalconUtils\Constants\Services;
use PhalconUtils\Util\Logger;
/**
* Class LoggerMiddleware
* @author Adeyemi Olaoye <yemi@cottacush.com>
* @package App\Middleware
*/
class RequestLoggerMiddleware extends BaseMiddleware
{
public function beforeExecuteRoute()
{
if ($this->isExcludedPath($this->getDI()->get(Services::CONFIG)->requestLogger->excluded_paths)) {
return true;
}
/** @var \Phalcon\Http\Request $request */
$request = $this->getDI()->get(Services::REQUEST);
$config = $this->getDI()->get(Services::CONFIG);
$logger = new Logger($config->application->logsDir . "requests.log");
$logger->log('Request URL:' . $request->getURI(), \Phalcon\Logger::INFO);
if ($request->isPost() || $request->isPut()) {
$rawBody = $request->getRawBody();
$logger->log('Request Body: ' . $rawBody, \Phalcon\Logger::INFO);
}
}
public function call(Micro $application)
{
return true;
}
}
|
Add tests requirements, fix console scripts definitions
|
from setuptools import find_packages, setup
setup(
name='ngx-task',
version='0.2',
description='Testimonial for candidates to show up their code-foo',
author='Dmitry Shulyak',
author_email='dmitri.shulyak@gmail.com',
url='https://github.com/shudmi/ngx-task',
classifiers=[
'License :: Apache License 2.0',
'Programming Language :: Python',
'Programming Language :: Python 3',
'Programming Language :: Python 3.4',
],
packages=find_packages(exclude=['tests', 'tests.*']),
install_requires=[],
tests_require=[
"pytest==3.0.7",
],
entry_points="""
[console_scripts]
ngx_generate=ngx_task.cli:generate_data
ngx_process=ngx_task.cli:process_data
"""
)
|
from setuptools import find_packages, setup
setup(
name='ngx-task',
version='0.1',
description='Testimonial for candidates to show up their code-foo',
author='Dmitry Shulyak',
author_email='dmitri.shulyak@gmail.com',
url='https://github.com/shudmi/ngx-task',
classifiers=[
'License :: Apache License 2.0',
'Programming Language :: Python',
'Programming Language :: Python 3',
'Programming Language :: Python 3.4',
],
packages=find_packages(exclude=['tests', 'tests.*']),
install_requires=[],
entry_points="""
[console_scripts]
ngx_generate=ngx_task.cli.generate_data
ngx_process=ngx_task.cli.process_data
"""
)
|
Throw APIErrorException if there's a gametime endpoint error
|
<?php
namespace TruckersMP\Models;
use Carbon\Carbon;
use TruckersMP\Exceptions\APIErrorException;
class GameTimeModel
{
/**
* @var Carbon
*/
public $time;
/**
* GameTimeModel constructor.
*
* @param array $response
* @throws \Exception
*/
public function __construct(array $response)
{
if ($response['error']) {
throw new APIErrorException($response['error']);
}
$load['minutes'] = $response['game_time'];
$load['hours'] = $load['minutes'] / 60;
$load['minutes'] = $load['minutes'] % 60;
$load['days'] = $load['hours'] / 24;
$load['hours'] = $load['hours'] % 24;
$load['months'] = $load['days'] / 30;
$load['days'] = $load['days'] % 30;
$load['years'] = intval($load['months'] / 12);
$load['months'] = $load['months'] % 12;
$this->time = Carbon::create($load['years'], $load['months'], $load['days'], $load['hours'], $load['minutes']);
}
}
|
<?php
namespace TruckersMP\Models;
use Carbon\Carbon;
class GameTimeModel
{
/**
* @var Carbon
*/
public $time;
/**
* GameTimeModel constructor.
*
* @param array $response
* @throws \Exception
*/
public function __construct(array $response)
{
if ($response['error']) {
throw new \Exception($response['error']);
}
$load['minutes'] = $response['game_time'];
$load['hours'] = $load['minutes'] / 60;
$load['minutes'] = $load['minutes'] % 60;
$load['days'] = $load['hours'] / 24;
$load['hours'] = $load['hours'] % 24;
$load['months'] = $load['days'] / 30;
$load['days'] = $load['days'] % 30;
$load['years'] = intval($load['months'] / 12);
$load['months'] = $load['months'] % 12;
$this->time = Carbon::create($load['years'], $load['months'], $load['days'], $load['hours'], $load['minutes']);
}
}
|
Bump version for tag and release
|
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
install_requires = (
'parsimonious',
)
description = "Connexions project search query parsing library."
with open('README.rst', 'r') as fb:
readme = fb.read()
long_description = readme
setup(
name='cnx-query-grammar',
version='0.2.2',
author='Connexions team',
author_email='info@cnx.org',
url='https://github.com/connexions/cnx-query-grammar',
license='AGPL, See also LICENSE.txt',
description=description,
long_description=long_description,
packages=find_packages(),
install_requires=install_requires,
package_data={
'': ['query.peg'],
},
entry_points="""\
[console_scripts]
query_parser = cnxquerygrammar.query_parser:main
""",
test_suite='cnxquerygrammar.tests'
)
|
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
install_requires = (
'parsimonious',
)
description = "Connexions project search query parsing library."
with open('README.rst', 'r') as fb:
readme = fb.read()
long_description = readme
setup(
name='cnx-query-grammar',
version='0.2.1',
author='Connexions team',
author_email='info@cnx.org',
url='https://github.com/connexions/cnx-query-grammar',
license='AGPL, See also LICENSE.txt',
description=description,
long_description=long_description,
packages=find_packages(),
install_requires=install_requires,
package_data={
'': ['query.peg'],
},
entry_points="""\
[console_scripts]
query_parser = cnxquerygrammar.query_parser:main
""",
test_suite='cnxquerygrammar.tests'
)
|
Fix comments in horizontal boxplot example
|
"""
Horizontal boxplot with observations
====================================
_thumb: .7, .37
"""
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="ticks")
# Initialize the figure with a logarithmic x axis
f, ax = plt.subplots(figsize=(7, 6))
ax.set_xscale("log")
# Load the example planets dataset
planets = sns.load_dataset("planets")
# Plot the orbital period with horizontal boxes
sns.boxplot(x="distance", y="method", data=planets,
whis=np.inf, palette="vlag")
# Add in points to show each observation
sns.swarmplot(x="distance", y="method", data=planets,
size=2, color=".3", linewidth=0)
# Tweak the visual presentation
ax.xaxis.grid(True)
ax.set(ylabel="")
sns.despine(trim=True, left=True)
|
"""
Horizontal boxplot with observations
====================================
_thumb: .7, .37
"""
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="ticks")
# Initialize the figure
f, ax = plt.subplots(figsize=(7, 6))
ax.set_xscale("log")
# Load the example planets dataset
planets = sns.load_dataset("planets")
# Plot the orbital period with horizontal boxes
sns.boxplot(x="distance", y="method", data=planets,
whis=np.inf, palette="vlag")
# Add in points to show each observation
sns.swarmplot(x="distance", y="method", data=planets,
size=2, color=".3", linewidth=0)
# Make the quantitative axis logarithmic
ax.xaxis.grid(True)
ax.set(ylabel="")
sns.despine(trim=True, left=True)
|
Use immutable arg rather mutable arg
Passing mutable objects as default args is a known Python pitfall.
We'd better avoid this. This commit changes mutable default args with
None, then use 'arg = arg or []'.
Change-Id: If3a10d58e6cd792a2011c177c49d3b865a7421ff
|
# Copyright (c) 2014 Mirantis Inc.
#
# 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.
from sahara.conductor import resource as r
def create_cluster(name, tenant, plugin, version, node_groups, **kwargs):
dct = {'name': name, 'tenant_id': tenant, 'plugin_name': plugin,
'hadoop_version': version, 'node_groups': node_groups}
dct.update(kwargs)
return r.ClusterResource(dct)
def make_ng_dict(name, flavor, processes, count, instances=None, **kwargs):
instances = instances or []
dct = {'name': name, 'flavor_id': flavor, 'node_processes': processes,
'count': count, 'instances': instances}
dct.update(kwargs)
return dct
def make_inst_dict(inst_id, inst_name):
return {'instance_id': inst_id, 'instance_name': inst_name}
|
# Copyright (c) 2014 Mirantis Inc.
#
# 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.
from sahara.conductor import resource as r
def create_cluster(name, tenant, plugin, version, node_groups, **kwargs):
dct = {'name': name, 'tenant_id': tenant, 'plugin_name': plugin,
'hadoop_version': version, 'node_groups': node_groups}
dct.update(kwargs)
return r.ClusterResource(dct)
def make_ng_dict(name, flavor, processes, count, instances=[], **kwargs):
dct = {'name': name, 'flavor_id': flavor, 'node_processes': processes,
'count': count, 'instances': instances}
dct.update(kwargs)
return dct
def make_inst_dict(inst_id, inst_name):
return {'instance_id': inst_id, 'instance_name': inst_name}
|
Use the right object for ACL validation
|
<?php
/*
* This file is part of the Sonata project.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\AdminBundle\Security\Handler;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Sonata\AdminBundle\Admin\AdminInterface;
class AclSecurityHandler implements SecurityHandlerInterface
{
public function __construct(SecurityContextInterface $securityContext)
{
$this->securityContext = $securityContext;
}
/**
* {@inheritDoc}
*/
public function isGranted($attributes, $object = null)
{
return $this->securityContext->isGranted($attributes, $object);
}
/**
* {@inheritDoc}
*/
public function buildSecurityInformation(AdminInterface $admin)
{
$baseRole = 'ROLE_'.str_replace('.', '_', strtoupper($admin->getCode())).'_%s';
$results = array();
foreach ($admin->getSecurityInformation() as $name => $permissions) {
$results[sprintf($baseRole, $name)] = $permissions;
}
return $results;
}
}
|
<?php
/*
* This file is part of the Sonata project.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\AdminBundle\Security\Handler;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Sonata\AdminBundle\Admin\AdminInterface;
class AclSecurityHandler implements SecurityHandlerInterface
{
public function __construct(SecurityContextInterface $securityContext)
{
$this->securityContext = $securityContext;
}
/**
* {@inheritDoc}
*/
public function isGranted($attributes, $object = null)
{
return $this->securityContext->isGranted($attributes, $this);
}
/**
* {@inheritDoc}
*/
public function buildSecurityInformation(AdminInterface $admin)
{
$baseRole = 'ROLE_'.str_replace('.', '_', strtoupper($admin->getCode())).'_%s';
$results = array();
foreach ($admin->getSecurityInformation() as $name => $permissions) {
$results[sprintf($baseRole, $name)] = $permissions;
}
return $results;
}
}
|
Use complete iri for annotation property declaration
|
package de.linkvt.bachelor.features.annotations.ontology.owl;
import de.linkvt.bachelor.features.Feature;
import de.linkvt.bachelor.features.FeatureCategory;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLAnnotation;
import org.semanticweb.owlapi.model.OWLAnnotationProperty;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLLiteral;
import org.springframework.stereotype.Component;
@Component
public class OwlAnnotationPropertyFeature extends Feature {
@Override
public void addToOntology() {
String ontologyIri = ontology.getOntologyID().getOntologyIRI().get().toString();
OWLAnnotationProperty annotationProperty = factory.getOWLAnnotationProperty(IRI.create(ontologyIri + "customAnnotationProperty"));
addAxiomToOntology(factory.getOWLDeclarationAxiom(annotationProperty));
OWLLiteral annotationValue = factory.getOWLLiteral("Custom Annotation Value");
OWLAnnotation annotation = factory.getOWLAnnotation(annotationProperty, annotationValue);
OWLClass owlClass = featurePool.getReusableClass();
addAxiomToOntology(factory.getOWLDeclarationAxiom(owlClass));
addAxiomToOntology(factory.getOWLAnnotationAssertionAxiom(owlClass.getIRI(), annotation));
}
@Override
public String getName() {
return "owl:AnnotationProperty";
}
@Override
public String getToken() {
return "annotationproperty";
}
@Override
public FeatureCategory getCategory() {
return FeatureCategory.ANNOTATIONS;
}
}
|
package de.linkvt.bachelor.features.annotations.ontology.owl;
import de.linkvt.bachelor.features.Feature;
import de.linkvt.bachelor.features.FeatureCategory;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLAnnotation;
import org.semanticweb.owlapi.model.OWLAnnotationProperty;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLLiteral;
import org.springframework.stereotype.Component;
@Component
public class OwlAnnotationPropertyFeature extends Feature {
@Override
public void addToOntology() {
OWLAnnotationProperty annotationProperty = factory.getOWLAnnotationProperty(IRI.create("customAnnotationProperty"));
addAxiomToOntology(factory.getOWLDeclarationAxiom(annotationProperty));
OWLLiteral annotationValue = factory.getOWLLiteral("Custom Annotation Value");
OWLAnnotation annotation = factory.getOWLAnnotation(annotationProperty, annotationValue);
OWLClass owlClass = featurePool.getReusableClass();
addAxiomToOntology(factory.getOWLDeclarationAxiom(owlClass));
addAxiomToOntology(factory.getOWLAnnotationAssertionAxiom(owlClass.getIRI(), annotation));
}
@Override
public String getName() {
return "owl:AnnotationProperty";
}
@Override
public String getToken() {
return "annotationproperty";
}
@Override
public FeatureCategory getCategory() {
return FeatureCategory.ANNOTATIONS;
}
}
|
Fix WOFF2 font so it passes OTS in Firefox
|
var supportsWoff2 = (function( win ){
if( !( "FontFace" in win ) ) {
return false;
}
var f = new FontFace('t', 'url( "data:application/font-woff2;base64,d09GMgABAAAAAADwAAoAAAAAAiQAAACoAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmAALAogOAE2AiQDBgsGAAQgBSAHIBuDAciO1EZ3I/mL5/+5/rfPnTt9/9Qa8H4cUUZxaRbh36LiKJoVh61XGzw6ufkpoeZBW4KphwFYIJGHB4LAY4hby++gW+6N1EN94I49v86yCpUdYgqeZrOWN34CMQg2tAmthdli0eePIwAKNIIRS4AGZFzdX9lbBUAQlm//f262/61o8PlYO/D1/X4FrWFFgdCQD9DpGJSxmFyjOAGUU4P0qigcNb82GAAA" ) format( "woff2" )', {});
f.load()['catch'](function() {});
return f.status == 'loading' || f.status == 'loaded';
})( this );
|
var supportsWoff2 = (function( win ){
if( !( "FontFace" in win ) ) {
return false;
}
var f = new FontFace('t', 'url( "data:application/font-woff2;base64,d09GMgABAAAAAADcAAoAAAAAAggAAACWAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAABk4ALAoUNAE2AiQDCAsGAAQgBSAHIBtvAcieB3aD8wURQ+TZazbRE9HvF5vde4KCYGhiCgq/NKPF0i6UIsZynbP+Xi9Ng+XLbNlmNz/xIBBqq61FIQRJhC/+QA/08PJQJ3sK5TZFMlWzC/iK5GUN40psgqvxwBjBOg6JUSJ7ewyKE2AAaXZrfUB4v+hze37ugJ9d+DeYqiDwVgCawviwVFGnuttkLqIMGivmDg" ) format( "woff2" )', {});
f.load()['catch'](function() {});
return f.status == 'loading' || f.status == 'loaded';
})( this );
|
Fix Fetch util reject case
|
var Promise = require('es6-promise').Promise;
function fetch(options) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if(xhr.getResponseHeader('content-type').search('application/json') >= 0) {
try {
var response = JSON.parse(xhr.responseText);
return resolve(response);
} catch(e) {
return reject(e);
}
}
if(xhr.status !== 200) {
return reject();
}
resolve(xhr.responseText);
};
xhr.onerror = function(e) {
reject(e);
};
xhr.open(options.method, options.url);
xhr.send(options.body);
});
}
module.exports = fetch;
|
var Promise = require('es6-promise').Promise;
function fetch(options) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if(xhr.getResponseHeader('content-type').search('application/json') >= 0) {
try {
var response = JSON.parse(xhr.responseText);
return resolve(response);
} catch(e) {
reject(e);
}
}
resolve(xhr.responseText);
};
xhr.onerror = function() {
reject();
};
xhr.open(options.method, options.url);
xhr.send(options.body);
});
}
module.exports = fetch;
|
Update tests and fix the failing test
|
from molo.core.tests.base import MoloTestCaseMixin
from django.test import TestCase, Client
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
class GemRegistrationViewTest(TestCase, MoloTestCaseMixin):
def setUp(self):
self.client = Client()
self.mk_main()
def test_user_info_displaying_after_registration(self):
self.user = User.objects.create_user(
username='tester',
email='tester@example.com',
password='tester')
self.client.login(username='tester', password='tester')
response = self.client.get(reverse('edit_my_profile'))
self.assertNotContains(response, 'useralias')
self.assertContains(response, '<option value="f">female</option>')
self.user.gem_profile.gender = 'f'
self.user.profile.alias = 'useralias'
self.user.gem_profile.save()
self.user.profile.save()
response = self.client.get(reverse('edit_my_profile'))
self.assertContains(response, 'useralias')
self.assertNotContains(response, '<option value="f">female</option>')
|
from molo.core.tests.base import MoloTestCaseMixin
from django.test import TestCase, Client
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
class GemRegistrationViewTest(TestCase, MoloTestCaseMixin):
def setUp(self):
self.client = Client()
self.mk_main()
def test_user_info_displaying_after_registration(self):
self.user = User.objects.create_user(
username='tester',
email='tester@example.com',
password='tester')
self.user.profile.gender = 'female'
self.user.profile.alias = 'useralias'
self.user.profile.save()
self.client.login(username='tester', password='tester')
response = self.client.get(reverse('edit_my_profile'))
print response
self.assertContains(response, 'useralias')
self.assertNotContains(response, '<option value="f">female</option>')
|
Add JSON content type to authenticate headers
|
import Ember from 'ember';
import Base from 'ember-simple-auth/authenticators/base';
import Configuration from '../configuration';
const { get, isEmpty, inject: { service }, RSVP: { resolve, reject } } = Ember;
export default Base.extend({
ajax: service(),
init() {
this._super(...arguments);
this.serverTokenEndpoint = Configuration.serverTokenEndpoint;
this.tokenAttributeName = Configuration.tokenAttributeName;
this.identificationAttributeName = Configuration.identificationAttributeName;
},
restore(data) {
const token = get(data, this.tokenAttributeName);
if (!isEmpty(token)) {
return resolve(data);
} else {
return reject();
}
},
authenticate(data) {
return get(this, 'ajax').post(this.serverTokenEndpoint, {
contentType: 'application/json',
data: JSON.stringify(data)
}).then((response) => {
return resolve(response);
}).catch((error) => {
Ember.Logger.warn(error);
return reject();
});
}
});
|
import Ember from 'ember';
import Base from 'ember-simple-auth/authenticators/base';
import Configuration from '../configuration';
const { get, isEmpty, inject: { service }, RSVP: { resolve, reject } } = Ember;
export default Base.extend({
ajax: service(),
init() {
this._super(...arguments);
this.serverTokenEndpoint = Configuration.serverTokenEndpoint;
this.tokenAttributeName = Configuration.tokenAttributeName;
this.identificationAttributeName = Configuration.identificationAttributeName;
},
restore(data) {
const token = get(data, this.tokenAttributeName);
if (!isEmpty(token)) {
return resolve(data);
} else {
return reject();
}
},
authenticate(data) {
return get(this, 'ajax').post(this.serverTokenEndpoint, {
data: JSON.stringify(data)
}).then((response) => {
return resolve(response);
}).catch((error) => {
Ember.Logger.warn(error);
return reject();
});
}
});
|
Improve error is API is dead
|
import fetch from 'isomorphic-fetch'
import config from './config'
async function fetchJson(url, options) {
const response = await fetch(url, options)
.catch(() => { throw new Error(`Could not fetch '${url}'.`)})
if (response.status < 200 || response.status >= 300) {
throw new Error(`'${url}' returned the unexpected return code: '${response.status}'.`)
}
const data = await response.json()
return {
data,
'country-package': response.headers.get('country-package'),
'country-package-version': response.headers.get('country-package-version'),
}
}
export function fetchParameters(apiBaseUrl = config.apiBaseUrl) {
return fetchJson(`${apiBaseUrl}/parameters`)
}
export function fetchVariables(apiBaseUrl = config.apiBaseUrl) {
return fetchJson(`${apiBaseUrl}/variables`)
}
export function fetchParameter(parameterId, apiBaseUrl = config.apiBaseUrl) {
return fetchJson(`${apiBaseUrl}/parameter/${parameterId}`)
}
export function fetchVariable(variableId, apiBaseUrl = config.apiBaseUrl) {
return fetchJson(`${apiBaseUrl}/variable/${variableId}`)
}
export function fetchSwagger(apiBaseUrl = config.apiBaseUrl) {
return fetchJson(`${apiBaseUrl}/spec`)
}
|
import fetch from 'isomorphic-fetch'
import config from './config'
async function fetchJson(url, options) {
const response = await fetch(url, options)
if (response.status < 200 || response.status >= 300) {
throw new Error(`'${url}' returned the unexpected return code: '${response.status}'.`)
}
const data = await response.json()
return {
data,
'country-package': response.headers.get('country-package'),
'country-package-version': response.headers.get('country-package-version'),
}
}
export function fetchParameters(apiBaseUrl = config.apiBaseUrl) {
return fetchJson(`${apiBaseUrl}/parameters`)
}
export function fetchVariables(apiBaseUrl = config.apiBaseUrl) {
return fetchJson(`${apiBaseUrl}/variables`)
}
export function fetchParameter(parameterId, apiBaseUrl = config.apiBaseUrl) {
return fetchJson(`${apiBaseUrl}/parameter/${parameterId}`)
}
export function fetchVariable(variableId, apiBaseUrl = config.apiBaseUrl) {
return fetchJson(`${apiBaseUrl}/variable/${variableId}`)
}
export function fetchSwagger(apiBaseUrl = config.apiBaseUrl) {
return fetchJson(`${apiBaseUrl}/spec`)
}
|
Add gcc 11.3 released on April 21, 2022
|
const ALL_COMPILERS = ['clang-3.8', 'clang-3.9', 'clang-4.0', 'clang-5.0',
'clang-6.0', 'clang-7.0', 'clang-7.1', 'clang-8.0', 'clang-9.0',
'clang-10.0', 'clang-11.0', 'clang-11.1', 'clang-12.0', 'clang-13.0',
'gcc-5.5', 'gcc-6.4', 'gcc-6.5', 'gcc-7.2', 'gcc-7.3',
'gcc-7.4', 'gcc-7.5', 'gcc-8.1', 'gcc-8.2', 'gcc-8.3', 'gcc-8.4', 'gcc-8.5',
'gcc-9.1', 'gcc-9.2', 'gcc-9.3', 'gcc-9.4', 'gcc-10.1', 'gcc-10.2', 'gcc-10.3',
'gcc-11.1', 'gcc-11.2', 'gcc-11.3'];
export default {
allCompilers: ALL_COMPILERS,
latestCompiler: 'clang-13.0'
};
|
const ALL_COMPILERS = ['clang-3.8', 'clang-3.9', 'clang-4.0', 'clang-5.0',
'clang-6.0', 'clang-7.0', 'clang-7.1', 'clang-8.0', 'clang-9.0',
'clang-10.0', 'clang-11.0', 'clang-11.1', 'clang-12.0', 'clang-13.0',
'gcc-5.5', 'gcc-6.4', 'gcc-6.5', 'gcc-7.2', 'gcc-7.3',
'gcc-7.4', 'gcc-7.5', 'gcc-8.1', 'gcc-8.2', 'gcc-8.3', 'gcc-8.4', 'gcc-8.5',
'gcc-9.1', 'gcc-9.2', 'gcc-9.3', 'gcc-9.4', 'gcc-10.1', 'gcc-10.2', 'gcc-10.3', 'gcc-11.1', 'gcc-11.2'];
export default {
allCompilers: ALL_COMPILERS,
latestCompiler: 'clang-13.0'
};
|
CLOUDSTACK-9266: Make deleting static routes in private gw work
|
# -- coding: utf-8 --
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from pprint import pprint
def merge(dbag, staticroutes):
for route in staticroutes['routes']:
key = route['network']
dbag[key] = route
return dbag
|
# -- coding: utf-8 --
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from pprint import pprint
def merge(dbag, staticroutes):
for route in staticroutes['routes']:
key = route['network']
revoke = route['revoke']
if revoke:
try:
del dbag[key]
except KeyError:
pass
else:
dbag[key] = route
return dbag
|
Return image type of file in api
|
from rest_framework import serializers
from grandchallenge.cases.models import Image, ImageFile
class ImageFileSerializer(serializers.ModelSerializer):
class Meta:
model = ImageFile
fields = ("pk", "image", "file", "image_type")
class ImageSerializer(serializers.ModelSerializer):
files = ImageFileSerializer(many=True, read_only=True)
class Meta:
model = Image
fields = (
"pk",
"name",
"study",
"files",
"width",
"height",
"depth",
"color_space",
"modality",
"eye_choice",
"stereoscopic_choice",
"field_of_view",
"shape_without_color",
"shape",
)
|
from rest_framework import serializers
from grandchallenge.cases.models import Image, ImageFile
class ImageFileSerializer(serializers.ModelSerializer):
class Meta:
model = ImageFile
fields = ("pk", "image", "file")
class ImageSerializer(serializers.ModelSerializer):
files = ImageFileSerializer(many=True, read_only=True)
class Meta:
model = Image
fields = (
"pk",
"name",
"study",
"files",
"width",
"height",
"depth",
"color_space",
"modality",
"eye_choice",
"stereoscopic_choice",
"field_of_view",
"shape_without_color",
"shape",
)
|
Remove spaces in user names.
- Also ensure multiple consecutive dashes are replaced by just one.
|
package com.uwetrottmann.trakt.v2.entities;
public class Username {
/**
* Special user name for the current user (determined by auth data).
*/
public static final Username ME = new Username("me");
private String encodedUsername;
/**
* Encodes the username returned from trakt so it is API compatible (currently replaces "." with "-").
*
* @param username A username as returned by the trakt API.
* @see #ME
*/
public Username(String username) {
if (username == null || username.length() == 0) {
throw new IllegalArgumentException("trakt username can not be empty.");
}
// trakt encodes some special chars in usernames
// - points "." as a dash "-"
// - spaces " " as a dash "-"
// - multiple dashes are reduced to one
this.encodedUsername = username.replace(".", "-").replace(" ", "-").replaceAll("(-)+", "-");
}
@Override
public String toString() {
return encodedUsername;
}
}
|
package com.uwetrottmann.trakt.v2.entities;
public class Username {
/**
* Special user name for the current user (determined by auth data).
*/
public static final Username ME = new Username("me");
private String encodedUsername;
/**
* Encodes the username returned from trakt so it is API compatible (currently replaces "." with "-").
*
* @param username A username as returned by the trakt API.
* @see #ME
*/
public Username(String username) {
if (username == null || username.length() == 0) {
throw new IllegalArgumentException("trakt username can not be empty.");
}
this.encodedUsername = username.replace(".", "-");
}
@Override
public String toString() {
return encodedUsername;
}
}
|
Allow filtering for tasks without due date
|
<?php
namespace Kanboard\Filter;
use Kanboard\Core\Filter\FilterInterface;
use Kanboard\Model\TaskModel;
/**
* Filter tasks by due date
*
* @package filter
* @author Frederic Guillot
*/
class TaskDueDateFilter extends BaseDateFilter implements FilterInterface
{
/**
* Get search attribute
*
* @access public
* @return string[]
*/
public function getAttributes()
{
return array('due');
}
/**
* Apply filter
*
* @access public
* @return FilterInterface
*/
public function apply()
{
if ($this->value == "none") {
$this->query->eq(TaskModel::TABLE.'.date_due', 0);
} else {
$this->query->neq(TaskModel::TABLE.'.date_due', 0);
$this->query->notNull(TaskModel::TABLE.'.date_due');
$this->applyDateFilter(TaskModel::TABLE.'.date_due');
}
return $this;
}
}
|
<?php
namespace Kanboard\Filter;
use Kanboard\Core\Filter\FilterInterface;
use Kanboard\Model\TaskModel;
/**
* Filter tasks by due date
*
* @package filter
* @author Frederic Guillot
*/
class TaskDueDateFilter extends BaseDateFilter implements FilterInterface
{
/**
* Get search attribute
*
* @access public
* @return string[]
*/
public function getAttributes()
{
return array('due');
}
/**
* Apply filter
*
* @access public
* @return FilterInterface
*/
public function apply()
{
$this->query->neq(TaskModel::TABLE.'.date_due', 0);
$this->query->notNull(TaskModel::TABLE.'.date_due');
$this->applyDateFilter(TaskModel::TABLE.'.date_due');
return $this;
}
}
|
Fix flake8 E113 unexpected indentation
|
import pickle
from sqlobject import *
from sqlobject.tests.dbtest import *
########################################
## Pickle instances
########################################
class TestPickle(SQLObject):
question = StringCol()
answer = IntCol()
test_question = 'The Ulimate Question of Life, the Universe and Everything'
test_answer = 42
def test_pickleCol():
setupClass(TestPickle)
connection = TestPickle._connection
test = TestPickle(question=test_question, answer=test_answer)
pickle_data = pickle.dumps(test, pickle.HIGHEST_PROTOCOL)
connection.cache.clear()
test = pickle.loads(pickle_data)
test2 = connection.cache.tryGet(test.id, TestPickle)
assert test2 is test
assert test.question == test_question
assert test.answer == test_answer
if (connection.dbName == 'sqlite') and connection._memory:
return # The following test requires a different connection
test = TestPickle.get(
test.id,
# make a different DB URI and open another connection
connection=getConnection(registry=''))
raises(pickle.PicklingError, pickle.dumps, test, pickle.HIGHEST_PROTOCOL)
|
import pickle
from sqlobject import *
from sqlobject.tests.dbtest import *
########################################
## Pickle instances
########################################
class TestPickle(SQLObject):
question = StringCol()
answer = IntCol()
test_question = 'The Ulimate Question of Life, the Universe and Everything'
test_answer = 42
def test_pickleCol():
setupClass(TestPickle)
connection = TestPickle._connection
test = TestPickle(question=test_question, answer=test_answer)
pickle_data = pickle.dumps(test, pickle.HIGHEST_PROTOCOL)
connection.cache.clear()
test = pickle.loads(pickle_data)
test2 = connection.cache.tryGet(test.id, TestPickle)
assert test2 is test
assert test.question == test_question
assert test.answer == test_answer
if (connection.dbName == 'sqlite') and connection._memory:
return # The following test requires a different connection
test = TestPickle.get(test.id,
connection=getConnection(registry='')) # to make a different DB URI
# and open another connection
raises(pickle.PicklingError, pickle.dumps, test, pickle.HIGHEST_PROTOCOL)
|
Increase keepalive timeout to 5 minutes.
|
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Factory to create grpc channel."""
# pytype: skip-file
import grpc
class GRPCChannelFactory(grpc.StreamStreamClientInterceptor):
DEFAULT_OPTIONS = [
("grpc.keepalive_time_ms", 20000),
("grpc.keepalive_timeout_ms", 300000),
]
def __init__(self):
pass
@staticmethod
def insecure_channel(target, options=None):
if options is None:
options = []
return grpc.insecure_channel(
target, options=options + GRPCChannelFactory.DEFAULT_OPTIONS)
@staticmethod
def secure_channel(target, credentials, options=None):
if options is None:
options = []
return grpc.secure_channel(
target,
credentials,
options=options + GRPCChannelFactory.DEFAULT_OPTIONS)
|
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Factory to create grpc channel."""
# pytype: skip-file
import grpc
class GRPCChannelFactory(grpc.StreamStreamClientInterceptor):
DEFAULT_OPTIONS = [("grpc.keepalive_time_ms", 20000)]
def __init__(self):
pass
@staticmethod
def insecure_channel(target, options=None):
if options is None:
options = []
return grpc.insecure_channel(
target, options=options + GRPCChannelFactory.DEFAULT_OPTIONS)
@staticmethod
def secure_channel(target, credentials, options=None):
if options is None:
options = []
return grpc.secure_channel(
target,
credentials,
options=options + GRPCChannelFactory.DEFAULT_OPTIONS)
|
Fix usage of fs-extra (should've been fs-extra-promise)
|
import fs from 'fs-extra-promise';
import path from 'path';
import app from 'app';
import BaseAutoLauncher from 'browser/components/auto-launcher/base';
import files from 'common/utils/files';
const autoStartDir = path.join(app.getPath('home'), '.config', 'autostart');
const desktopFilePath = path.join(autoStartDir, global.manifest.name + '.desktop');
const initialDesktopPath = path.join(app.getAppPath(), 'startup.desktop');
class LinuxAutoLauncher extends BaseAutoLauncher {
async enable() {
log('enabling linux auto-launch');
log('creating autolaunch .desktop');
await files.replaceFile(desktopFilePath, () => fs.copyAsync(initialDesktopPath, desktopFilePath));
}
async disable() {
log('disabling linux auto-launch');
log('removing autolaunch .desktop');
await fs.removeAsync(desktopFilePath);
}
async isEnabled() {
log('checking linux auto-launch');
await files.isFileExists(desktopFilePath);
}
}
export default LinuxAutoLauncher;
|
import fs from 'fs-extra';
import path from 'path';
import app from 'app';
import BaseAutoLauncher from 'browser/components/auto-launcher/base';
import files from 'common/utils/files';
const autoStartDir = path.join(app.getPath('home'), '.config', 'autostart');
const desktopFilePath = path.join(autoStartDir, global.manifest.name + '.desktop');
const initialDesktopPath = path.join(app.getAppPath(), 'startup.desktop');
class LinuxAutoLauncher extends BaseAutoLauncher {
async enable() {
log('enabling linux auto-launch');
log('creating autolaunch .desktop');
await files.replaceFile(desktopFilePath, () => fs.copyAsync(initialDesktopPath, desktopFilePath));
}
async disable() {
log('disabling linux auto-launch');
log('removing autolaunch .desktop');
await fs.removeAsync(desktopFilePath);
}
async isEnabled() {
log('checking linux auto-launch');
await files.isFileExists(desktopFilePath);
}
}
export default LinuxAutoLauncher;
|
Add as a dependency (minification)
|
(function () {
'use strict';
/*global angular, Blob, URL */
angular.module('angular.img', [
]).directive('httpSrc', ['$http', function ($http) {
return {
link: function ($scope, elem, attrs) {
function revokeObjectURL() {
if ($scope.objectURL) {
URL.revokeObjectURL($scope.objectURL);
}
}
$scope.$watch('objectURL', function (objectURL) {
elem.attr('src', objectURL);
});
$scope.$on('$destroy', function () {
revokeObjectURL();
});
attrs.$observe('httpSrc', function (url) {
revokeObjectURL();
if (url) {
$http.get(url, { responseType: 'arraybuffer' }).then(function (response) {
var blob = new Blob([ response.data ], { type: response.headers('Content-Type') });
$scope.objectURL = URL.createObjectURL(blob);
});
}
});
}
};
}]);
}());
|
(function () {
'use strict';
/*global angular, Blob, URL */
angular.module('angular.img', [
]).directive('httpSrc', function ($http) {
return {
link: function ($scope, elem, attrs) {
function revokeObjectURL() {
if ($scope.objectURL) {
URL.revokeObjectURL($scope.objectURL);
}
}
$scope.$watch('objectURL', function (objectURL) {
elem.attr('src', objectURL);
});
$scope.$on('$destroy', function () {
revokeObjectURL();
});
attrs.$observe('httpSrc', function (url) {
revokeObjectURL();
if (url) {
$http.get(url, { responseType: 'arraybuffer' }).then(function (response) {
var blob = new Blob([ response.data ], { type: response.headers('Content-Type') });
$scope.objectURL = URL.createObjectURL(blob);
});
}
});
}
};
});
}());
|
Make the id argument optional
|
// Creates an HD canvas element on page and
// returns a reference to the element
var createCanvasElement = function (width, height, id, insertAfter) {
// Creates a scaled-up canvas based on the device's
// resolution, then displays it properly using styles
function createHDCanvas (ratio) {
var canvas = document.createElement('canvas');
// Creates a dummy canvas to test device's pixel ratio
ratio = (function () {
var context = document.createElement('canvas').getContext('2d');
var dpr = window.devicePixelRatio || 1;
var bsr = context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1;
return dpr / bsr;
})();
canvas.width = width * ratio;
canvas.height = height * ratio;
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
canvas.getContext('2d').setTransform(ratio, 0, 0, ratio, 0, 0);
if (id) canvas.id = id;
return canvas;
}
var canvas = createHDCanvas();
if (insertAfter) insertAfter.parentNode.insertBefore(canvas, insertAfter.nextSibling);
else document.body.appendChild(canvas);
return canvas;
};
module.exports = {
createCanvasElement: createCanvasElement
};
|
// Creates an HD canvas element on page and
// returns a reference to the element
var createCanvasElement = function (width, height, id, insertAfter) {
// Creates a scaled-up canvas based on the device's
// resolution, then displays it properly using styles
function createHDCanvas (ratio) {
var canvas = document.createElement('canvas');
// Creates a dummy canvas to test device's pixel ratio
ratio = (function () {
var context = document.createElement('canvas').getContext('2d');
var dpr = window.devicePixelRatio || 1;
var bsr = context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1;
return dpr / bsr;
})();
canvas.width = width * ratio;
canvas.height = height * ratio;
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
canvas.getContext('2d').setTransform(ratio, 0, 0, ratio, 0, 0);
canvas.id = id;
return canvas;
}
var canvas = createHDCanvas();
if (insertAfter) insertAfter.parentNode.insertBefore(canvas, insertAfter.nextSibling);
else document.body.appendChild(canvas);
return canvas;
};
module.exports = {
createCanvasElement: createCanvasElement
};
|
Change testing database to sqlite
|
import os
class Config(object):
"""Parent configuration class."""
DEBUG = False
CSRF_ENABLED = True
SECRET_KEY = os.getenv('SECRET_KEY')
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
class DevelopmentConfig(Config):
"""Configurations for Development."""
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/flask_db'
class TestingConfig(Config):
"""Configurations for Testing, with a separate test database."""
TESTING = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///test_db.db'
DEBUG = True
class StagingConfig(Config):
"""Configurations for Staging."""
DEBUG = True
class ProductionConfig(Config):
"""Configurations for Production."""
DEBUG = False
TESTING = False
app_config = {
'development': DevelopmentConfig,
'testing': TestingConfig,
'staging': StagingConfig,
'production': ProductionConfig,
}
|
import os
class Config(object):
"""Parent configuration class."""
DEBUG = False
CSRF_ENABLED = True
SECRET_KEY = os.getenv('SECRET_KEY')
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
class DevelopmentConfig(Config):
"""Configurations for Development."""
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/flask_db'
class TestingConfig(Config):
"""Configurations for Testing, with a separate test database."""
TESTING = True
SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/test_db'
DEBUG = True
class StagingConfig(Config):
"""Configurations for Staging."""
DEBUG = True
class ProductionConfig(Config):
"""Configurations for Production."""
DEBUG = False
TESTING = False
app_config = {
'development': DevelopmentConfig,
'testing': TestingConfig,
'staging': StagingConfig,
'production': ProductionConfig,
}
|
Use some Guava .net classes to clean up code a little
|
/*
* Copyright Myrrix 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.
*/
package net.myrrix.online.partition;
import java.util.List;
import com.google.common.net.HostAndPort;
/**
* Does nothing; not applicable in local mode.
*
* @author Sean Owen
*/
public final class PartitionLoaderImpl implements PartitionLoader {
/**
* @throws UnsupportedOperationException
*/
@Override
public List<List<HostAndPort>> loadPartitions(int defaultPort, String bucket, String instanceID) {
throw new UnsupportedOperationException();
}
}
|
/*
* Copyright Myrrix 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.
*/
package net.myrrix.online.partition;
import java.util.List;
import org.apache.mahout.common.Pair;
/**
* Does nothing; not applicable in local mode.
*
* @author Sean Owen
*/
public final class PartitionLoaderImpl implements PartitionLoader {
/**
* @throws UnsupportedOperationException
*/
@Override
public List<List<Pair<String, Integer>>> loadPartitions(int defaultPort, String bucket, String instanceID) {
throw new UnsupportedOperationException();
}
}
|
Mark Equal function as lazy
|
package builtins
import "github.com/coel-lang/coel/src/lib/core"
// Equal checks if all arguments are equal or not, and returns true if so or false otherwise.
var Equal = core.NewLazyFunction(
core.NewSignature(nil, nil, "args", nil, nil, ""),
func(ts ...*core.Thunk) core.Value {
l := ts[0]
if v := checkEmptyList(l, core.True); v != nil {
return v
}
e := core.PApp(core.First, l)
l = core.PApp(core.Rest, l)
for {
if v := checkEmptyList(l, core.True); v != nil {
return v
}
v := core.PApp(core.Equal, e, core.PApp(core.First, l)).Eval()
b, ok := v.(core.BoolType)
if !ok {
return core.NotBoolError(v)
} else if !b {
return core.False
}
l = core.PApp(core.Rest, l)
}
})
|
package builtins
import "github.com/coel-lang/coel/src/lib/core"
// Equal checks if all arguments are equal or not, and returns true if so or false otherwise.
var Equal = core.NewStrictFunction(
core.NewSignature(nil, nil, "args", nil, nil, ""),
func(ts ...*core.Thunk) core.Value {
l := ts[0]
if v := checkEmptyList(l, core.True); v != nil {
return v
}
e := core.PApp(core.First, l)
l = core.PApp(core.Rest, l)
for {
if v := checkEmptyList(l, core.True); v != nil {
return v
}
v := core.PApp(core.Equal, e, core.PApp(core.First, l)).Eval()
b, ok := v.(core.BoolType)
if !ok {
return core.NotBoolError(v)
} else if !b {
return core.False
}
l = core.PApp(core.Rest, l)
}
})
|
Use workshopper commands to run server mode
|
#!/usr/bin/env node
import path from 'path';
import workshopper from 'workshopper';
import updateNotifier from 'update-notifier';
import Server from './lib/Server';
import pkg from '../package.json';
updateNotifier({pkg: pkg}).notify();
workshopper({
name: 'testdrived3',
appDir: __dirname,
languages: ['en'],
helpFile: path.join(__dirname, './i18n/help/{lang}.txt'),
menuItems: [],
commands: [
{
name: 'server',
menu: false,
short: 's',
handler() {
const submissionPath = path.resolve(process.cwd(), process.argv[3]);
const server = new Server(process.env.PORT || 3333, submissionPath);
server.watch();
},
},
],
});
|
#!/usr/bin/env node
import path from 'path';
import workshopper from 'workshopper';
import updateNotifier from 'update-notifier';
import Server from './lib/Server';
import pkg from '../package.json';
updateNotifier({pkg: pkg}).notify();
const serverMode = process.argv[2] === 'server';
if (serverMode) {
const submissionPath = path.resolve(process.cwd(), process.argv[3]);
const server = new Server(process.env.PORT || 3333, submissionPath);
server.watch();
} else {
workshopper({
name: 'testdrived3',
appDir: __dirname,
languages: ['en'],
helpFile: path.join(__dirname, './i18n/help/{lang}.txt'),
menuItems: [],
});
}
|
Add status back to my reports
|
import React from 'react'
import Page from 'components/Page'
import Breadcrumbs from 'components/Breadcrumbs'
import ReportTable from 'components/ReportTable'
import API from 'api'
import {Report} from 'models'
export default class ReportsIndex extends Page {
constructor(props) {
super(props)
this.state = {reports: []}
}
fetchData() {
API.query(/* GraphQL */`
reports(f:getAll, pageSize:100, pageNum:0) {
id, intent, state
author {
id
name
}
}
`).then(data => this.setState({reports: Report.fromArray(data.reports)}))
}
render() {
return (
<div>
<Breadcrumbs items={[['My reports', '/reports']]} />
<ReportTable reports={this.state.reports} showAuthors={true} showStatus={true}/>
</div>
)
}
}
|
import React from 'react'
import Page from 'components/Page'
import Breadcrumbs from 'components/Breadcrumbs'
import ReportTable from 'components/ReportTable'
import API from 'api'
import {Report} from 'models'
export default class ReportsIndex extends Page {
constructor(props) {
super(props)
this.state = {reports: []}
}
fetchData() {
API.query(/* GraphQL */`
reports(f:getAll, pageSize:100, pageNum:0) {
id, intent, state
author {
id
name
}
}
`).then(data => this.setState({reports: Report.fromArray(data.reports)}))
}
render() {
return (
<div>
<Breadcrumbs items={[['My reports', '/reports']]} />
<ReportTable reports={this.state.reports} showAuthors={true} />
</div>
)
}
}
|
Fix how we are reading user name
|
from __future__ import unicode_literals
import django.forms
from django.conf import settings
from django.apps import apps
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.admin.forms import AdminAuthenticationForm
from captcha.fields import ReCaptchaField
class CaptchaForm(django.forms.Form):
captcha = ReCaptchaField()
username = django.forms.CharField()
def clean_username(self):
username = self.cleaned_data.get('username')
User = apps.get_model(getattr(settings, 'AUTH_USER_MODEL'))
if not User.objects.filter(email=username).exists():
raise django.forms.ValidationError("Username does not belong to a registered user")
return username
class EmailBasedAuthenticationForm(AuthenticationForm):
def clean_username(self):
return self.data['username'].lower()
class EmailBasedAdminAuthenticationForm(AdminAuthenticationForm):
def clean_username(self):
return self.data['username'].lower()
|
from __future__ import unicode_literals
import django.forms
from django.conf import settings
from django.apps import apps
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.admin.forms import AdminAuthenticationForm
from captcha.fields import ReCaptchaField
class CaptchaForm(django.forms.Form):
captcha = ReCaptchaField()
username = django.forms.CharField()
def clean_username(self):
username = self.cleaned_data.get('username')
User = apps.get_model(getattr(settings, 'AUTH_USER_MODEL'))
if not User.objects.filter(email=username).exists():
raise django.forms.ValidationError("Username does not belong to a registered user")
return username
class EmailBasedAuthenticationForm(AuthenticationForm):
def clean_username(self):
return self.cleaned_data['username'].lower()
class EmailBasedAdminAuthenticationForm(AdminAuthenticationForm):
def clean_username(self):
return self.cleaned_data['username'].lower()
|
Fix escaping for stricter php7.3.
|
<?php
declare(strict_types = 1);
namespace Soliant\SimpleFM\Client\ResultSet\Transformer;
use Litipk\BigNumbers\Decimal;
final class NumberTransformer
{
public function __invoke(string $value)
{
$cleanedValue = preg_replace_callback(
'(^[^\d-\.]*(-?)([^.]*)(.?)(.*)$)',
function (array $match) : string {
return
$match[1]
. preg_replace('([^\d]+)', '', $match[2])
. $match[3]
. preg_replace('([^\d]+)', '', $match[4]);
},
$value
);
if ('' === $cleanedValue) {
return null;
}
if ('-' === $cleanedValue) {
$cleanedValue = '0';
}
if (0 === strpos($cleanedValue, '.')) {
$cleanedValue = '0' . $cleanedValue;
}
return Decimal::fromString($cleanedValue);
}
}
|
<?php
declare(strict_types = 1);
namespace Soliant\SimpleFM\Client\ResultSet\Transformer;
use Litipk\BigNumbers\Decimal;
final class NumberTransformer
{
public function __invoke(string $value)
{
$cleanedValue = preg_replace_callback(
'(^[^\d-.]*(-?)([^.]*)(.?)(.*)$)',
function (array $match) : string {
return
$match[1]
. preg_replace('([^\d]+)', '', $match[2])
. $match[3]
. preg_replace('([^\d]+)', '', $match[4]);
},
$value
);
if ('' === $cleanedValue) {
return null;
}
if ('-' === $cleanedValue) {
$cleanedValue = '0';
}
if (0 === strpos($cleanedValue, '.')) {
$cleanedValue = '0' . $cleanedValue;
}
return Decimal::fromString($cleanedValue);
}
}
|
Add simple endpoint for form submission
|
import flask
import config
app = flask.Flask(__name__)
@app.route('/')
@app.route('/dashboard')
def render_dashboard():
return flask.render_template('dashboard.html')
@app.route('/new')
def render_new_procedure_form():
return flask.render_template('new_procedure.html')
# Endpoint for new opportunity form submission
@app.route('/opportunity', methods=['POST'])
def new_opportunity():
print(str.format(""))
return flask.redirect(flask.url_for('new', code=201))
# Endpoint for receiving SMS messages from Twilio
@app.route('/sms', methods=['POST'])
def receive_sms():
print(str.format("Received SMS: \n"
"To: {0}\n"
"From: {1}\n"
"Body: {2}\n",
str(flask.request.form['To']),
str(flask.request.form['From']),
str(flask.request.form['Body'])))
return '<Response></Response>'
if __name__ == '__main__':
app.debug = config.debug_mode
print(str.format("Debug Mode is: {0}", app.debug))
app.run()
|
import flask
import config
app = flask.Flask(__name__)
@app.route('/')
def index():
return flask.render_template('dashboard.html')
@app.route('/new')
def new():
return flask.render_template('new_procedure.html')
@app.route('/sms', methods=['POST'])
def receive_sms():
print(str.format("Received SMS: \n"
"To: {0}\n"
"From: {1}\n"
"Body: {2}\n",
str(flask.request.form['To']),
str(flask.request.form['From']),
str(flask.request.form['Body'])))
return '<Response></Response>'
if __name__ == '__main__':
app.debug = config.debug_mode
print(str.format("Debug Mode is: {0}", app.debug))
app.run()
|
Set Texture minification/magnification filters to Linear
This improves the quality of textures that need to be rendered at a
smaller
size.
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from PyQt5.QtGui import QOpenGLTexture, QImage
from UM.View.GL.Texture import Texture
from UM.View.GL.OpenGL import OpenGL
## Texture subclass using PyQt for the OpenGL implementation.
class QtTexture(Texture):
def __init__(self):
super().__init__()
self._qt_texture = QOpenGLTexture(QOpenGLTexture.Target2D)
self._qt_texture.setMinMagFilters(QOpenGLTexture.Linear, QOpenGLTexture.Linear)
self._gl = OpenGL.getInstance().getBindingsObject()
def getTextureId(self):
return self._qt_texture.textureId()
def bind(self, unit):
self._qt_texture.bind(unit)
def release(self, unit):
self._qt_texture.release(unit)
def load(self, file_name):
image = QImage(file_name).mirrored()
self._qt_texture.setData(image)
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from PyQt5.QtGui import QOpenGLTexture, QImage
from UM.View.GL.Texture import Texture
from UM.View.GL.OpenGL import OpenGL
## Texture subclass using PyQt for the OpenGL implementation.
class QtTexture(Texture):
def __init__(self):
super().__init__()
self._qt_texture = QOpenGLTexture(QOpenGLTexture.Target2D)
self._gl = OpenGL.getInstance().getBindingsObject()
def getTextureId(self):
return self._qt_texture.textureId()
def bind(self, unit):
self._qt_texture.bind(unit)
def release(self, unit):
self._qt_texture.release(unit)
def load(self, file_name):
image = QImage(file_name).mirrored()
self._qt_texture.setData(image)
|
Add comment to send func
|
import { HUB } from './hub';
import config from './config';
export function post (apiUrl, data) {
const payload = JSON.stringify(data);
const url = config.API_ROOT + apiUrl;
GM_xmlhttpRequest({
method: 'POST',
url: url,
headers: {
'Content-Type': 'application/json',
'X-Fbtrex-Version': config.VERSION,
'X-Fbtrex-Build': config.BUILD
},
data: payload,
onload: function (response) {
HUB.event('syncReponse', { url: url, response: response });
},
onerror: function (error) {
// We are parsing the payload because `data` will be modified by the handers/sync.js::sync function.
HUB.event('syncError', { url: url, data: JSON.parse(payload), error: error});
}
});
}
export const postTimeline = post.bind(null, 'timelines');
export const postDOM = post.bind(null, 'dom');
|
import { HUB } from './hub';
import config from './config';
export function post (apiUrl, data) {
const payload = JSON.stringify(data);
const url = config.API_ROOT + apiUrl;
GM_xmlhttpRequest({
method: 'POST',
url: url,
headers: {
'Content-Type': 'application/json',
'X-Fbtrex-Version': config.VERSION,
'X-Fbtrex-Build': config.BUILD
},
data: payload,
onload: function (response) {
HUB.event('syncReponse', { url: url, response: response });
},
onerror: function (error) {
HUB.event('syncError', { url: url, data: JSON.parse(payload), error: error});
}
});
}
export const postTimeline = post.bind(null, 'timelines');
export const postDOM = post.bind(null, 'dom');
|
Remove class namespace prefix and declare on top
|
<?php namespace App\Providers;
use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use App\Business;
class RouteServiceProvider extends ServiceProvider {
/**
* This namespace is applied to the controller routes in your routes file.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function boot(Router $router)
{
parent::boot($router);
$router->model('contact', 'App\Contact');
$router->model('business', 'App\Business');
$router->model('service', 'App\Service');
$router->bind('business_slug', function($business_slug)
{
return Business::where('slug', $business_slug)->first();
});
}
/**
* Define the routes for the application.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function map(Router $router)
{
$router->group(['namespace' => $this->namespace], function($router)
{
require app_path('Http/routes.php');
});
}
}
|
<?php namespace App\Providers;
use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
class RouteServiceProvider extends ServiceProvider {
/**
* This namespace is applied to the controller routes in your routes file.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function boot(Router $router)
{
parent::boot($router);
$router->model('contact', 'App\Contact');
$router->model('business', 'App\Business');
$router->model('service', 'App\Service');
$router->bind('business_slug', function($business_slug)
{
return \App\Business::where('slug', $business_slug)->first();
});
}
/**
* Define the routes for the application.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function map(Router $router)
{
$router->group(['namespace' => $this->namespace], function($router)
{
require app_path('Http/routes.php');
});
}
}
|
Add a bit of logging
|
/* eslint-env mocha */
const assert = require('assert')
const cm = require('cucumber-messages').io.cucumber.messages
const Gherkin = require('../src/Gherkin')
describe('Gherkin', () => {
it('parses gherkin from the file system', async () => {
const messages = await streamToArray(
Gherkin.fromPaths(['testdata/good/minimal.feature'])
)
assert.strictEqual(messages.length, 3)
})
it('parses gherkin from STDIN', async () => {
const source = cm.Source.fromObject({
uri: 'test.feature',
data: `Feature: Minimal
Scenario: minimalistic
Given the minimalism
`,
media: cm.Media.fromObject({
encoding: 'UTF-8',
contentType: 'text/x.cucumber.gherkin+plain',
}),
})
const messages = await streamToArray(Gherkin.fromSources([source]))
console.log('Messages', messages)
assert.strictEqual(messages.length, 3)
})
})
function streamToArray(readableStream) {
return new Promise((resolve, reject) => {
const items = []
readableStream.on('data', items.push.bind(items))
readableStream.on('error', reject)
readableStream.on('end', () => resolve(items))
})
}
|
/* eslint-env mocha */
const assert = require('assert')
const cm = require('cucumber-messages').io.cucumber.messages
const Gherkin = require('../src/Gherkin')
describe('Gherkin', () => {
it('parses gherkin from the file system', async () => {
const messages = await streamToArray(
Gherkin.fromPaths(['testdata/good/minimal.feature'])
)
assert.strictEqual(messages.length, 3)
})
it('parses gherkin from STDIN', async () => {
const source = cm.Source.fromObject({
uri: 'test.feature',
data: `Feature: Minimal
Scenario: minimalistic
Given the minimalism
`,
media: cm.Media.fromObject({
encoding: 'UTF-8',
contentType: 'text/x.cucumber.gherkin+plain',
}),
})
const messages = await streamToArray(Gherkin.fromSources([source]))
assert.strictEqual(messages.length, 3)
})
})
function streamToArray(readableStream) {
return new Promise((resolve, reject) => {
const items = []
readableStream.on('data', items.push.bind(items))
readableStream.on('error', reject)
readableStream.on('end', () => resolve(items))
})
}
|
Add unit test for LoginToken model
|
"""accounts app unittests
"""
from django.test import TestCase
from django.contrib.auth import get_user_model
from accounts.models import LoginToken
TEST_EMAIL = 'newvisitor@example.com'
class WelcomePageTest(TestCase):
"""Tests relating to the welcome_page view.
"""
def test_uses_welcome_template(self):
"""The root url should response with the welcome page template.
"""
response = self.client.get('/')
self.assertTemplateUsed(response, 'accounts/welcome.html')
class UserModelTest(TestCase):
"""Tests for passwordless user model.
"""
def test_user_valid_with_only_email(self):
"""Should not raise if the user model is happy with email only.
"""
user = get_user_model()(email=TEST_EMAIL)
user.full_clean()
def test_users_are_authenticated(self):
"""User objects should be authenticated for views/templates.
"""
user = get_user_model()()
self.assertTrue(user.is_authenticated())
class TokenModelTest(TestCase):
"""Tests for login token model.
"""
def test_unique_tokens_generated(self):
"""Two tokens generated should be unique.
"""
token1 = LoginToken(TEST_EMAIL)
token2 = LoginToken(TEST_EMAIL)
self.assertNotEqual(token1, token2)
|
"""accounts app unittests
"""
from django.test import TestCase
from django.contrib.auth import get_user_model
class WelcomePageTest(TestCase):
"""Tests relating to the welcome_page view.
"""
def test_uses_welcome_template(self):
"""The root url should response with the welcome page template.
"""
response = self.client.get('/')
self.assertTemplateUsed(response, 'accounts/welcome.html')
class UserModelTest(TestCase):
"""Tests for passwordless user model.
"""
def test_user_valid_with_only_email(self):
"""Should not raise if the user model is happy with email only
"""
user = get_user_model()(email='newvisitor@example.com')
user.full_clean()
def test_users_are_authenticated(self):
"""User objects should be authenticated for views/templates.
"""
user = get_user_model()()
self.assertTrue(user.is_authenticated())
|
Swap find_packages for a manual list
This is required to support PEP420 namespace packages.
|
"""Setuptools configuration for engine."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='asyncdef.engine',
version='0.1.0',
url='https://github.com/asyncdef/engine',
description='Core event loop implementation.',
author="Kevin Conway",
author_email="kevinjacobconway@gmail.com",
long_description=README,
license='Apache 2.0',
packages=[
'asyncdef',
'asyncdef.engine',
'asyncdef.engine.processors',
],
install_requires=[
'iface<2.0.0',
'asyncdef.interfaces<2.0.0',
],
extras_require={
'testing': [
'pep257',
'pep8',
'pyenchant',
'pyflakes',
'pylint',
'pytest',
'pytest-cov',
],
},
entry_points={
'console_scripts': [
],
},
include_package_data=True,
zip_safe=False,
)
|
"""Setuptools configuration for engine."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='asyncdef.engine',
version='0.1.0',
url='https://github.com/asyncdef/engine',
description='Core event loop implementation.',
author="Kevin Conway",
author_email="kevinjacobconway@gmail.com",
long_description=README,
license='Apache 2.0',
packages=find_packages(exclude=['build', 'dist', 'docs']),
install_requires=[
'iface<2.0.0',
'asyncdef.interfaces<2.0.0',
],
extras_require={
'testing': [
'pep257',
'pep8',
'pyenchant',
'pyflakes',
'pylint',
'pytest',
'pytest-cov',
],
},
entry_points={
'console_scripts': [
],
},
include_package_data=True,
zip_safe=False,
)
|
Make csv reader binary safe
|
<?php
declare(strict_types=1);
namespace Phpml\Dataset;
use Phpml\Exception\DatasetException;
class CsvDataset extends ArrayDataset
{
/**
* @param string $filepath
* @param int $features
* @param bool $headingRow
*
* @throws DatasetException
*/
public function __construct(string $filepath, int $features, bool $headingRow = true)
{
if (!file_exists($filepath)) {
throw DatasetException::missingFile(basename($filepath));
}
if (false === $handle = fopen($filepath, 'rb')) {
throw DatasetException::cantOpenFile(basename($filepath));
}
if ($headingRow) {
fgets($handle);
}
while (($data = fgetcsv($handle, 1000, ',')) !== false) {
$this->samples[] = array_slice($data, 0, $features);
$this->targets[] = $data[$features];
}
fclose($handle);
}
}
|
<?php
declare(strict_types=1);
namespace Phpml\Dataset;
use Phpml\Exception\DatasetException;
class CsvDataset extends ArrayDataset
{
/**
* @param string $filepath
* @param int $features
* @param bool $headingRow
*
* @throws DatasetException
*/
public function __construct(string $filepath, int $features, bool $headingRow = true)
{
if (!file_exists($filepath)) {
throw DatasetException::missingFile(basename($filepath));
}
if (false === $handle = fopen($filepath, 'r')) {
throw DatasetException::cantOpenFile(basename($filepath));
}
if ($headingRow) {
fgets($handle);
}
while (($data = fgetcsv($handle, 1000, ',')) !== false) {
$this->samples[] = array_slice($data, 0, $features);
$this->targets[] = $data[$features];
}
fclose($handle);
}
}
|
Add a constructor of component
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.tatsuyafw.camel.component.fluentd;
import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.impl.UriEndpointComponent;
import java.util.Map;
// [WIP]
public class FluentdComponent extends UriEndpointComponent {
public FluentdComponent() {
super(FluentdEndpoint.class);
}
public FluentdComponent(CamelContext context) {
super(context, FluentdEndpoint.class);
}
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
Endpoint endpoint = new FluentdEndpoint(uri, this);
return endpoint;
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.tatsuyafw.camel.component.fluentd;
import org.apache.camel.Endpoint;
import org.apache.camel.impl.UriEndpointComponent;
import java.util.Map;
// [WIP]
public class FluentdComponent extends UriEndpointComponent {
public FluentdComponent() {
super(FluentdEndpoint.class);
}
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
Endpoint endpoint = new FluentdEndpoint(uri, this);
return endpoint;
}
}
|
Write to png file in binary mode
|
import os
import base64
import tempfile
import subprocess
def convert_to_pdf(post):
path = tempfile.mkdtemp()
pagenr = 1
while True:
data = post.get('page_%s' % pagenr)
if data is None:
break
if not data.startswith('data:image/png;base64,'):
continue
prefix, data = data.split(',', 1)
filename = os.path.join(path, 'page_%03d.png' % pagenr)
with open(filename, 'wb') as f:
f.write(base64.b64decode(data))
pagenr += 1
filename = os.path.join(path, 'page_*')
output_file = os.path.join(path, 'final.pdf')
if subprocess.call(["convert", filename, output_file]) == 0:
return output_file
return None
|
import os
import base64
import tempfile
import subprocess
def convert_to_pdf(post):
path = tempfile.mkdtemp()
pagenr = 1
while True:
data = post.get('page_%s' % pagenr)
if data is None:
break
if not data.startswith('data:image/png;base64,'):
continue
prefix, data = data.split(',', 1)
filename = os.path.join(path, 'page_%03d.png' % pagenr)
open(filename, 'w').write(base64.b64decode(data))
pagenr += 1
filename = os.path.join(path, 'page_*')
output_file = os.path.join(path, 'final.pdf')
if subprocess.call(["convert", filename, output_file]) == 0:
return output_file
return None
|
Move message interval into a global constant
|
/**
* lib/app.js: main module for `bonta` CLI utility
*
* Copyright 2015, Sudaraka Wijesinghe <sudaraka@sudaraka.org>
*
* This program comes with ABSOLUTELY NO WARRANTY;
* This is free software, and you are welcome to redistribute it and/or modify
* it under the terms of the BSD 2-clause License. See the LICENSE file for more
* details.
*/
const
cluster = require('cluster'),
growl = require('growl'),
INTERVAL = 5; // In seconds
module.exports = () => {
'use strict';
if(cluster.isMaster) {
cluster.fork();
cluster.on('exit', () => {
setTimeout(() => {
cluster.fork();
}, INTERVAL * 1000);
});
}
else {
console.log('It\'s time to take a drink');
growl('It\'s time to take a drink');
cluster.worker.kill();
}
};
|
/**
* lib/app.js: main module for `bonta` CLI utility
*
* Copyright 2015, Sudaraka Wijesinghe <sudaraka@sudaraka.org>
*
* This program comes with ABSOLUTELY NO WARRANTY;
* This is free software, and you are welcome to redistribute it and/or modify
* it under the terms of the BSD 2-clause License. See the LICENSE file for more
* details.
*/
const
cluster = require('cluster'),
growl = require('growl');
module.exports = () => {
'use strict';
if(cluster.isMaster) {
cluster.fork();
cluster.on('exit', () => {
setTimeout(() => {
cluster.fork();
}, 5000);
});
}
else {
console.log('It\'s time to take a drink');
growl('It\'s time to take a drink');
cluster.worker.kill();
}
};
|
lisa: Remove Python < 3.6 version check
Since Python >= 3.6 is now mandatory, remove the check and the warning.
|
#! /usr/bin/env python3
import warnings
import os
import sys
from lisa.version import __version__
# Raise an exception when a deprecated API is used from within a lisa.*
# submodule. This ensures that we don't use any deprecated APIs internally, so
# they are only kept for external backward compatibility purposes.
warnings.filterwarnings(
action='error',
category=DeprecationWarning,
module=r'{}\..*'.format(__name__),
)
# When the deprecated APIs are used from __main__ (script or notebook), always
# show the warning
warnings.filterwarnings(
action='always',
category=DeprecationWarning,
module=r'__main__',
)
# Prevent matplotlib from trying to connect to X11 server, for headless testing.
# Must be done before importing matplotlib.pyplot or pylab
try:
import matplotlib
except ImportError:
pass
else:
if not os.getenv('DISPLAY'):
matplotlib.use('Agg')
# vim :set tabstop=4 shiftwidth=4 textwidth=80 expandtab
|
#! /usr/bin/env python3
import warnings
import os
import sys
from lisa.version import __version__
# Raise an exception when a deprecated API is used from within a lisa.*
# submodule. This ensures that we don't use any deprecated APIs internally, so
# they are only kept for external backward compatibility purposes.
warnings.filterwarnings(
action='error',
category=DeprecationWarning,
module=r'{}\..*'.format(__name__),
)
# When the deprecated APIs are used from __main__ (script or notebook), always
# show the warning
warnings.filterwarnings(
action='always',
category=DeprecationWarning,
module=r'__main__',
)
# Prevent matplotlib from trying to connect to X11 server, for headless testing.
# Must be done before importing matplotlib.pyplot or pylab
try:
import matplotlib
except ImportError:
pass
else:
if not os.getenv('DISPLAY'):
matplotlib.use('Agg')
if sys.version_info < (3, 6):
warnings.warn(
'Python 3.6 will soon be required to run LISA, please upgrade from {} to any version higher than 3.6'.format(
'.'.join(
map(str, tuple(sys.version_info)[:3])
),
),
DeprecationWarning,
)
# vim :set tabstop=4 shiftwidth=4 textwidth=80 expandtab
|
Connect person to user account
|
# Django
# Third-Party
from django.db.models.signals import pre_delete
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.conf import settings
# Local
from .models import User
from .tasks import activate_user
from .tasks import delete_account
@receiver(pre_delete, sender=User)
def user_pre_delete(sender, instance, **kwargs):
allowed = any([
settings.DJANGO_SETTINGS_MODULE == 'settings.prod',
settings.DJANGO_SETTINGS_MODULE == 'settings.dev',
])
if allowed:
if not instance.is_staff:
delete_account(instance)
return
@receiver(pre_save, sender=User)
def user_pre_save(sender, instance, **kwargs):
allowed = any([
settings.DJANGO_SETTINGS_MODULE == 'settings.prod',
settings.DJANGO_SETTINGS_MODULE == 'settings.dev',
])
if allowed:
if not instance.is_staff and not instance.person:
activate_user(instance)
return
|
# Django
# Third-Party
from django.db.models.signals import pre_delete
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.conf import settings
# Local
from .models import User
from .tasks import delete_account
@receiver(pre_delete, sender=User)
def user_pre_delete(sender, instance, **kwargs):
if settings.DJANGO_SETTINGS_MODULE == 'settings.prod':
if not instance.is_staff:
delete_account(instance)
return
@receiver(pre_save, sender=User)
def user_pre_save(sender, instance, **kwargs):
if settings.DJANGO_SETTINGS_MODULE == 'settings.prod':
if not instance.is_staff and not instance.person:
activate_user(instance)
return
|
Comment out the SemesterDetail log
|
import * as React from 'react'
import * as Immutable from 'immutable'
import {State} from 'react-router'
import {isCurrentSemester} from 'app/helpers/isCurrent'
let SemesterDetail = React.createClass({
mixins: [State],
propTypes: {
student: React.PropTypes.object.isRequired,
},
getInitialState() {
return {
year: null,
semester: null,
schedules: Immutable.List(),
}
},
componentWillReceiveProps(nextProps) {
let params = this.getParams()
let {year, semester} = params
let schedules = nextProps.student.schedules.filter(isCurrentSemester(year, semester))
// console.log('semesterDetail.componentWillReceiveProps', year, semester, nextProps.student.schedules.toJS())
this.setState({year, semester, schedules})
},
componentDidMount() {
this.componentWillReceiveProps(this.props)
},
render() {
return React.createElement('div',
{className: 'semester-detail'},
React.createElement('pre', null,
this.getPath(), '\n',
JSON.stringify(this.state.schedules.toJS(), null, 2)))
},
})
export default SemesterDetail
|
import * as React from 'react'
import * as Immutable from 'immutable'
import {State} from 'react-router'
import {isCurrentSemester} from 'app/helpers/isCurrent'
let SemesterDetail = React.createClass({
mixins: [State],
propTypes: {
student: React.PropTypes.object.isRequired,
},
getInitialState() {
return {
year: null,
semester: null,
schedules: Immutable.List(),
}
},
componentWillReceiveProps(nextProps) {
let params = this.getParams()
let {year, semester} = params
let schedules = nextProps.student.schedules.filter(isCurrentSemester(year, semester))
console.log('semester.componentWillReceiveProps', year, semester, nextProps.student.schedules.toJS())
this.setState({year, semester, schedules})
},
componentDidMount() {
this.componentWillReceiveProps(this.props)
},
render() {
return React.createElement('div',
{className: 'semester-detail'},
React.createElement('pre', null,
this.getPath(), '\n',
JSON.stringify(this.state.schedules.toJS(), null, 2)))
},
})
export default SemesterDetail
|
Make sure components receive all children properly
|
import Component from '../Component';
export default function patchMithril(global) {
const mo = global.m;
const m = function(comp, ...args) {
if (comp.prototype && comp.prototype instanceof Component) {
return comp.component(args[0], args.slice(1));
}
const node = mo.apply(this, arguments);
if (node.attrs.bidi) {
m.bidi(node, node.attrs.bidi);
}
if (node.attrs.route) {
node.attrs.href = node.attrs.route;
node.attrs.config = m.route;
delete node.attrs.route;
}
return node;
};
Object.keys(mo).forEach(key => m[key] = mo[key]);
/**
* Redraw only if not in the middle of a computation (e.g. a route change).
*
* @return {void}
*/
m.lazyRedraw = function() {
m.startComputation();
m.endComputation();
};
global.m = m;
}
|
import Component from '../Component';
export default function patchMithril(global) {
const mo = global.m;
const m = function(comp, ...args) {
if (comp.prototype && comp.prototype instanceof Component) {
return comp.component(...args);
}
const node = mo.apply(this, arguments);
if (node.attrs.bidi) {
m.bidi(node, node.attrs.bidi);
}
if (node.attrs.route) {
node.attrs.href = node.attrs.route;
node.attrs.config = m.route;
delete node.attrs.route;
}
return node;
};
Object.keys(mo).forEach(key => m[key] = mo[key]);
/**
* Redraw only if not in the middle of a computation (e.g. a route change).
*
* @return {void}
*/
m.lazyRedraw = function() {
m.startComputation();
m.endComputation();
};
global.m = m;
}
|
Fix TimedEvent sets GUID twice
TBR=nduca@chromium.org
BUG=
Review URL: https://codereview.appspot.com/12746044
git-svn-id: 3a56fcae908c7e16d23cb53443ea4795ac387cf2@896 0e6d7f2b-9903-5b78-7403-59d27f066143
|
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
'use strict';
base.require('base.guid');
base.require('tracing.trace_model.event');
/**
* @fileoverview Provides the TimedEvent class.
*/
base.exportTo('tracing.trace_model', function() {
/**
* A TimedEvent is the base type for any piece of data in the trace model with
* a specific start and duration.
*
* @constructor
*/
function TimedEvent(start) {
tracing.trace_model.Event.call(this);
this.start = start;
this.duration = 0;
}
TimedEvent.prototype = {
__proto__: tracing.trace_model.Event.prototype,
get end() {
return this.start + this.duration;
},
addBoundsToRange: function(range) {
range.addValue(this.start);
range.addValue(this.end);
}
};
return {
TimedEvent: TimedEvent
};
});
|
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
'use strict';
base.require('base.guid');
base.require('tracing.trace_model.event');
/**
* @fileoverview Provides the TimedEvent class.
*/
base.exportTo('tracing.trace_model', function() {
/**
* A TimedEvent is the base type for any piece of data in the trace model with
* a specific start and duration.
*
* @constructor
*/
function TimedEvent(start) {
tracing.trace_model.Event.call(this);
this.guid_ = base.GUID.allocate();
this.start = start;
this.duration = 0;
}
TimedEvent.prototype = {
__proto__: tracing.trace_model.Event.prototype,
get end() {
return this.start + this.duration;
},
addBoundsToRange: function(range) {
range.addValue(this.start);
range.addValue(this.end);
}
};
return {
TimedEvent: TimedEvent
};
});
|
Add internal implementation to increase performance
|
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var replace = require( '@stdlib/string/replace' );
// VARIABLES //
// The following regular expression should suffice to polyfill (most?) all environments.
var RE = /^[\u0020\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+([\S\s]*?)[\u0020\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+$/;
// MAIN //
/**
* Trim whitespace characters from beginning and end of a string.
*
* @param {string} str - input string
* @throws {TypeError} must provide a string primitive
* @returns {string} trimmed string
*
* @example
* var out = trim( ' Whitespace ' );
* // returns 'Whitespace'
*
* @example
* var out = trim( '\t\t\tTabs\t\t\t' );
* // returns 'Tabs'
*
* @example
* var out = trim( '\n\n\nNew Lines\n\n\n' ) );
* // returns 'New Lines'
*/
function trim( str ) {
if ( !isString( str ) ) {
throw new TypeError( 'invalid input argument. Must provide a string primitive. Value: `' + str + '`.' );
}
return replace( str, RE, '$1' );
} // end FUNCTION trim()
// EXPORTS //
module.exports = trim;
|
'use strict';
// MODULES //
var ltrim = require( '@stdlib/string/left-trim' );
var rtrim = require( '@stdlib/string/right-trim' );
// MAIN //
/**
* Trim whitespace characters from beginning and end of a string.
*
* @param {string} str - input string
* @throws {TypeError} must provide a string primitive
* @returns {string} trimmed string
*
* @example
* var out = trim( ' Whitespace ' );
* // returns 'Whitespace'
*
* @example
* var out = trim( '\t\t\tTabs\t\t\t' );
* // returns 'Tabs'
*
* @example
* var out = trim( '\n\n\nNew Lines\n\n\n' ) );
* // returns 'New Lines'
*/
function trim( str ) {
return ltrim( rtrim( str ) );
} // end FUNCTION trim()
// EXPORTS //
module.exports = trim;
|
Comment out python3 classifier for now.
|
import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='slugger',
version='0.2dev',
description=('Slugging done right. Tries to support close to 300'
'languages.'),
long_description=read('README.rst'),
keywords='slug slugging web i18n',
author='Marc Brinkmann',
author_email='git@marcbrinkmann.de',
url='http://github.com/mbr/slugger',
license='LGPLv2.1',
install_requires=['remember', 'logbook', 'unihandecode'],
include_package_data=True,
packages=find_packages(exclude=['glibcparse']),
classifiers=[
'Programming Language :: Python :: 2',
#'Programming Language :: Python :: 3',
]
)
|
import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='slugger',
version='0.2dev',
description=('Slugging done right. Tries to support close to 300'
'languages.'),
long_description=read('README.rst'),
keywords='slug slugging web i18n',
author='Marc Brinkmann',
author_email='git@marcbrinkmann.de',
url='http://github.com/mbr/slugger',
license='LGPLv2.1',
install_requires=['remember', 'logbook', 'unihandecode'],
include_package_data=True,
packages=find_packages(exclude=['glibcparse']),
classifiers=[
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
]
)
|
Fix travis error with SQLITE_LIMIT_VARIABLE_NUMBER
|
import sqlite3
def max_sql_variables():
"""Get the maximum number of arguments allowed in a query by the current
sqlite3 implementation.
Returns:
int: SQLITE_MAX_VARIABLE_NUMBER
"""
db = sqlite3.connect(':memory:')
cur = db.cursor()
cur.execute('CREATE TABLE t (test)')
low, high = 0, 100000
while (high - 1) > low:
guess = (high + low) // 2
query = 'INSERT INTO t VALUES ' + ','.join(['(?)' for _ in
range(guess)])
args = [str(i) for i in range(guess)]
try:
cur.execute(query, args)
except sqlite3.OperationalError as e:
if "too many SQL variables" in str(e):
high = guess
else:
return 999
else:
low = guess
cur.close()
db.close()
return low
|
import sqlite3
def max_sql_variables():
"""Get the maximum number of arguments allowed in a query by the current
sqlite3 implementation.
Returns:
int: SQLITE_MAX_VARIABLE_NUMBER
"""
db = sqlite3.connect(':memory:')
cur = db.cursor()
cur.execute('CREATE TABLE t (test)')
low, high = 0, 100000
while (high - 1) > low:
guess = (high + low) // 2
query = 'INSERT INTO t VALUES ' + ','.join(['(?)' for _ in
range(guess)])
args = [str(i) for i in range(guess)]
try:
cur.execute(query, args)
except sqlite3.OperationalError as e:
if "too many SQL variables" in str(e):
high = guess
else:
raise
else:
low = guess
cur.close()
db.close()
return low
|
Handle bad image files in example
|
import face_recognition
# Load the jpg files into numpy arrays
biden_image = face_recognition.load_image_file("biden.jpg")
obama_image = face_recognition.load_image_file("obama.jpg")
unknown_image = face_recognition.load_image_file("obama2.jpg")
# Get the face encodings for each face in each image file
# Since there could be more than one face in each image, it returns a list of encodings.
# But since I know each image only has one face, I only care about the first encoding in each image, so I grab index 0.
try:
biden_face_encoding = face_recognition.face_encodings(biden_image)[0]
obama_face_encoding = face_recognition.face_encodings(obama_image)[0]
unknown_face_encoding = face_recognition.face_encodings(unknown_image)[0]
except IndexError:
print("I wasn't able to locate any faces in at least one of the images. Check the image files. Aborting...")
quit()
known_faces = [
biden_face_encoding,
obama_face_encoding
]
# results is an array of True/False telling if the unknown face matched anyone in the known_faces array
results = face_recognition.compare_faces(known_faces, unknown_face_encoding)
print("Is the unknown face a picture of Biden? {}".format(results[0]))
print("Is the unknown face a picture of Obama? {}".format(results[1]))
print("Is the unknown face a new person that we've never seen before? {}".format(not True in results))
|
import face_recognition
# Load the jpg files into numpy arrays
biden_image = face_recognition.load_image_file("biden.jpg")
obama_image = face_recognition.load_image_file("obama.jpg")
unknown_image = face_recognition.load_image_file("obama2.jpg")
# Get the face encodings for each face in each image file
# Since there could be more than one face in each image, it returns a list of encodings.
# But since I know each image only has one face, I only care about the first encoding in each image, so I grab index 0.
biden_face_encoding = face_recognition.face_encodings(biden_image)[0]
obama_face_encoding = face_recognition.face_encodings(obama_image)[0]
unknown_face_encoding = face_recognition.face_encodings(unknown_image)[0]
known_faces = [
biden_face_encoding,
obama_face_encoding
]
# results is an array of True/False telling if the unknown face matched anyone in the known_faces array
results = face_recognition.compare_faces(known_faces, unknown_face_encoding)
print("Is the unknown face a picture of Biden? {}".format(results[0]))
print("Is the unknown face a picture of Obama? {}".format(results[1]))
print("Is the unknown face a new person that we've never seen before? {}".format(not True in results))
|
Add missing semicolon for ES7
|
'use strict';
import React, {
Platform,
StyleSheet,
View,
} from 'react-native';
import Layout from './Layout';
export default class TabBar extends React.Component {
static propTypes = {
...View.propTypes,
shadowStyle: View.propTypes.style,
};
render() {
return (
<View {...this.props} style={[styles.container, this.props.style]}>
{this.props.children}
<View style={[styles.shadow, this.props.shadowStyle]} />
</View>
);
}
}
let styles = StyleSheet.create({
container: {
backgroundColor: '#f8f8f8',
flexDirection: 'row',
justifyContent: 'space-around',
height: Layout.tabBarHeight,
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
},
shadow: {
backgroundColor: 'rgba(0, 0, 0, 0.25)',
height: Layout.pixel,
position: 'absolute',
left: 0,
right: 0,
top: Platform.OS === 'android' ? 0 : -Layout.pixel,
},
});
|
'use strict';
import React, {
Platform,
StyleSheet,
View,
} from 'react-native';
import Layout from './Layout';
export default class TabBar extends React.Component {
static propTypes = {
...View.propTypes,
shadowStyle: View.propTypes.style,
}
render() {
return (
<View {...this.props} style={[styles.container, this.props.style]}>
{this.props.children}
<View style={[styles.shadow, this.props.shadowStyle]} />
</View>
);
}
}
let styles = StyleSheet.create({
container: {
backgroundColor: '#f8f8f8',
flexDirection: 'row',
justifyContent: 'space-around',
height: Layout.tabBarHeight,
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
},
shadow: {
backgroundColor: 'rgba(0, 0, 0, 0.25)',
height: Layout.pixel,
position: 'absolute',
left: 0,
right: 0,
top: Platform.OS === 'android' ? 0 : -Layout.pixel,
},
});
|
Use module aifc instead of module aiff.
|
import sys
import readcd
import aifc
import AL
import CD
Error = 'cdaiff.Error'
def writeaudio(a, type, data):
a.writeframesraw(data)
def main():
if len(sys.argv) > 1:
a = aifc.open(sys.argv[1], 'w')
else:
a = aifc.open('@', 'w')
a.setsampwidth(AL.SAMPLE_16)
a.setnchannels(AL.STEREO)
a.setframerate(AL.RATE_44100)
r = readcd.Readcd().init()
for arg in sys.argv[2:]:
x = eval(arg)
try:
if len(x) <> 2:
raise Error, 'bad argument'
r.appendstretch(x[0], x[1])
except TypeError:
r.appendtrack(x)
r.setcallback(CD.AUDIO, writeaudio, a)
r.play()
a.close()
main()
|
import sys
import readcd
import aiff
import AL
import CD
Error = 'cdaiff.Error'
def writeaudio(a, type, data):
a.writesampsraw(data)
def main():
if len(sys.argv) > 1:
a = aiff.Aiff().init(sys.argv[1], 'w')
else:
a = aiff.Aiff().init('@', 'w')
a.sampwidth = AL.SAMPLE_16
a.nchannels = AL.STEREO
a.samprate = AL.RATE_44100
r = readcd.Readcd().init()
for arg in sys.argv[2:]:
x = eval(arg)
try:
if len(x) <> 2:
raise Error, 'bad argument'
r.appendstretch(x[0], x[1])
except TypeError:
r.appendtrack(x)
r.setcallback(CD.AUDIO, writeaudio, a)
r.play()
a.destroy()
main()
|
Simplify with forEach instead of for..in
|
"use strict";
var forge = require("node-forge");
var APNCertificate = require("./APNCertificate");
function apnCertificateFromPem(certData) {
if (!certData) {
return null;
}
var pemMessages;
try {
pemMessages = forge.pem.decode(certData);
}
catch (e) {
if (e.message.match("Invalid PEM formatted message.")) {
throw new Error("unable to parse certificate, not a valid PEM file");
}
}
var certificates = [];
pemMessages.forEach(function(message) {
if (!message.type.match(new RegExp("CERTIFICATE$"))) {
return;
}
var certAsn1 = forge.asn1.fromDer(message.body);
var forgeCertificate = forge.pki.certificateFromAsn1(certAsn1);
certificates.push(new APNCertificate(forgeCertificate));
});
return certificates;
}
module.exports = apnCertificateFromPem;
|
"use strict";
var forge = require("node-forge");
var APNCertificate = require("./APNCertificate");
function apnCertificateFromPem(certData) {
if (!certData) {
return null;
}
var pemMessages;
try {
pemMessages = forge.pem.decode(certData);
}
catch (e) {
if (e.message.match("Invalid PEM formatted message.")) {
throw new Error("unable to parse certificate, not a valid PEM file");
}
}
var certificates = [];
for(var i in pemMessages) {
var certMessage = pemMessages[i];
if (!certMessage.type.match(new RegExp("CERTIFICATE$"))) {
continue;
}
var certAsn1 = forge.asn1.fromDer(certMessage.body);
var forgeCertificate = forge.pki.certificateFromAsn1(certAsn1);
certificates.push(new APNCertificate(forgeCertificate));
}
return certificates;
}
module.exports = apnCertificateFromPem;
|
Fix relative path for plugin system
|
export default {
data () {
return {
plugins: {
list: ['Invoice'],
loaded: []
}
}
},
methods: {
loadPlugin (name) {
if (this.plugins.loaded.indexOf(name) > -1) {
return true
}
if (this.plugins.list.indexOf(name) < 0) {
return false
}
var vm = this
var script = document.createElement('script')
script.onload = function () {
vm.$options.components[name] = vm.$root.extend(window[name])
vm.plugins.loaded.push(name)
}
script.src = './static/plugins/' + name + '.js'
document.body.appendChild(script)
return false
}
}
}
|
export default {
data () {
return {
plugins: {
list: ['Invoice'],
loaded: []
}
}
},
methods: {
loadPlugin (name) {
if (this.plugins.loaded.indexOf(name) > -1) {
return true
}
if (this.plugins.list.indexOf(name) < 0) {
return false
}
var vm = this
var script = document.createElement('script')
script.onload = function () {
vm.$options.components[name] = vm.$root.extend(window[name])
vm.plugins.loaded.push(name)
}
script.src = '/static/plugins/' + name + '.js'
document.body.appendChild(script)
return false
}
}
}
|
Apply YQL change from GF-9695 and GF-9700 to JSONP sample too
Enyo-DCO-1.1-Signed-Off-By: Ben Combee (ben.combee@lge.com)
|
enyo.kind({
name: "enyo.sample.JsonpSample",
kind: "FittableRows",
classes: "enyo-fit jsonp-sample",
components: [
{kind: "FittableColumns", classes:"onyx-toolbar-inline", components: [
{content: "YQL: "},
{kind: "onyx.Input", name:"query", fit:true, value:'select * from weather.forecast where woeid in (select woeid from geo.places where text="san francisco, ca")'},
{kind: "onyx.Button", content:"Fetch", ontap:"fetch"}
]},
{kind: "onyx.TextArea", fit:true, classes:"jsonp-sample-source"}
],
fetch: function() {
var jsonp = new enyo.JsonpRequest({
url: "http://query.yahooapis.com/v1/public/yql?format=json",
callbackName: "callback"
});
// send parameters the remote service using the 'go()' method
jsonp.go({
q: this.$.query.getValue()
});
// attach responders to the transaction object
jsonp.response(this, "processResponse");
},
processResponse: function(inSender, inResponse) {
// do something with it
this.$.textArea.setValue(JSON.stringify(inResponse, null, 2));
}
});
|
enyo.kind({
name: "enyo.sample.JsonpSample",
kind: "FittableRows",
classes: "enyo-fit jsonp-sample",
components: [
{kind: "FittableColumns", classes:"onyx-toolbar-inline", components: [
{content: "YQL: "},
{kind: "onyx.Input", name:"query", fit:true, value:'select * from upcoming.events where woeid in (select woeid from geo.places where text="Sunnyvale, CA")'},
{kind: "onyx.Button", content:"Fetch", ontap:"fetch"}
]},
{kind: "onyx.TextArea", fit:true, classes:"jsonp-sample-source"}
],
fetch: function() {
var jsonp = new enyo.JsonpRequest({
url: "http://query.yahooapis.com/v1/public/yql?format=json",
callbackName: "callback"
});
// send parameters the remote service using the 'go()' method
jsonp.go({
q: this.$.query.getValue()
});
// attach responders to the transaction object
jsonp.response(this, "processResponse");
},
processResponse: function(inSender, inResponse) {
// do something with it
this.$.textArea.setValue(JSON.stringify(inResponse, null, 2));
}
});
|
Insert empty line at to fix patch.
gyptest-link-pdb.py was checked in without a blank line. This appears
to cause a patch issue with the try bots. This CL is only a whitespace
change to attempt to fix that problem.
SEE:
patching file test/win/gyptest-link-pdb.py
Hunk #1 FAILED at 26.
1 out of 1 hunk FAILED -- saving rejects to file test/win/gyptest-link-pdb.py.rej
===================================================================
--- test/win/gyptest-link-pdb.py (revision 1530)
+++ test/win/gyptest-link-pdb.py (working copy)
@@ -26,7 +26,9 @@
# Verify the specified PDB is created when ProgramDatabaseFile
# is provided.
- if not FindFile('name_set.pdb'):
+ if not FindFile('name_outdir.pdb'):
test.fail_test()
- else:
- test.pass_test()
\ No newline at end of file
+ if not FindFile('name_proddir.pdb'):
+ test.fail_test()
+
+ test.pass_test()
Index: test/win/linker-flags/program-database.gyp
TBR=bradnelson@chromium.org
Review URL: https://codereview.chromium.org/11368061
|
#!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that the 'Profile' attribute in VCLinker is extracted properly.
"""
import TestGyp
import os
import sys
if sys.platform == 'win32':
test = TestGyp.TestGyp(formats=['msvs', 'ninja'])
CHDIR = 'linker-flags'
test.run_gyp('program-database.gyp', chdir=CHDIR)
test.build('program-database.gyp', test.ALL, chdir=CHDIR)
def FindFile(pdb):
full_path = test.built_file_path(pdb, chdir=CHDIR)
return os.path.isfile(full_path)
# Verify the specified PDB is created when ProgramDatabaseFile
# is provided.
if not FindFile('name_set.pdb'):
test.fail_test()
else:
test.pass_test()
|
#!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that the 'Profile' attribute in VCLinker is extracted properly.
"""
import TestGyp
import os
import sys
if sys.platform == 'win32':
test = TestGyp.TestGyp(formats=['msvs', 'ninja'])
CHDIR = 'linker-flags'
test.run_gyp('program-database.gyp', chdir=CHDIR)
test.build('program-database.gyp', test.ALL, chdir=CHDIR)
def FindFile(pdb):
full_path = test.built_file_path(pdb, chdir=CHDIR)
return os.path.isfile(full_path)
# Verify the specified PDB is created when ProgramDatabaseFile
# is provided.
if not FindFile('name_set.pdb'):
test.fail_test()
else:
test.pass_test()
|
Increment route count on route
|
module.exports = (function() {
function chimneypot(opts) {
if (!opts || !isOptionsValid(opts)) {
throw new Error("Required options: port, path, secret");
}
this.options = {
port: opts.port,
path: opts.path,
secret: opts.secret
};
this.routeCount = 0;
}
function isOptionsValid(opts) {
if (opts.port === undefined || opts.path === undefined) {
return false;
}
// Non numbers and non-integers
if (Number(opts.port) !== opts.port || opts.port % 1 !== 0) {
return false;
}
return true;
}
function route(path, callback) {
this.routeCount++;
}
function listen() {
if (this.routeCount === 0) {
throw new Error("Routes must be applied before listening.");
}
}
chimneypot.prototype = {
constructor: chimneypot,
route: route,
listen: listen
};
return chimneypot;
})();
|
module.exports = (function() {
function chimneypot(opts) {
if (!opts || !isOptionsValid(opts)) {
throw new Error("Required options: port, path, secret");
}
this.options = {
port: opts.port,
path: opts.path,
secret: opts.secret
};
this.routeCount = 0;
}
function isOptionsValid(opts) {
if (opts.port === undefined || opts.path === undefined) {
return false;
}
// Non numbers and non-integers
if (Number(opts.port) !== opts.port || opts.port % 1 !== 0) {
return false;
}
return true;
}
function route(path, callback) {
}
function listen() {
if (this.routeCount === 0) {
throw new Error("Routes must be applied before listening.");
}
}
chimneypot.prototype = {
constructor: chimneypot,
route: route,
listen: listen
};
return chimneypot;
})();
|
Add test for null date.
|
package uk.ac.ebi.quickgo.annotation.download.converter.helpers;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.function.Function;
/**
* A home for the logic to format dates into Strings.
*
* @author Tony Wardell
* Date: 09/04/2018
* Time: 14:54
* Created with IntelliJ IDEA.
*/
public class DateConverter {
private DateConverter() {
}
private static final DateTimeFormatter YYYYMMDD_DATE_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd");
public static final Function<java.util.Date, String> toYYYYMMDD =
d -> d.toInstant().atZone(ZoneId.systemDefault()).format(YYYYMMDD_DATE_FORMAT);
public static String toYearMonthDay(Date date) {
return date != null ? toYYYYMMDD.apply(date) : "";
}
}
|
package uk.ac.ebi.quickgo.annotation.download.converter.helpers;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.function.Function;
/**
* A home for the logic to format dates into Strings.
*
* @author Tony Wardell
* Date: 09/04/2018
* Time: 14:54
* Created with IntelliJ IDEA.
*/
public class DateConverter {
private DateConverter() {
}
private static final DateTimeFormatter YYYYMMDD_DATE_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd");
public static final Function<java.util.Date, String> toYYYYMMDD =
d -> d.toInstant().atZone(ZoneId.systemDefault()).format(YYYYMMDD_DATE_FORMAT);
public static String toYearMonthDay(Date date) {
return toYYYYMMDD.apply(date);
}
}
|
refactor(app-tests): Merge fixture tests to reduce live servers and time
|
"""
Test fixtures.
:copyright: (c) 2017 Derek M. Frank
:license: MPL-2.0
"""
from flask import Flask # type: ignore
def test_simple_app(app):
"""Verify basic application."""
assert isinstance(app, Flask)
def test_simple_config(config):
"""Verify basic application configuration."""
assert isinstance(config, dict)
def test_webdriver_current_url(webdriver):
"""
Verify data URL.
Chrome: 'data:,'
Firefox: 'about:blank'
"""
assert webdriver.name in ['chrome', 'firefox']
assert webdriver.current_url in ['data:,', 'about:blank']
def test_webdriver_get_google(webdriver):
"""If google is down, something bad has happened."""
webdriver.get('http://google.com/')
assert 'Google' in webdriver.title
def test_page_proxies_webdriver(page):
"""Verify webdriver proxying."""
assert page.title == page.driver.title
assert page.current_url == page.driver.current_url
assert page.get == page.driver.get
|
"""
Test fixtures.
:copyright: (c) 2017 Derek M. Frank
:license: MPL-2.0
"""
from flask import Flask # type: ignore
def test_simple_app(app):
"""Verify basic application."""
assert isinstance(app, Flask)
def test_simple_config(config):
"""Verify basic application configuration."""
assert isinstance(config, dict)
def test_webdriver_current_url(webdriver):
"""
Verify data URL.
Chrome: 'data:,'
Firefox: 'about:blank'
"""
assert webdriver.current_url in ['data:,', 'about:blank']
def test_webdriver_valid_service(webdriver, services=('chrome', 'firefox')):
"""Make sure valid service is being used."""
assert webdriver.name in services
def test_webdriver_get_google(webdriver):
"""If google is down, something bad has happened."""
webdriver.get('http://google.com/')
assert 'Google' in webdriver.title
def test_page_proxies_webdriver(page):
"""Verify webdriver proxying."""
assert page.title == page.driver.title
assert page.current_url == page.driver.current_url
assert page.get == page.driver.get
|
Remove 'public' for interface methods
+ fix formatting issues
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.log;
import java.util.logging.Level;
/**
* This is the interface for controlling the log level of a
* component logger. This hides the actual controlling
* mechanism.
*
* @author arnej27959
*
*/
public interface LevelController {
/**
* should we actually publish a log message with the given Level now?
*/
boolean shouldLog(Level level);
/**
* return a string suitable for printing in a logctl file.
* the string must be be 4 * 8 characters, where each group
* of 4 characters is either " ON" or " OFF".
*/
String getOnOffString();
/**
* check the current state of logging and reflect it into the
* associated Logger instance, if available.
*/
void checkBack();
Level getLevelLimit();
}
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
/**
* This is the interface for controlling the log level of a
* component logger. This hides the actual controlling
* mechanism.
*
* @author arnej27959
*
*/
/**
* @author arnej27959
**/
package com.yahoo.log;
import java.util.logging.Level;
public interface LevelController {
/**
* should we actually publish a log message with the given Level now?
**/
public boolean shouldLog(Level level);
/**
* return a string suitable for printing in a logctl file.
* the string must be be 4 * 8 characters, where each group
* of 4 characters is either " ON" or " OFF".
**/
public String getOnOffString();
/**
* check the current state of logging and reflect it into the
* associated Logger instance, if available.
**/
public void checkBack();
public Level getLevelLimit();
}
|
Set default component group view to 1
|
<?php
/*
* This file is part of Cachet.
*
* (c) Alt Three Services Limited
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AlterTableComponentGroupsMakeColumnInteger extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('component_groups', function (Blueprint $table) {
$table->dropcolumn('collapsed');
});
Schema::table('component_groups', function (Blueprint $table) {
$table->integer('collapsed')->unsigned()->default(1)->after('order');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('component_groups', function (Blueprint $table) {
$table->boolean('collapsed')->change();
});
}
}
|
<?php
/*
* This file is part of Cachet.
*
* (c) Alt Three Services Limited
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AlterTableComponentGroupsMakeColumnInteger extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('component_groups', function (Blueprint $table) {
$table->dropcolumn('collapsed');
});
Schema::table('component_groups', function (Blueprint $table) {
$table->integer('collapsed')->unsigned()->default(2)->after('order');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('component_groups', function (Blueprint $table) {
$table->boolean('collapsed')->change();
});
}
}
|
Simplify CORS model and improve wording
|
# coding: utf-8
from django.db import models
from django.utils.translation import ugettext_lazy as _
class CorsModel(models.Model):
"""
A model with one field, `cors`, which specifies an allowed origin that must
exactly match `request.META.get('HTTP_ORIGIN')`
"""
cors = models.CharField(
max_length=255,
verbose_name=_('allowed origin'),
help_text=_(
'Must contain exactly the URI scheme, host, and port, e.g. '
'https://example.com:1234. Standard ports (80 for http and 443 '
'for https) may be omitted.'
)
)
def __str__(self):
return self.cors
class Meta:
verbose_name = _('allowed CORS origin')
|
# coding: utf-8
from django.db import models
from django.utils.translation import ugettext_lazy as _
def _set_cors_field_options(name, bases, attrs):
cls = type(name, bases, attrs)
# The `cors` field is already defined by `AbstractCorsModel`, but let's
# help folks out by giving it a more descriptive name and help text, which
# will both appear in the admin interface
cors_field = cls._meta.get_field('cors')
cors_field.verbose_name = _('allowed origin')
cors_field.help_text = _('You must include scheme (http:// or https://)')
return cls
class CorsModel(models.Model, metaclass=_set_cors_field_options):
"""
A model with one field, `cors`, which specifies an allowed origin that must
exactly match the host with its scheme. e.g. https://example.com
"""
cors = models.CharField(max_length=255)
def __str__(self):
return self.cors
class Meta:
verbose_name = _('allowed CORS origin')
|
Add result catch, better logging
|
'use strict'
const _ = require('lodash')
const Promise = require('bluebird')
var arr = []
module.exports = function loadAllPages (callFx, opts) {
opts['page'] = opts.page || 1
return Promise
.resolve(callFx(opts))
.then((result) => {
arr.push(result)
if (result && _.isFunction(result.nextPage)) {
opts.page = opts.page + 1
return loadAllPages(callFx, opts)
} else {
var newArr = arr
arr = []
return _.flatten(newArr)
}
})
.catch((err) => {
if (err) {
console.log('Failed to depaginate!\n', err)
console.log('Options:', opts)
console.trace()
}
})
}
|
'use strict'
const _ = require('lodash')
const Promise = require('bluebird')
var arr = []
module.exports = function loadAllPages (callFx, opts) {
opts['page'] = opts.page || 1
return Promise
.resolve(callFx(opts))
.then((result) => {
arr.push(result)
if (_.isFunction(result.nextPage)) {
opts.page = opts.page + 1
return loadAllPages(callFx, opts)
} else {
var newArr = arr
arr = []
return _.flatten(newArr)
}
}).catch((err) => {
if (err) {
console.log('Failed to depaginate\n', err)
}
})
}
|
Reset values of external link add-on to default when deleted.
|
# -*- coding: utf-8 -*-
from modularodm import fields
from modularodm.validators import (
URLValidator, MinValueValidator, MaxValueValidator
)
from modularodm.exceptions import ValidationValueError
from framework.mongo.utils import sanitized
from website.addons.base import AddonNodeSettingsBase
class ForwardNodeSettings(AddonNodeSettingsBase):
complete = True
url = fields.StringField(validate=URLValidator())
label = fields.StringField(validate=sanitized)
redirect_bool = fields.BooleanField(default=True, validate=True)
redirect_secs = fields.IntegerField(
default=15,
validate=[MinValueValidator(5), MaxValueValidator(60)]
)
@property
def link_text(self):
return self.label if self.label else self.url
def on_delete(self):
self.reset()
def reset(self):
self.url = None
self.label = None
self.redirect_bool = True
self.redirect_secs = 15
@ForwardNodeSettings.subscribe('before_save')
def validate_circular_reference(schema, instance):
"""Prevent node from forwarding to itself."""
if instance.url and instance.owner._id in instance.url:
raise ValidationValueError('Circular URL')
|
# -*- coding: utf-8 -*-
from modularodm import fields
from modularodm.validators import (
URLValidator, MinValueValidator, MaxValueValidator
)
from modularodm.exceptions import ValidationValueError
from framework.mongo.utils import sanitized
from website.addons.base import AddonNodeSettingsBase
class ForwardNodeSettings(AddonNodeSettingsBase):
complete = True
url = fields.StringField(validate=URLValidator())
label = fields.StringField(validate=sanitized)
redirect_bool = fields.BooleanField(default=True, validate=True)
redirect_secs = fields.IntegerField(
default=15,
validate=[MinValueValidator(5), MaxValueValidator(60)]
)
@property
def link_text(self):
return self.label if self.label else self.url
@ForwardNodeSettings.subscribe('before_save')
def validate_circular_reference(schema, instance):
"""Prevent node from forwarding to itself."""
if instance.url and instance.owner._id in instance.url:
raise ValidationValueError('Circular URL')
|
Fix a few unlikely issues with empty trade iterations (Binance)
|
const moment = require('moment');
const util = require('../../core/util.js');
const _ = require('lodash');
const log = require('../../core/log');
var config = util.getConfig();
var dirs = util.dirs();
var Fetcher = require(dirs.exchanges + 'binance');
util.makeEventEmitter(Fetcher);
var end = false;
var done = false;
var from = false;
var fetcher = new Fetcher(config.watch);
var fetch = () => {
fetcher.import = true;
fetcher.getTrades(from, handleFetch);
};
var handleFetch = (unk, trades) => {
if (trades.length > 0) {
var last = moment.unix(_.last(trades).date).utc();
var next = last.clone();
} else {
var next = from.clone().add(1, 'd');
log.debug('Import step returned no results, moving to the next 24h period');
}
if (from.add(1, 'd') >= end) {
fetcher.emit('done');
var endUnix = end.unix();
trades = _.filter(trades, t => t.date <= endUnix);
}
from = next.clone();
fetcher.emit('trades', trades);
};
module.exports = function(daterange) {
from = daterange.from.clone().utc();
end = daterange.to.clone().utc();
return {
bus: fetcher,
fetch: fetch,
};
};
|
const moment = require('moment');
const util = require('../../core/util.js');
const _ = require('lodash');
const log = require('../../core/log');
var config = util.getConfig();
var dirs = util.dirs();
var Fetcher = require(dirs.exchanges + 'binance');
util.makeEventEmitter(Fetcher);
var end = false;
var done = false;
var from = false;
var fetcher = new Fetcher(config.watch);
var fetch = () => {
fetcher.import = true;
fetcher.getTrades(from, handleFetch);
};
var handleFetch = (unk, trades) => {
if (trades.length > 0) {
var last = moment.unix(_.last(trades).date);
if (last < from) {
log.debug(
'Skipping data, they are before from date (probably a programming error)',
last.format()
);
return fetch();
}
}
var next = from.add(1, 'd');
if (next >= end) {
fetcher.emit('done');
var endUnix = end.unix();
trades = _.filter(trades, t => t.date <= endUnix);
}
from = next.clone();
fetcher.emit('trades', trades);
};
module.exports = function(daterange) {
from = daterange.from.clone();
end = daterange.to.clone();
return {
bus: fetcher,
fetch: fetch,
};
};
|
Use class instead of helper.
Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
|
<?php
namespace Orchestra\Database\Console\Migrations;
use Illuminate\Support\Collection;
trait Packages
{
/**
* The path to the packages directory (vendor).
*
* @var string
*/
protected $packagePath;
/**
* Set package path.
*
* @param string $packagePath
*
* @return $this
*/
public function setPackagePath(string $packagePath)
{
$this->packagePath = $packagePath;
return $this;
}
/**
* Get the path to the package migration directory.
*
* @param string $package
*
* @return array
*/
protected function getPackageMigrationPaths(string $package): array
{
$packagePath = $this->packagePath;
return Collection::make($this->option('path') ?: 'database/migrations')
->map(static function ($path) use ($packagePath, $package) {
return $packagePath.'/'.$package.'/'.$path;
})->all();
}
}
|
<?php
namespace Orchestra\Database\Console\Migrations;
trait Packages
{
/**
* The path to the packages directory (vendor).
*
* @var string
*/
protected $packagePath;
/**
* Set package path.
*
* @param string $packagePath
*
* @return $this
*/
public function setPackagePath(string $packagePath)
{
$this->packagePath = $packagePath;
return $this;
}
/**
* Get the path to the package migration directory.
*
* @param string $package
*
* @return array
*/
protected function getPackageMigrationPaths(string $package): array
{
$packagePath = $this->packagePath;
return \collect($this->option('path') ?: 'database/migrations')
->map(static function ($path) use ($packagePath, $package) {
return $packagePath.'/'.$package.'/'.$path;
})->all();
}
}
|
Throw exception when trying to access undefined property
|
<?php
namespace Fathomminds\Rest;
use Fathomminds\Rest\Contracts\ISchema;
use Fathomminds\Rest\Schema\TypeValidators\ValidatorFactory;
use Fathomminds\Rest\Exceptions\RestException;
abstract class Schema implements ISchema
{
public function __construct($object = null)
{
if ($object === null) {
return;
}
if (gettype($object) !== 'object') {
throw new RestException('Schema constructor expects object or null as parameter', [
'parameter' => $object,
]);
}
foreach (get_object_vars($object) as $name => $value) {
$this->{$name} = $value;
}
}
public function __get($name)
{
if (!isset($this->{$name})) {
throw new RestException() {
'Trying to access undefined property ' . $name,
[]
}
}
}
abstract public function schema();
}
|
<?php
namespace Fathomminds\Rest;
use Fathomminds\Rest\Contracts\ISchema;
use Fathomminds\Rest\Schema\TypeValidators\ValidatorFactory;
use Fathomminds\Rest\Exceptions\RestException;
abstract class Schema implements ISchema
{
public function __construct($object = null)
{
if ($object === null) {
return;
}
if (gettype($object) !== 'object') {
throw new RestException('Schema constructor expects object or null as parameter', [
'parameter' => $object,
]);
}
foreach (get_object_vars($object) as $name => $value) {
$this->{$name} = $value;
}
}
abstract public function schema();
}
|
Remove as fetch ones for now
|
const fs = require('fs')
const path = require('path')
const promisify = require('util').promisify
const writeFile = promisify(fs.writeFile)
const globby = require('globby')
;(async () => {
const files = await globby('./dist/**/*.{css,mjs}')
const headers = []
for (const file of files) {
const relative = path.relative('./dist', file)
switch (path.extname(relative)) {
case '.css':
headers.push(` Link: </${relative}>; rel=preload; as=style`)
break
case '.mjs':
headers.push(` Link: </${relative}>; rel=modulepreload; as=script`)
break
}
}
const lines = []
for (const path of ['/', '/posts/*']) {
lines.push(path, ...headers)
}
await writeFile('./dist/_headers', lines.join('\n'))
})()
|
const fs = require('fs')
const path = require('path')
const promisify = require('util').promisify
const writeFile = promisify(fs.writeFile)
const globby = require('globby')
;(async () => {
const files = await globby('./dist/**/*.{css,mjs}')
const headers = [' Link: </content/posts/index.json>; rel=preload; as=fetch']
for (const file of files) {
const relative = path.relative('./dist', file)
switch (path.extname(relative)) {
case '.css':
headers.push(` Link: </${relative}>; rel=preload; as=style`)
break
case '.mjs':
headers.push(` Link: </${relative}>; rel=modulepreload; as=script`)
break
}
}
const lines = []
for (const path of ['/', '/posts/*']) {
lines.push(path, ...headers)
}
const posts = await globby('./dist/content/posts/*.md')
for (const post of posts) {
const relative = path.relative('./dist', post)
const slug = path.basename(post, '.md')
lines.push(`/posts/${slug}`, ` Link: </${relative}>; rel=preload; as=fetch`)
}
await writeFile('./dist/_headers', lines.join('\n'))
})()
|
Correct handling of broken references
|
var escape = require('escape-latex');
var quotes = require('../replace-quotes');
var preprocess = function(input) {
return escape(quotes(input));
};
var blankLine = '{\\leavevmode \\vbox{\\hrule width5\\parindent}}';
module.exports = function run(element, numberStyle, conspicuous) {
if (typeof element === 'string') {
if (conspicuous) {
return '{\\bi ' + preprocess(element) + '}';
} else {
return preprocess(element);
}
} else if (element.hasOwnProperty('definition')) {
return '{``\\it ' + element.definition + '\'\'}';
} else if (element.hasOwnProperty('blank')) {
return blankLine + ' (' + preprocess(element.blank) + ')';
} else if (element.hasOwnProperty('heading')) {
var numbering = element.numbering;
var heading = element.heading;
if (
element.hasOwnProperty('broken') ||
element.hasOwnProperty('ambiguous')
) {
return (
blankLine +
' (reference to ``' + preprocess(heading) + '\'\')'
);
} else {
return preprocess('Section ' + numberStyle(numbering) + ' (' +
heading + ')');
}
} else {
throw new Error('Invalid type: ' + JSON.stringify(element));
}
};
|
var escape = require('escape-latex');
var quotes = require('../replace-quotes');
var preprocess = function(input) {
return escape(quotes(input));
};
var blankLine = '{\\leavevmode \\vbox{\\hrule width5\\parindent}}';
module.exports = function run(element, numberStyle, conspicuous) {
if (typeof element === 'string') {
if (conspicuous) {
return '{\\bi ' + preprocess(element) + '}';
} else {
return preprocess(element);
}
} else if (element.hasOwnProperty('definition')) {
return '{``\\it ' + element.definition + '\'\'}';
} else if (element.hasOwnProperty('blank')) {
return blankLine + ' (' + preprocess(element.blank) + ')';
} else if (element.hasOwnProperty('numbering')) {
var numbering = element.numbering;
var heading = element.heading;
if (
element.hasOwnProperty('broken') ||
element.hasOwnProperty('ambiguous')
) {
return (
blankLine +
' (reference to ``' + preprocess(heading) + '\'\')'
);
} else {
return preprocess('Section ' + numberStyle(numbering) + ' (' +
heading + ')');
}
} else {
throw new Error('Invalid type: ' + JSON.stringify(element));
}
};
|
Remove diacritics from search terms
|
import React from 'react';
import { Query } from 'react-apollo';
import { Switch, Route } from 'react-router-dom';
import { remove as removeDiacritics } from 'diacritics';
import parseRoute from 'react/util/parseRoute';
import searchUiStateQuery from 'apps/search/queries/searchUiState';
import SearchPage from 'react/pages/search/SearchPage';
export default () => (
<Switch>
<Route
path="/search/:term/:view?"
render={parseRoute(({ params }) => (
<Query query={searchUiStateQuery}>
{({ data, error }) => {
if (error) return error.message;
const { cookies } = data;
const view = params.view || cookies.view || 'all';
const term = removeDiacritics(params.term);
return (
<SearchPage
term={term}
view={view}
/>
);
}}
</Query>
))}
/>
</Switch>
);
|
import React from 'react';
import { Query } from 'react-apollo';
import { Switch, Route } from 'react-router-dom';
import parseRoute from 'react/util/parseRoute';
import searchUiStateQuery from 'apps/search/queries/searchUiState';
import SearchPage from 'react/pages/search/SearchPage';
export default () => (
<Switch>
<Route
path="/search/:term/:view?"
render={parseRoute(({ params }) => (
<Query query={searchUiStateQuery}>
{({ data, error }) => {
if (error) return error.message;
const { cookies } = data;
const view = params.view || cookies.view || 'all';
return (
<SearchPage
term={params.term}
view={view}
/>
);
}}
</Query>
))}
/>
</Switch>
);
|
Fix the build: latest bnd includes the most recent repoindex
Signed-off-by: Ferry Huberts <66e11f9f5d965b69497c7e73d5e808f8b13c1218@pelagic.nl>
|
package bndtools;
import java.io.File;
import java.io.OutputStream;
import java.io.Writer;
import java.util.Map;
import java.util.Set;
import org.osgi.framework.BundleContext;
import org.osgi.service.indexer.ResourceIndexer;
import org.osgi.util.tracker.ServiceTracker;
public class ResourceIndexerTracker extends ServiceTracker implements ResourceIndexer {
private final long timeout;
public ResourceIndexerTracker(BundleContext context, long timeout) {
super(context, ResourceIndexer.class.getName(), null);
this.timeout = timeout;
}
public void index(Set<File> files, OutputStream out, Map<String,String> config) throws Exception {
ResourceIndexer indexer = doGetIndexer();
indexer.index(files, out, config);
}
public void indexFragment(Set<File> files, Writer out, Map<String,String> config) throws Exception {
ResourceIndexer indexer = doGetIndexer();
indexer.indexFragment(files, out, config);
}
public IndexResult indexFile(File file) throws Exception {
ResourceIndexer indexer = doGetIndexer();
return indexer.indexFile(file);
}
private ResourceIndexer doGetIndexer() throws InterruptedException {
ResourceIndexer indexer = (ResourceIndexer) waitForService(timeout);
if (indexer == null)
throw new IllegalStateException("Resource indexer service not available.");
return indexer;
}
}
|
package bndtools;
import java.io.File;
import java.io.OutputStream;
import java.io.Writer;
import java.util.Map;
import java.util.Set;
import org.osgi.framework.BundleContext;
import org.osgi.service.indexer.ResourceIndexer;
import org.osgi.util.tracker.ServiceTracker;
public class ResourceIndexerTracker extends ServiceTracker implements ResourceIndexer {
private final long timeout;
public ResourceIndexerTracker(BundleContext context, long timeout) {
super(context, ResourceIndexer.class.getName(), null);
this.timeout = timeout;
}
public void index(Set<File> files, OutputStream out, Map<String,String> config) throws Exception {
ResourceIndexer indexer = doGetIndexer();
indexer.index(files, out, config);
}
public void indexFragment(Set<File> files, Writer out, Map<String,String> config) throws Exception {
ResourceIndexer indexer = doGetIndexer();
indexer.indexFragment(files, out, config);
}
private ResourceIndexer doGetIndexer() throws InterruptedException {
ResourceIndexer indexer = (ResourceIndexer) waitForService(timeout);
if (indexer == null)
throw new IllegalStateException("Resource indexer service not available.");
return indexer;
}
}
|
:bug: Fix SSR when importing svg
Babel-register & Node doesn’t know how to handle `.svg` files
|
import path from 'path';
import Express from 'express';
import compression from 'compression';
import bodyParser from 'body-parser';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import webpackConfig from '../webpack.dev.babel';
import universalRender from './universalRender';
const PORT = process.env.PORT || 3000;
// Initialize the Express App
const app = new Express();
// Run Webpack dev server in development mode
if (process.env.NODE_ENV === 'development') {
require.extensions['.svg'] = () => {};
const compiler = webpack(webpackConfig);
app.use(webpackDevMiddleware(compiler, {
noInfo: true,
publicPath: webpackConfig.output.publicPath,
stats: {
colors: true,
},
}));
app.use(webpackHotMiddleware(compiler));
}
// Apply body Parser and server public assets and routes
app.use(compression());
app.use(bodyParser.json({ limit: '20mb' }));
app.use(bodyParser.urlencoded({ limit: '20mb', extended: false }));
app.use(Express.static(path.resolve(__dirname, '../public')));
// Server Side Rendering
app.use(universalRender);
// start app
app.listen(PORT, (error) => {
if (!error) {
console.log(`YARIS started on => http://localhost:${PORT}`); // eslint-disable-line
}
});
export default app;
|
import path from 'path';
import Express from 'express';
import compression from 'compression';
import bodyParser from 'body-parser';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import webpackConfig from '../webpack.dev.babel';
import universalRender from './universalRender';
const PORT = process.env.PORT || 3000;
// Initialize the Express App
const app = new Express();
// Run Webpack dev server in development mode
if (process.env.NODE_ENV === 'development') {
const compiler = webpack(webpackConfig);
app.use(webpackDevMiddleware(compiler, {
noInfo: true,
publicPath: webpackConfig.output.publicPath,
stats: {
colors: true,
},
}));
app.use(webpackHotMiddleware(compiler));
}
// Apply body Parser and server public assets and routes
app.use(compression());
app.use(bodyParser.json({ limit: '20mb' }));
app.use(bodyParser.urlencoded({ limit: '20mb', extended: false }));
app.use(Express.static(path.resolve(__dirname, '../public')));
// Server Side Rendering
app.use(universalRender);
// start app
app.listen(PORT, (error) => {
if (!error) {
console.log(`YARIS started on => http://localhost:${PORT}`); // eslint-disable-line
}
});
export default app;
|
Fix incorrect require() path in Marked renderer
|
var escape = require('./util/escape')
var format = require('string-template');
var hljs = require('highlight.js');
var heading = require('./util/writeHeading');
var marked = require('marked');
var multiline = require('multiline');
var mdRenderer = new marked.Renderer();
var HTML_EXAMPLE_TEMPLATE = multiline(function() {/*
<div class="docs-code" data-docs-code>
<pre>
<code class="{0}">{1}</code>
</pre>
</div>
*/});
// Adds an anchor link to each heading created
mdRenderer.heading = heading;
// Adds special formatting to each code block created
// If the language is suffixed with "_example", the raw HTML is printed after the code sample, creating a live example.
mdRenderer.code = function(code, language) {
var extraOutput = '';
if (language === 'inky') {
return require('./util/buildInkySample')(code);
}
if (typeof language === 'undefined') language = 'html';
// If the language is *_example, live code will print out along with the sample
if (language.match(/_example$/)) {
extraOutput = format('\n\n<div class="docs-code-live">{0}</div>', [code]);
language = language.replace(/_example$/, '');
}
var renderedCode = hljs.highlight(language, code).value;
var output = format(HTML_EXAMPLE_TEMPLATE, [language, renderedCode]);
return output + extraOutput;
}
module.exports = mdRenderer;
|
var escape = require('./util/escape')
var format = require('string-template');
var hljs = require('highlight.js');
var heading = require('./util/writeHeading');
var marked = require('marked');
var multiline = require('multiline');
var mdRenderer = new marked.Renderer();
var HTML_EXAMPLE_TEMPLATE = multiline(function() {/*
<div class="docs-code" data-docs-code>
<pre>
<code class="{0}">{1}</code>
</pre>
</div>
*/});
// Adds an anchor link to each heading created
mdRenderer.heading = heading;
// Adds special formatting to each code block created
// If the language is suffixed with "_example", the raw HTML is printed after the code sample, creating a live example.
mdRenderer.code = function(code, language) {
var extraOutput = '';
if (language === 'inky') {
return require('./buildInkySample')(code);
}
if (typeof language === 'undefined') language = 'html';
// If the language is *_example, live code will print out along with the sample
if (language.match(/_example$/)) {
extraOutput = format('\n\n<div class="docs-code-live">{0}</div>', [code]);
language = language.replace(/_example$/, '');
}
var renderedCode = hljs.highlight(language, code).value;
var output = format(HTML_EXAMPLE_TEMPLATE, [language, renderedCode]);
return output + extraOutput;
}
module.exports = mdRenderer;
|
Allow circular references in dust templates.
|
var dust = require('dustjs-linkedin');
var _ = require('lodash');
dust.compiled = function(template) {
return this.template(template).compiled;
};
dust.src = function(template) {
return this.template(template).src;
};
dust.dependencies = function(template) {
var all = [],
check = [ dust.template(template).dependencies ],
deps,
prev = null;
while(deps = check.shift()) {
// allow circular reference in templates, mainly because of navigation-item.
// missing templates will be loaded asyncronously anyway
if(deps === prev) continue;//throw new Error('Circular reference in Dust templates.');
all = _.union(all, deps);
for(var i = 0; i < deps.length; i++) {
var dependencies = dust.template(deps[i]).dependencies;
if(dependencies) check.push(dependencies);
}
prev = deps;
}
return all;
};
dust.template = function(templateName) {
var template = this.templates[templateName];
if(!template) throw new Error('Template Not Found: ' + templateName);
return template;
};
|
var dust = require('dustjs-linkedin');
var _ = require('lodash');
dust.compiled = function(template) {
return this.template(template).compiled;
};
dust.src = function(template) {
return this.template(template).src;
};
dust.dependencies = function(template) {
var all = [],
check = [ dust.template(template).dependencies ],
deps,
prev = null;
while(deps = check.shift()) {
if(deps === prev) throw new Error('Circular reference in Dust templates.');
all = _.union(all, deps);
for(var i = 0; i < deps.length; i++) {
var dependencies = dust.template(deps[i]).dependencies;
if(dependencies) check.push(dependencies);
}
prev = deps;
}
return all;
};
dust.template = function(templateName) {
var template = this.templates[templateName];
if(!template) throw new Error('Template Not Found: ' + templateName);
return template;
};
|
Fix docstring, remove unused import
|
# -*- coding: utf-8 -*-
"""Factories for the S3 addon."""
from factory import SubFactory, Sequence
from tests.factories import ModularOdmFactory, UserFactory, ProjectFactory, ExternalAccountFactory
from website.addons.s3.model import (
S3UserSettings,
S3NodeSettings
)
class S3AccountFactory(ExternalAccountFactory):
provider = 's3'
provider_id = Sequence(lambda n: 'id-{0}'.format(n))
oauth_key = Sequence(lambda n: 'key-{0}'.format(n))
oauth_secret = Sequence(lambda n:'secret-{0}'.format(n))
display_name = 'S3 Fake User'
class S3UserSettingsFactory(ModularOdmFactory):
FACTORY_FOR = S3UserSettings
owner = SubFactory(UserFactory)
class S3NodeSettingsFactory(ModularOdmFactory):
FACTORY_FOR = S3NodeSettings
owner = SubFactory(ProjectFactory)
user_settings = SubFactory(S3UserSettingsFactory)
bucket = 'mock_bucket'
|
# -*- coding: utf-8 -*-
"""Factory boy factories for the Box addon."""
import mock
from datetime import datetime
from dateutil.relativedelta import relativedelta
from factory import SubFactory, Sequence
from tests.factories import ModularOdmFactory, UserFactory, ProjectFactory, ExternalAccountFactory
from website.addons.s3.model import (
S3UserSettings,
S3NodeSettings
)
class S3AccountFactory(ExternalAccountFactory):
provider = 's3'
provider_id = Sequence(lambda n: 'id-{0}'.format(n))
oauth_key = Sequence(lambda n: 'key-{0}'.format(n))
oauth_secret = Sequence(lambda n:'secret-{0}'.format(n))
display_name = 'S3 Fake User'
class S3UserSettingsFactory(ModularOdmFactory):
FACTORY_FOR = S3UserSettings
owner = SubFactory(UserFactory)
class S3NodeSettingsFactory(ModularOdmFactory):
FACTORY_FOR = S3NodeSettings
owner = SubFactory(ProjectFactory)
user_settings = SubFactory(S3UserSettingsFactory)
bucket = 'mock_bucket'
|
Make sure all fit feedmes get made
|
#!/usr/bin/env python
from glob import glob
import os
import re
def make_feedmes():
# One-time script
# Used to convert all the fit*.galfit files to fit*.diff
ids = glob('*/')
for id in ids:
os.chdir(id)
feedmes = glob('fit*diff')
# output starting models
for f in feedmes:
template = r'fit(.*)(\d)(n|m){0,1}([ugrizYJHK]{0,1})([abcde]{0,1})'
matchobj = re.match(template, f)
print matchobj.groups()
if matchobj.group(1) != 'A' or matchobj.group(5) != '':
cmd = matchobj.expand('patch -o \g<0>.galfit ../A\g<2>/'
'fitA\g<2>\g<4>.galfit \g<0>.diff')
print cmd
os.system(cmd)
os.chdir('..')
if __name__ =='__main__':
make_feedmes()
|
#!/usr/bin/env python
from glob import glob
import os
import re
def make_feedmes():
# One-time script
# Used to convert all the fit*.galfit files to fit*.diff
ids = glob('*/')
for id in ids:
os.chdir(id)
feedmes = glob('fit*diff')
# output starting models
for f in feedmes:
template = r'fit(.).*(\d)(n|m){0,1}([ugrizYJHK]{0,1})([abcde]{0,1})'
matchobj = re.match(template, f)
if matchobj.group(1) != 'A':
cmd = matchobj.expand('patch -o \g<0>.galfit ../A\g<2>/'
'fitA\g<2>\g<4>.galfit \g<0>.diff')
print cmd
os.system(cmd)
os.chdir('..')
if __name__ =='__main__':
make_feedmes()
|
Fix URLs for login/logout, and password changes.
|
import django.contrib.auth.views as auth_views
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles import views
admin.autodiscover()
urlpatterns = [
url(r'^login/*$', auth_views.LoginView.as_view(), name='login'),
url(r'^logout/$', auth_views.logout_then_login, name='logout_then_login'),
url(r'^changepassword/$', auth_views.PasswordChangeView.as_view(), name='password_change'),
url(r'^changepassword/done/$', auth_views.PasswordChangeDoneView.as_view(),
name='password_change_done'),
url(r'^', include('server.urls')),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', admin.site.urls),
url(r'^api/', include('api.v1.urls')),
url(r'^api/v1/', include('api.v1.urls')),
url(r'^api/v2/', include('api.v2.urls')),
url(r'^inventory/', include('inventory.urls')),
url(r'^search/', include('search.urls')),
url(r'^licenses/', include('licenses.urls')),
url(r'^catalog/', include('catalog.urls')),
url(r'^profiles/', include('profiles.urls')),
]
if settings.DEBUG:
urlpatterns.append(url(r'^static/(?P<path>.*)$', views.serve))
|
import django.contrib.auth.views as auth_views
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles import views
admin.autodiscover()
urlpatterns = [
url(r'^login/*$', auth_views.LoginView, name='login'),
url(r'^logout/$', auth_views.logout_then_login, name='logout_then_login'),
url(r'^changepassword/$', auth_views.PasswordChangeView, name='password_change'),
url(r'^changepassword/done/$', auth_views.PasswordChangeDoneView, name='password_change_done'),
url(r'^', include('server.urls')),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', admin.site.urls),
url(r'^api/', include('api.v1.urls')),
url(r'^api/v1/', include('api.v1.urls')),
url(r'^api/v2/', include('api.v2.urls')),
url(r'^inventory/', include('inventory.urls')),
url(r'^search/', include('search.urls')),
url(r'^licenses/', include('licenses.urls')),
url(r'^catalog/', include('catalog.urls')),
url(r'^profiles/', include('profiles.urls')),
]
if settings.DEBUG:
urlpatterns.append(url(r'^static/(?P<path>.*)$', views.serve))
|
Move process scheduling out of main.
|
# -*- coding: utf-8 -*-
import schedule
from feed import load_feed
from twitter import send_queued_tweet
import time
import os
RSS_FEED_LIST = os.environ['RSS_FEED_LIST']
LOAD_FEED_SECONDS = int(os.environ['LOAD_FEED_SECONDS'])
SEND_QUEUED_TWEET_SECONDS = int(os.environ['SEND_QUEUED_TWEET_SECONDS'])
def parse_feed_list(s):
parsed = s.split(',')
if parsed == ['']:
return []
else:
return parsed
schedule.every(LOAD_FEED_SECONDS).seconds.do(
load_feed, parse_feed_list(RSS_FEED_LIST))
schedule.every(SEND_QUEUED_TWEET_SECONDS).seconds.do(send_queued_tweet)
def main():
while True:
schedule.run_pending()
time.sleep(1)
def __main__():
main()
if __name__ == "__main__":
try:
__main__()
except (KeyboardInterrupt):
exit('Received Ctrl+C. Stopping application.', 1)
|
# -*- coding: utf-8 -*-
import schedule
from feed import load_feed
from twitter import send_queued_tweet
import time
import os
RSS_FEED_LIST = os.environ['RSS_FEED_LIST']
LOAD_FEED_SECONDS = int(os.environ['LOAD_FEED_SECONDS'])
SEND_QUEUED_TWEET_SECONDS = int(os.environ['SEND_QUEUED_TWEET_SECONDS'])
def parse_feed_list(s):
parsed = s.split(',')
if parsed == ['']:
return []
else:
return parsed
def main():
rsslist = parse_feed_list(RSS_FEED_LIST)
schedule.every(LOAD_FEED_SECONDS).seconds.do(load_feed, rsslist)
schedule.every(SEND_QUEUED_TWEET_SECONDS).seconds.do(send_queued_tweet)
while True:
schedule.run_pending()
time.sleep(1)
def __main__():
main()
if __name__ == "__main__":
try:
__main__()
except (KeyboardInterrupt):
exit('Received Ctrl+C. Stopping application.', 1)
|
Revert last commit and tiggers _count_attended_registration method when one registrations.state changes
|
# -*- encoding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in root directory
##############################################################################
from openerp import models, fields, api
class ResPartner(models.Model):
_inherit = 'res.partner'
registrations = fields.One2many(
string="Event registrations",
comodel_name='event.registration', inverse_name="partner_id")
registration_count = fields.Integer(
string='Event registrations number', compute='_count_registration',
store=True)
attended_registration_count = fields.Integer(
string='Event attended registrations number',
compute='_count_attended_registration', store=True)
@api.one
@api.depends('registrations')
def _count_registration(self):
self.registration_count = len(self.registrations)
@api.one
@api.depends('registrations.state')
def _count_attended_registration(self):
self.attended_registration_count = len(self.registrations.filtered(
lambda x: x.state == 'done'))
|
# -*- encoding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in root directory
##############################################################################
from openerp import models, fields, api
class ResPartner(models.Model):
_inherit = 'res.partner'
registrations = fields.One2many(
string="Event registrations",
comodel_name='event.registration', inverse_name="partner_id")
registration_count = fields.Integer(
string='Event registrations number', compute='_count_registration',
store=True)
attended_registration_count = fields.Integer(
string='Event attended registrations number',
compute='_count_registration', store=True)
@api.one
@api.depends('registrations')
def _count_registration(self):
self.registration_count = len(self.registrations)
self.attended_registration_count = len(self.registrations.filtered(
lambda x: x.state == 'done'))
|
Fix non-visible CREATOR in sample app
|
package nz.bradcampbell.paperparcel.java7example;
import nz.bradcampbell.paperparcel.AccessorName;
import nz.bradcampbell.paperparcel.PaperParcel;
import nz.bradcampbell.paperparcel.PaperParcelable;
import nz.bradcampbell.paperparcel.TypeAdapters;
import java.util.Date;
@PaperParcel
@TypeAdapters(DateTypeAdapter.class)
public final class State extends PaperParcelable {
public static final PaperParcelable.Creator<State> CREATOR = new PaperParcelable.Creator<>(State.class);
private final int count;
// Able to use a custom getter name as per the @AccessorMethod tag. By default, if "x" is the property name,
// PaperParcel will search for a method named "x()", "getX()", or "isX()"
@AccessorName("customGetterMethodName")
private final Date modificationDate;
public State(int count, Date modificationDate) {
this.count = count;
this.modificationDate = modificationDate;
}
public int getCount() {
return count;
}
public Date customGetterMethodName() {
return modificationDate;
}
}
|
package nz.bradcampbell.paperparcel.java7example;
import nz.bradcampbell.paperparcel.AccessorName;
import nz.bradcampbell.paperparcel.PaperParcel;
import nz.bradcampbell.paperparcel.PaperParcelable;
import nz.bradcampbell.paperparcel.TypeAdapters;
import java.util.Date;
@PaperParcel
@TypeAdapters(DateTypeAdapter.class)
public final class State extends PaperParcelable {
private static final PaperParcelable.Creator<State> CREATOR = new PaperParcelable.Creator<>(State.class);
private final int count;
// Able to use a custom getter name as per the @AccessorMethod tag. By default, if "x" is the property name,
// PaperParcel will search for a method named "x()", "getX()", or "isX()"
@AccessorName("customGetterMethodName")
private final Date modificationDate;
public State(int count, Date modificationDate) {
this.count = count;
this.modificationDate = modificationDate;
}
public int getCount() {
return count;
}
public Date customGetterMethodName() {
return modificationDate;
}
}
|
Improve JSON Tree directive code
|
(function(kopf, JSONTree) {
"use strict";
kopf.directive('kopfJsonTree',function($sce) {
var directive = {
restrict: 'E',
template:'<div class="json-tree" ng-bind-html="result"></div>',
scope: {
kopfBind: '='
},
link: function(scope, element, attrs, requires){
scope.$watch('kopfBind', function(value) {
var result;
if (value) {
try {
result = JSONTree.create(value);
} catch (invalidJsonError) {
result = invalidJsonError;
}
} else {
result = '';
}
scope.result = $sce.trustAsHtml(result);
});
}
};
return directive;
});
})(kopf, JSONTree);
|
(function(kopf, JSONTree) {
"use strict";
kopf.directive('kopfJsonTree',function() {
var directive = {
restrict: 'E',
template:'<div class="json-tree"></div>',
link: function(scope, element, attrs, requires){
var scopeAttr = attrs.kopfBind;
if(scopeAttr) {
scope.$watch(scopeAttr, function(value) {
if (value) {
try {
value = JSONTree.create(value);
} catch (invalidJsonError) {
value = invalidJsonError;
}
} else {
value = '';
}
element.html(value);
});
}
}
};
return directive;
});
})(kopf, JSONTree);
|
Fix the encode url for the browser in InfoPackage
|
import got from 'got'
import semver from 'semver'
import validate from 'validate-npm-package-name'
const exp = /^((@[^@\/]+)\/)?([^@\/]+)(@([^@\/]+))?$/
// Rename for PackageInfo
export default class InfoPackage {
constructor(info) {
const match = exp.exec(info)
if (!info || !match) {
this.isValid = false
return this.isValid
}
this.scope = match[2] || null
this.name = this.scope ? `${this.scope}/${match[3]}` : match[3]
this.isValid = validate(this.name).validForOldPackages
this.version = semver.valid(match[5], true)
this.tag = !this.version ? match[5] || 'latest' : null
}
get urlPackage() {
return `https://registry.npmjs.org/${encodeURIComponent(this.name)}`.toLowerCase()
}
async getInfo() {
if (this._info)
return this._info
// verify if the response is ok, if the package exits
const res = await got(this.urlPackage, {json: true})
const version = this.version ? this.version : res.body['dist-tags'][this.tag]
this._info = res.body.versions[version]
return this._info || Promise.reject('package version does not exist')
}
async getStream() {
const info = await this.getInfo()
return got.stream(info.dist.tarball)
}
}
|
import got from 'got'
import semver from 'semver'
import querystring from 'querystring'
import validate from 'validate-npm-package-name'
const exp = /^((@[^@\/]+)\/)?([^@\/]+)(@([^@\/]+))?$/
// Rename for PackageInfo
export default class InfoPackage {
constructor(info) {
const match = exp.exec(info)
if (!info || !match) {
this.isValid = false
return this.isValid
}
this.scope = match[2] || null
this.name = this.scope ? `${this.scope}/${match[3]}` : match[3]
this.isValid = validate(this.name).validForOldPackages
this.version = semver.valid(match[5], true)
this.tag = !this.version ? match[5] || 'latest' : null
}
get urlPackage() {
return `https://registry.npmjs.org/${querystring.escape(this.name)}`.toLowerCase()
}
async getInfo() {
if (this._info)
return this._info
// verify if the response is ok, if the package exits
const res = await got(this.urlPackage, {json: true})
const version = this.version ? this.version : res.body['dist-tags'][this.tag]
this._info = res.body.versions[version]
return this._info || Promise.reject('package version does not exist')
}
async getStream() {
const info = await this.getInfo()
return got.stream(info.dist.tarball)
}
}
|
Add channel root on set context data, sent to template
|
# -*- coding: utf-8 -*-
from django.utils import timezone
from opps.articles.models import ArticleBox, Article
def set_context_data(self, SUPER, **kwargs):
context = super(SUPER, self).get_context_data(**kwargs)
article = Article.objects.filter(
site=self.site,
channel_long_slug__in=self.channel_long_slug,
date_available__lte=timezone.now(),
published=True)
context['posts'] = article.filter(child_class='Post')[:self.limit]
context['albums'] = article.filter(child_class='Album')[:self.limit]
context['channel'] = {}
context['channel']['long_slug'] = self.long_slug
if self.channel:
context['channel']['level'] = self.channel.get_level()
context['channel']['root'] = self.channel.get_root()
context['articleboxes'] = ArticleBox.objects.filter(
channel__long_slug=self.long_slug)
if self.slug:
context['articleboxes'] = context['articleboxes'].filter(
article__slug=self.slug)
return context
|
# -*- coding: utf-8 -*-
from django.utils import timezone
from opps.articles.models import ArticleBox, Article
def set_context_data(self, SUPER, **kwargs):
context = super(SUPER, self).get_context_data(**kwargs)
article = Article.objects.filter(
site=self.site,
channel_long_slug__in=self.channel_long_slug,
date_available__lte=timezone.now(),
published=True)
context['posts'] = article.filter(child_class='Post')[:self.limit]
context['albums'] = article.filter(child_class='Album')[:self.limit]
context['channel'] = {}
context['channel']['long_slug'] = self.long_slug
if self.channel:
context['channel']['level'] = self.channel.get_level()
context['articleboxes'] = ArticleBox.objects.filter(
channel__long_slug=self.long_slug)
if self.slug:
context['articleboxes'] = context['articleboxes'].filter(
article__slug=self.slug)
return context
|
Rename task. Add templates folder to watch
|
var gulp = require('gulp'),
scssLint = require('sass-lint'),
sass = require('gulp-sass'),
sassdoc = require('sassdoc');
gulp.task('watch', function() {
gulp.watch(['tests/*.scss', 'sass/**/*.scss', 'templates/project/*.scss'], ['_build']);
});
gulp.task('doc', function() {
return gulp.src('sass/**/*.scss')
.pipe(sassdoc());
});
gulp.task('_build', function() {
// Build example project.
gulp.src('templates/project/screen.scss')
.pipe(sass())
.pipe(gulp.dest('templates/project/screen.css'));
});
gulp.task('lint', function() {
// Lint the piecss files.
var results = scssLint.lintFiles('sass/piecss/**/*.scss', {}, './.scss-lint.yml');
scssLint.outputResults(results, {}, './.scss-lint.yml');
// Lint the piecss tests.
results = scssLint.lintFiles('tests/*.scss', {}, './.scss-lint.yml');
scssLint.outputResults(results, {}, './.scss-lint.yml');
});
gulp.task('test', function() {
gulp.src('tests/*.scss')
.pipe(sass());
});
gulp.task('default', function() {
gulp.watch(['tests/*.scss', 'sass/**/*.scss'], ['test', 'lint', '_build']);
});
|
var gulp = require('gulp'),
scssLint = require('sass-lint'),
sass = require('gulp-sass'),
sassdoc = require('sassdoc');
gulp.task('watch', function() {
gulp.watch(['tests/*.scss', 'sass/**/*.scss'], ['_build']);
});
gulp.task('sassdoc', function() {
return gulp.src('sass/**/*.scss')
.pipe(sassdoc());
});
gulp.task('_build', function() {
// Build example project.
gulp.src('templates/project/screen.scss')
.pipe(sass())
.pipe(gulp.dest('templates/project/screen.css'));
});
gulp.task('lint', function() {
// Lint the piecss files.
var results = scssLint.lintFiles('sass/piecss/**/*.scss', {}, './.scss-lint.yml');
scssLint.outputResults(results, {}, './.scss-lint.yml');
// Lint the piecss tests.
results = scssLint.lintFiles('tests/*.scss', {}, './.scss-lint.yml');
scssLint.outputResults(results, {}, './.scss-lint.yml');
});
gulp.task('test', function() {
gulp.src('tests/*.scss')
.pipe(sass());
});
gulp.task('default', function() {
gulp.watch(['tests/*.scss', 'sass/**/*.scss'], ['test', 'lint', '_build']);
});
|
Use jQuery nomenclature (event => eventType)
|
/**
* Events.
*
* @mixin
* @namespace Bolt.events
*
* @param {Object} bolt - The Bolt module.
*/
(function (bolt) {
'use strict';
/*
* Bolt.events mixin container.
*
* @private
* @type {Object}
*/
var events = {};
/*
* Event broker object.
*
* @private
* @type {Object}
*/
var broker = $({});
/**
* Fires an event.
*
* @static
* @function fire
* @memberof Bolt.events
*
* @param {string} eventType - Event type
* @param {object} [parameter] - Additional parameters to pass along to the event handler
*/
events.fire = function (eventType, parameter) {
broker.triggerHandler(eventType, parameter);
};
/**
* Attach an event handler.
*
* @static
* @function on
* @memberof Bolt.events
*
* @param {string} eventType - Event type
* @param {function} handler - Event handler
*/
events.on = function (eventType, handler) {
broker.on(eventType, handler);
};
// Apply mixin container
bolt.events = events;
})(Bolt || {});
|
/**
* Events.
*
* @mixin
* @namespace Bolt.events
*
* @param {Object} bolt - The Bolt module.
*/
(function (bolt) {
'use strict';
/*
* Bolt.events mixin container.
*
* @private
* @type {Object}
*/
var events = {};
/*
* Event broker object.
*
* @private
* @type {Object}
*/
var broker = $({});
/**
* Fires an event.
*
* @static
* @function fire
* @memberof Bolt.events
*
* @param {string} event - Event type
* @param {object} [parameter] - Additional parameters to pass along to the event handler
*/
events.fire = function (event, parameter) {
broker.triggerHandler(event, parameter);
};
/**
* Attach an event handler.
*
* @static
* @function on
* @memberof Bolt.events
*
* @param {string} event - Event type
* @param {function} handler - Event handler
*/
events.on = function (event, handler) {
broker.on(event, handler);
};
// Apply mixin container
bolt.events = events;
})(Bolt || {});
|
Test fix for db.blob.dir changes
|
_test = {
setup: function() {
app.log("Application Config Setup");
},
teardown: function() {
app.log("Application Config Teardown");
},
app_settings_suite: {
setup: function() {
app.log("app_settings_suite setup");
},
teardown: function() {
app.log("app_settings_suite teardown");
},
test_dbdir_property: function() {
var dbDir = new axiom.SystemFile(app.dbDir);
var appDbdir = new axiom.SystemFile(app.serverDir + axiom.SystemFile.separator + app.getProperty("dbDir"));
Assert.assertEquals("test_dbdir_property() failed ", dbDir.getAbsolutePath(), appDbdir.getAbsolutePath());
},
test_event_log_property: function(){
var eventLog = new axiom.SystemFile(app.logDir + axiom.SystemFile.separator + app.getProperty("eventLog") + ".log");
Assert.assertEquals("test_event_log_property() failed ", eventLog.isFile(), true);
},
test_db_blob_dir_property: function() {
var db_blob_dir = new axiom.SystemFile(app.dir + axiom.SystemFile.separator + app.getProperty("db.blob.dir"));
Assert.assertEquals("test_db_blob_dir_property() failed ", db_blob_dir.isDirectory(), true);
},
}
}
|
_test = {
setup: function() {
app.log("Application Config Setup");
},
teardown: function() {
app.log("Application Config Teardown");
},
app_settings_suite: {
setup: function() {
app.log("app_settings_suite setup");
},
teardown: function() {
app.log("app_settings_suite teardown");
},
test_dbdir_property: function() {
var dbDir = new axiom.SystemFile(app.dbDir);
var appDbdir = new axiom.SystemFile(app.serverDir + axiom.SystemFile.separator + app.getProperty("dbDir"));
Assert.assertEquals("test_dbdir_property() failed ", dbDir.getAbsolutePath(), appDbdir.getAbsolutePath());
},
test_event_log_property: function(){
var eventLog = new axiom.SystemFile(app.logDir + axiom.SystemFile.separator + app.getProperty("eventLog") + ".log");
Assert.assertEquals("test_event_log_property() failed ", eventLog.isFile(), true);
},
test_db_blob_dir_property: function() {
var db_blob_dir = new axiom.SystemFile(app.serverDir + axiom.SystemFile.separator + app.getProperty("db.blob.dir"));
Assert.assertEquals("test_db_blob_dir_property() failed ", db_blob_dir.isDirectory(), true);
},
}
}
|
Remove @abstracmethod from archive method as well
|
#!/usr/bin/env python3
# Copyright 2014-2018 PUNCH Cyber Analytics Group
#
# 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.
from abc import abstractmethod
from typing import Optional
from stoq.data_classes import ArchiverResponse, Payload, RequestMeta
from stoq.plugins import BasePlugin
class ArchiverPlugin(BasePlugin):
def archive(
self, payload: Payload, request_meta: RequestMeta
) -> Optional[ArchiverResponse]:
pass
def get(self, task: str) -> Optional[Payload]:
pass
|
#!/usr/bin/env python3
# Copyright 2014-2018 PUNCH Cyber Analytics Group
#
# 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.
from abc import abstractmethod
from typing import Optional
from stoq.data_classes import ArchiverResponse, Payload, RequestMeta
from stoq.plugins import BasePlugin
class ArchiverPlugin(BasePlugin):
@abstractmethod
def archive(
self, payload: Payload, request_meta: RequestMeta
) -> Optional[ArchiverResponse]:
pass
def get(self, task: str) -> Optional[Payload]:
pass
|
Configure to run tests under pytest runner
|
import sys
import setuptools
py26_reqs = ['argparse', 'importlib'] if sys.version_info < (2,7) else []
setuptools.setup(
name='librarypaste',
use_hg_version=dict(increment='0.1'),
author='Jamie Turner',
author_email='jamie@jamwt.com',
url='http://bitbucket.org/chmullig/librarypaste/',
description='Simple pastebin',
long_description='Simple pastebin',
license='MIT',
packages=['librarypaste'],
package_dir={'librarypaste': 'librarypaste'},
include_package_data=True,
entry_points={
'console_scripts': [
'librarypaste=librarypaste.librarypaste:main',
],
},
install_requires=[
'pygments',
'Mako',
'cherrypy',
'PyYAML',
] + py26_reqs,
setup_requires=[
'hgtools',
'pytest-runner',
],
tests_require=[
'pytest',
],
zip_safe=False,
)
|
import sys
import setuptools
py26_reqs = ['argparse', 'importlib'] if sys.version_info < (2,7) else []
setuptools.setup(
name='librarypaste',
use_hg_version=dict(increment='0.1'),
author='Jamie Turner',
author_email='jamie@jamwt.com',
url='http://bitbucket.org/chmullig/librarypaste/',
description='Simple pastebin',
long_description='Simple pastebin',
license='MIT',
packages=['librarypaste'],
package_dir={'librarypaste': 'librarypaste'},
include_package_data=True,
entry_points={
'console_scripts': [
'librarypaste=librarypaste.librarypaste:main',
],
},
install_requires=[
'pygments',
'Mako',
'cherrypy',
'PyYAML',
] + py26_reqs,
setup_requires=[
'hgtools',
],
zip_safe=False,
)
|
Remove unnecessary Gingerbread check around strict mode
|
package com.wkovacs64.mtorch;
import android.app.Application;
import android.os.StrictMode;
import timber.log.Timber;
public final class CustomApplication extends Application {
@Override
public void onCreate() {
if (BuildConfig.DEBUG) {
// Initialize Timber logging library
Timber.plant(new Timber.DebugTree());
// Enable StrictMode for debug builds
enabledStrictMode();
}
super.onCreate();
}
private void enabledStrictMode() {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.penaltyDialog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectAll()
.penaltyLog()
.build());
}
}
|
package com.wkovacs64.mtorch;
import android.app.Application;
import android.os.Build;
import android.os.StrictMode;
import timber.log.Timber;
public final class CustomApplication extends Application {
@Override
public void onCreate() {
if (BuildConfig.DEBUG) {
// Initialize Timber logging library
Timber.plant(new Timber.DebugTree());
// Enable StrictMode for debug builds
enabledStrictMode();
}
super.onCreate();
}
private void enabledStrictMode() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.penaltyDialog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectAll()
.penaltyLog()
.build());
}
}
}
|
Update the next version to 4.4.0
|
# Author: Prabhu Ramachandran, Gael Varoquaux
# Copyright (c) 2004-2014, Enthought, Inc.
# License: BSD Style.
""" A tool for easy and interactive visualization of data.
Part of the Mayavi project of the Enthought Tool Suite.
"""
__version__ = '4.4.0'
__requires__ = [
'apptools',
'traits',
'traitsui',
]
__extras_require__ = {
'app': [
'envisage',
],
}
# Try forcing the use of wx 2.8 before any other import.
import sys
if not 'wx' in sys.modules:
try:
# Try forcing the use of wx 2.8
from traits.etsconfig.api import ETSConfig
if ETSConfig.toolkit in ('wx', ''):
import wxversion
wxversion.ensureMinimal('2.8')
except ImportError:
""" wxversion not installed """
|
# Author: Prabhu Ramachandran, Gael Varoquaux
# Copyright (c) 2004-2014, Enthought, Inc.
# License: BSD Style.
""" A tool for easy and interactive visualization of data.
Part of the Mayavi project of the Enthought Tool Suite.
"""
__version__ = '5.0.0'
__requires__ = [
'apptools',
'traits',
'traitsui',
]
__extras_require__ = {
'app': [
'envisage',
],
}
# Try forcing the use of wx 2.8 before any other import.
import sys
if not 'wx' in sys.modules:
try:
# Try forcing the use of wx 2.8
from traits.etsconfig.api import ETSConfig
if ETSConfig.toolkit in ('wx', ''):
import wxversion
wxversion.ensureMinimal('2.8')
except ImportError:
""" wxversion not installed """
|
Replace requestNamespace by xmlNamespace method
|
<?php
/**
* This file is part of the Zimbra API in PHP library.
*
* © Nguyen Van Nguyen <nguyennv1981@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Zimbra\Mail\Request;
use Zimbra\Soap\Request;
/**
* Base mail request class
*
* @package Zimbra
* @subpackage Mail
* @category Request
* @author Nguyen Van Nguyen - nguyennv1981@gmail.com
* @copyright Copyright © 2013 by Nguyen Van Nguyen.
*/
abstract class Base extends Request
{
/**
* Constructor method for base request
* @param string $value
* @return self
*/
public function __construct($value = null)
{
parent::__construct($value);
$this->xmlNamespace('urn:zimbraMail');
}
}
|
<?php
/**
* This file is part of the Zimbra API in PHP library.
*
* © Nguyen Van Nguyen <nguyennv1981@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Zimbra\Mail\Request;
use Zimbra\Soap\Request;
/**
* Base mail request class
*
* @package Zimbra
* @subpackage Mail
* @category Request
* @author Nguyen Van Nguyen - nguyennv1981@gmail.com
* @copyright Copyright © 2013 by Nguyen Van Nguyen.
*/
abstract class Base extends Request
{
/**
* Constructor method for base request
* @param string $value
* @return self
*/
public function __construct($value = null)
{
parent::__construct($value);
$this->requestNamespace('urn:zimbraMail');
}
}
|
Use the smart JSON serializer for BadRequest
|
package org.openstack.client.internals;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.module.SimpleModule;
import org.openstack.model.compute.Addresses;
import org.openstack.model.compute.BadRequest;
import org.openstack.model.compute.SecurityGroup;
import org.openstack.model.compute.SecurityGroupList;
import org.openstack.model.compute.Server;
import org.openstack.model.identity.Access;
public class OpenstackSerializationModule extends SimpleModule {
public OpenstackSerializationModule() {
super(OpenstackSerializationModule.class.getName(), new Version(1, 0, 0, null));
addSerializer(Addresses.class, new AddressesSerializer());
addDeserializer(Addresses.class, new AddressesDeserializer());
// Compute
installSmartDeserializer(SecurityGroup.class);
installSmartDeserializer(SecurityGroupList.class);
installSmartDeserializer(Server.class);
installSmartDeserializer(BadRequest.class);
// Keystone (Redux)
installSmartDeserializer(Access.class);
}
private <T> void installSmartDeserializer(Class<T> c) {
addDeserializer(c, new SmartDeserializer<T>(c));
}
}
|
package org.openstack.client.internals;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.module.SimpleModule;
import org.openstack.model.compute.Addresses;
import org.openstack.model.compute.SecurityGroup;
import org.openstack.model.compute.SecurityGroupList;
import org.openstack.model.compute.Server;
import org.openstack.model.identity.Access;
public class OpenstackSerializationModule extends SimpleModule {
public OpenstackSerializationModule() {
super(OpenstackSerializationModule.class.getName(), new Version(1, 0, 0, null));
addSerializer(Addresses.class, new AddressesSerializer());
addDeserializer(Addresses.class, new AddressesDeserializer());
// Compute
installSmartDeserializer(SecurityGroup.class);
installSmartDeserializer(SecurityGroupList.class);
installSmartDeserializer(Server.class);
// Keystone (Redux)
installSmartDeserializer(Access.class);
}
private <T> void installSmartDeserializer(Class<T> c) {
addDeserializer(c, new SmartDeserializer<T>(c));
}
}
|
Remove y-axis ticks and top x-axis ticks
|
import matplotlib.pyplot as plt
import numpy as np
def horizontal_bar(sorted_streaks, sort):
"""
Render a horizontal bar chart of streaks.
Values have already been sorted by sort.
"""
# Only extract those users & streaks for streaks that are non-zero:
users, streaks = zip(*[(user, streak.get(sort)) for user, streak
in sorted_streaks if streak.get(sort) > 0][::-1])
title = 'Top Contributors by {} Streak'.format(sort.title())
figure = plt.figure(num=None, figsize=(6, 15))
y_pos = np.arange(len(users)) # y-location of bars
print('y_pos', y_pos)
plt.barh(y_pos, streaks, facecolor='#5555EE', edgecolor='grey', align='center')
plt.yticks(y_pos, users)
plt.xlim([0, max(streaks) + 10]) # x-limits a bit wider at right
plt.subplots_adjust(left=0.25) # Wider left margin
plt.title(title)
ax = plt.gca()
ax.yaxis.set_ticks_position('none')
ax.xaxis.set_ticks_position('bottom')
for format in ('png', 'svg'):
figure.savefig('temp/top_{}.{}'.format(sort, format), format=format)
|
import matplotlib.pyplot as plt
import numpy as np
def horizontal_bar(sorted_streaks, sort):
"""
Render a horizontal bar chart of streaks.
Values have already been sorted by sort.
"""
# Only extract those users & streaks for streaks that are non-zero:
users, streaks = zip(*[(user, streak.get(sort)) for user, streak
in sorted_streaks if streak.get(sort) > 0][::-1])
title = 'Top Contributors by {} Streak'.format(sort.title())
figure = plt.figure(num=None, figsize=(6, 15))
y_pos = np.arange(len(users)) # y-location of bars
print('y_pos', y_pos)
plt.barh(y_pos, streaks, facecolor='#5555EE', edgecolor='grey', align='center')
plt.yticks(y_pos, users)
plt.xlim([0, max(streaks) + 10]) # x-limits a bit wider at right
plt.subplots_adjust(left=0.25) # Wider left margin
plt.title(title)
for format in ('png', 'svg'):
figure.savefig('temp/top_{}.{}'.format(sort, format), format=format)
|
Correct wrong constructor in test
|
<?php
namespace spec\Swarrot\Processor\Stack;
use Swarrot\Processor\InitializableInterface;
use Swarrot\Processor\TerminableInterface;
use Swarrot\Processor\ProcessorInterface;
use Swarrot\ParameterBag;
use Swarrot\AMQP\Message;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class StackedProcessorSpec extends ObjectBehavior
{
function it_is_initializable(ProcessorInterface $p1, InitializableProcessor $p2, TerminableProcessor $p3)
{
$this->beConstructedWith($p1, array($p2, $p3));
$this->shouldHaveType('Swarrot\Processor\Stack\StackedProcessor');
}
}
class InitializableProcessor implements InitializableInterface {
public function initialize(ParameterBag $bag) {}
}
class TerminableProcessor implements TerminableInterface {
public function terminate(ParameterBag $bag) {}
}
|
<?php
namespace spec\Swarrot\Processor\Stack;
use Swarrot\Processor\InitializableInterface;
use Swarrot\Processor\TerminableInterface;
use Swarrot\Processor\ProcessorInterface;
use Swarrot\ParameterBag;
use Swarrot\AMQP\Message;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class StackedProcessorSpec extends ObjectBehavior
{
function it_is_initializable(InitializableProcessor $p1, TerminableProcessor $p2)
{
$this->beConstructedWith(array($p1, $p2));
$this->shouldHaveType('Swarrot\Processor\Stack\StackedProcessor');
}
}
class InitializableProcessor implements InitializableInterface {
public function initialize(ParameterBag $bag) {}
}
class TerminableProcessor implements TerminableInterface {
public function terminate(ParameterBag $bag) {}
}
|
Add mobile app menu to Project Lists
Summary: Using Project lists on mobile is missing the query menu, this adds it.
Test Plan: test mobile layout, click menu, see query list
Reviewers: btrahan, epriestley
Reviewed By: epriestley
Subscribers: Korvin, epriestley
Differential Revision: https://secure.phabricator.com/D11010
|
<?php
final class PhabricatorProjectListController
extends PhabricatorProjectController {
private $queryKey;
public function shouldAllowPublic() {
return true;
}
public function willProcessRequest(array $data) {
$this->queryKey = idx($data, 'queryKey');
}
public function processRequest() {
$controller = id(new PhabricatorApplicationSearchController())
->setQueryKey($this->queryKey)
->setSearchEngine(new PhabricatorProjectSearchEngine())
->setNavigation($this->buildSideNavView());
return $this->delegateToController($controller);
}
public function buildApplicationMenu() {
return $this->buildSideNavView(true)->getMenu();
}
public function buildApplicationCrumbs() {
$crumbs = parent::buildApplicationCrumbs();
$can_create = $this->hasApplicationCapability(
ProjectCreateProjectsCapability::CAPABILITY);
$crumbs->addAction(
id(new PHUIListItemView())
->setName(pht('Create Project'))
->setHref($this->getApplicationURI('create/'))
->setIcon('fa-plus-square')
->setWorkflow(!$can_create)
->setDisabled(!$can_create));
return $crumbs;
}
}
|
<?php
final class PhabricatorProjectListController
extends PhabricatorProjectController {
private $queryKey;
public function shouldAllowPublic() {
return true;
}
public function willProcessRequest(array $data) {
$this->queryKey = idx($data, 'queryKey');
}
public function processRequest() {
$controller = id(new PhabricatorApplicationSearchController())
->setQueryKey($this->queryKey)
->setSearchEngine(new PhabricatorProjectSearchEngine())
->setNavigation($this->buildSideNavView());
return $this->delegateToController($controller);
}
public function buildApplicationCrumbs() {
$crumbs = parent::buildApplicationCrumbs();
$can_create = $this->hasApplicationCapability(
ProjectCreateProjectsCapability::CAPABILITY);
$crumbs->addAction(
id(new PHUIListItemView())
->setName(pht('Create Project'))
->setHref($this->getApplicationURI('create/'))
->setIcon('fa-plus-square')
->setWorkflow(!$can_create)
->setDisabled(!$can_create));
return $crumbs;
}
}
|
Complete a bit the application helpers tests
|
require('../test_helper');
require('../../app/helpers');
describe('Application helpers', () => {
before(() => {
I18n.load('en')
})
describe('#g', () => {
it('should generate a Glyphicon span', () => {
var output = Handlebars.helpers.g('foo');
assert(output instanceof Handlebars.SafeString);
assert.equal(output.string, '<span class="glyphicon glyphicon-foo"> </span>');
});
});
describe('#t', () => {
it('should delegate to the translation module', () => {
var output = Handlebars.helpers.t('meta.history');
assert.equal(output, 'History');
});
});
describe('#interpolate', () => {
it('should delegate to the i18n module passing the current scope', () => {
var context = { current: 10, total: 100 };
var output = Handlebars.helpers.interpolate('local.feedback.progress', {
data: { root: context }
});
assert.equal(output.string, '10 files processed out of 100.');
});
});
describe('pluralize', () => {
it('should delegate to the i18n module', () => {
var output = Handlebars.helpers.pluralize(10, 'album')
assert.equal(output, '10 albums')
})
})
describe('titleize', () => {
it('should delegate to the i18n module', () => {
var output = Handlebars.helpers.titleize('album')
assert.equal(output, 'Album')
})
})
});
|
require('../test_helper');
require('../../app/helpers');
describe('Application helpers', () => {
describe('#g', () => {
it('should generate a Glyphicon span', () => {
var output = Handlebars.helpers.g('foo');
assert(output instanceof Handlebars.SafeString);
assert.equal(output.string, '<span class="glyphicon glyphicon-foo"> </span>');
});
});
describe('#t', () => {
it('should delegate to the translation module', () => {
I18n.load('en');
var output = Handlebars.helpers.t('meta.history');
assert.equal(output, 'History');
});
});
describe('#interpolate', () => {
it('should delegate to the i18n module passing the current scope', () => {
I18n.load('en');
var context = { current: 10, total: 100 };
var output = Handlebars.helpers.interpolate('local.feedback.progress', {
data: { root: context }
});
assert.equal(output.string, '10 files processed out of 100.');
});
});
});
|
LIBRA-235: Add html and htm to list of acceptable files
|
(function() {
"use strict";
function initPage() {
var fileTypes = [
"csv",
"gif",
"htm",
"html",
"jpeg",
"jpg",
"mp3",
"mp4",
"pdf",
"png",
"tif",
"tiff",
"txt",
"xml"
];
var list = fileTypes.join(", ").toUpperCase();
var filter = fileTypes.join("|");
// Match any file that doesn't contain the above extensions.
var regex = new RegExp("(\.|\/)(" + filter + ")$", "i");
var acceptableFileTypeList = $(".acceptable-file-type-list");
acceptableFileTypeList.text(list);
var fileUploadButton = $('#fileupload');
if (fileUploadButton.length > 0) { // If we are on a page with file upload.
// Override curation_concern's file filter. We wait until we are sure that the curation_concern has initialized to make sure this gets called last.
setTimeout(function() {
fileUploadButton.fileupload(
'option',
'acceptFileTypes',
regex
);
}, 1000);
}
}
$(window).bind('page:change', function() {
initPage();
});
})();
|
(function() {
"use strict";
function initPage() {
var fileTypes = [
"csv",
"gif",
"jpeg",
"jpg",
"mp3",
"mp4",
"pdf",
"png",
"tif",
"tiff",
"txt",
"xml"
];
var list = fileTypes.join(", ").toUpperCase();
var filter = fileTypes.join("|");
// Match any file that doesn't contain the above extensions.
var regex = new RegExp("(\.|\/)(" + filter + ")$", "i");
var acceptableFileTypeList = $(".acceptable-file-type-list");
acceptableFileTypeList.text(list);
var fileUploadButton = $('#fileupload');
if (fileUploadButton.length > 0) { // If we are on a page with file upload.
// Override curation_concern's file filter. We wait until we are sure that the curation_concern has initialized to make sure this gets called last.
setTimeout(function() {
fileUploadButton.fileupload(
'option',
'acceptFileTypes',
regex
);
}, 1000);
}
}
$(window).bind('page:change', function() {
initPage();
});
})();
|
Drop messages instead of buffering
|
"use strict";
var stream = require("stream"),
util = require("util");
// TODO write this up as "how to merge readable streams"
var InfinitePassThrough = function() {
stream.Transform.call(this);
this._transform = function(chunk, encoding, callback) {
// only pass data on if something's listening and we're flowing
if (this._readableState.pipesCount > 0 &&
this._readableState.buffer.length === 0) {
this.push(chunk);
}
return callback();
};
setInterval(function() {
console.log("%d clients.", this._readableState.pipesCount);
}.bind(this), 5000).unref();
// overwrite Transform's end() function with a mangled version that doesn't
// actually end.
this.end = function(chunk, encoding, cb) {
if (typeof chunk === 'function') {
cb = chunk;
chunk = null;
encoding = null;
} else if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
cb = cb || function() {};
if (typeof chunk !== 'undefined' && chunk !== null) {
this.write(chunk, encoding);
}
return cb();
};
};
util.inherits(InfinitePassThrough, stream.Transform);
module.exports = InfinitePassThrough;
|
"use strict";
var stream = require("stream"),
util = require("util");
// TODO write this up as "how to merge readable streams"
var InfinitePassThrough = function() {
stream.Transform.call(this);
this._transform = function(chunk, encoding, callback) {
// only pass data on if something's listening
if (this._readableState.pipesCount > 0) {
this.push(chunk);
}
return callback();
};
// overwrite Transform's end() function with a mangled version that doesn't
// actually end.
this.end = function(chunk, encoding, cb) {
if (typeof chunk === 'function') {
cb = chunk;
chunk = null;
encoding = null;
} else if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
cb = cb || function() {};
if (typeof chunk !== 'undefined' && chunk !== null) {
this.write(chunk, encoding);
}
return cb();
};
};
util.inherits(InfinitePassThrough, stream.Transform);
module.exports = InfinitePassThrough;
|
[BPK-1053] Add elevation tokens under shadows
|
/*
* Backpack - Skyscanner's Design System
*
* Copyright 2017 Skyscanner 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.
*/
import React from 'react';
import TOKENS from 'bpk-tokens/tokens/base.raw.json';
import IOS_TOKENS from 'bpk-tokens/tokens/ios/base.raw.json';
import ANDROID_TOKENS from 'bpk-tokens/tokens/android/base.raw.json';
import DocsPageBuilder from './../../components/DocsPageBuilder';
import { getPlatformTokens } from './../../helpers/tokens-helper';
const ShadowsPage = () => <DocsPageBuilder
title="Shadows"
tokenMap={getPlatformTokens(
TOKENS, IOS_TOKENS, ANDROID_TOKENS, ({ category }) => ['box-shadows', 'elevation'].includes(category),
)}
/>;
export default ShadowsPage;
|
/*
* Backpack - Skyscanner's Design System
*
* Copyright 2017 Skyscanner 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.
*/
import React from 'react';
import TOKENS from 'bpk-tokens/tokens/base.raw.json';
import IOS_TOKENS from 'bpk-tokens/tokens/ios/base.raw.json';
import ANDROID_TOKENS from 'bpk-tokens/tokens/android/base.raw.json';
import DocsPageBuilder from './../../components/DocsPageBuilder';
import { getPlatformTokens } from './../../helpers/tokens-helper';
const ShadowsPage = () => <DocsPageBuilder
title="Shadows"
tokenMap={getPlatformTokens(TOKENS, IOS_TOKENS, ANDROID_TOKENS, ({ category }) => category === 'box-shadows')}
/>;
export default ShadowsPage;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.