text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Fix typo preventing the Django/Datadog integration from starting | from django.core.management.base import BaseCommand
from spinach.const import DEFAULT_QUEUE, DEFAULT_WORKER_NUMBER
from spinach.contrib.datadog import register_datadog_if_module_patched
from ...apps import spin
class Command(BaseCommand):
help = 'Run Spinach workers'
def add_arguments(self, parser):
parser.add_argument(
'--threads',
dest='threads',
type=int,
default=DEFAULT_WORKER_NUMBER,
help='Number of worker threads to launch'
)
parser.add_argument(
'--queue',
dest='queue',
default=DEFAULT_QUEUE,
help='Queue to consume'
)
parser.add_argument(
'--stop-when-queue-empty',
dest='stop_when_queue_empty',
default=False,
action='store_true',
help='Stop workers once the queue is empty'
)
def handle(self, *args, **options):
# Use the Datadog integration if Datadog is already used
# to trace Django.
register_datadog_if_module_patched(
'django',
namespace=spin.namespace
)
spin.start_workers(
number=options['threads'],
queue=options['queue'],
stop_when_queue_empty=options['stop_when_queue_empty']
)
| from django.core.management.base import BaseCommand
from spinach.const import DEFAULT_QUEUE, DEFAULT_WORKER_NUMBER
from spinach.contrib.datadog import register_datadog_if_module_patched
from ...apps import spin
class Command(BaseCommand):
help = 'Run Spinach workers'
def add_arguments(self, parser):
parser.add_argument(
'--threads',
dest='threads',
type=int,
default=DEFAULT_WORKER_NUMBER,
help='Number of worker threads to launch'
)
parser.add_argument(
'--queue',
dest='queue',
default=DEFAULT_QUEUE,
help='Queue to consume'
)
parser.add_argument(
'--stop-when-queue-empty',
dest='stop_when_queue_empty',
default=False,
action='store_true',
help='Stop workers once the queue is empty'
)
def handle(self, *args, **options):
# Use the Datadog integration if Datadog is already used
# to trace Django.
register_datadog_if_module_patched(
'django',
namespance=spin.namespace
)
spin.start_workers(
number=options['threads'],
queue=options['queue'],
stop_when_queue_empty=options['stop_when_queue_empty']
)
|
Change cartridge conf of advaced search dynamically | import { isFunction } from 'lodash';
import { setHeader } from 'focus-core/application';
module.exports = {
/**
* Updates the cartridge using the cartridgeConfiguration.
*/
_registerCartridge(props = this.props) {
const cartridgeConfiguration = this.cartridgeConfiguration || props.cartridgeConfiguration;
if (!isFunction(cartridgeConfiguration)) {
this.cartridgeConfiguration = () => ({});
console.warn(`
Your detail page does not have any cartrige configuration, this is not mandarory but recommended.
It should be a component attribute return by a function.
function cartridgeConfiguration(){
var cartridgeConfiguration = {
summary: {component: "A React Component", props: {id: this.props.id}},
cartridge: {component: "A React Component"},
actions: {components: "react actions"}
};
return cartridgeConfiguration;
}
`);
}
setHeader(cartridgeConfiguration());
},
/**
* Registers the cartridge upon mounting.
*/
componentWillMount() {
this._registerCartridge();
},
componentWillReceiveProps(nextProps) {
this._registerCartridge(nextProps);
}
};
| import {isFunction, isUndefined} from 'lodash/lang';
import {setHeader} from 'focus-core/application';
import {component as Empty} from '../../common/empty';
module.exports = {
/**
* Updates the cartridge using the cartridgeConfiguration.
*/
_registerCartridge() {
this.cartridgeConfiguration = this.cartridgeConfiguration || this.props.cartridgeConfiguration;
if (!isFunction(this.cartridgeConfiguration)) {
this.cartridgeConfiguration = () => ({});
console.warn(`
Your detail page does not have any cartrige configuration, this is not mandarory but recommended.
It should be a component attribute return by a function.
function cartridgeConfiguration(){
var cartridgeConfiguration = {
summary: {component: "A React Component", props: {id: this.props.id}},
cartridge: {component: "A React Component"},
actions: {components: "react actions"}
};
return cartridgeConfiguration;
}
`);
}
setHeader(this.cartridgeConfiguration());
},
/**
* Registers the cartridge upon mounting.
*/
componentWillMount() {
this._registerCartridge();
}
};
|
Fix shared event manager when used in ZF3 | <?php
namespace JwPersistentUser;
use JwPersistentUser\Service\CookieAuthenticationService;
use Zend\EventManager\EventInterface;
use Zend\EventManager\EventManager;
use Zend\ModuleManager\Feature;
use Zend\ServiceManager\ServiceManager;
class Module implements
Feature\ConfigProviderInterface,
Feature\BootstrapListenerInterface,
Feature\AutoloaderProviderInterface
{
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function onBootstrap(EventInterface $e)
{
/** @var EventManager $em */
$em = $e->getApplication()->getEventManager();
/** @var ServiceManager $sm */
$sm = $e->getApplication()->getServiceManager();
$request = $e->getApplication()->getRequest();
$response = $e->getApplication()->getResponse();
// Try to login from Cookie if applicable
$service = new CookieAuthenticationService($sm);
$service->setEventManager(new EventManager($em->getSharedManager()));
$service->loginFrom($request, $response);
}
public function getAutoloaderConfig()
{
return [
'Zend\Loader\StandardAutoloader' => [
'namespaces' => [
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
],
],
];
}
}
| <?php
namespace JwPersistentUser;
use JwPersistentUser\Service\CookieAuthenticationService;
use Zend\EventManager\EventInterface;
use Zend\EventManager\EventManager;
use Zend\ModuleManager\Feature;
use Zend\ServiceManager\ServiceManager;
class Module implements
Feature\ConfigProviderInterface,
Feature\BootstrapListenerInterface,
Feature\AutoloaderProviderInterface
{
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function onBootstrap(EventInterface $e)
{
/** @var EventManager $em */
$em = $e->getApplication()->getEventManager();
/** @var ServiceManager $sm */
$sm = $e->getApplication()->getServiceManager();
$request = $e->getApplication()->getRequest();
$response = $e->getApplication()->getResponse();
// Try to login from Cookie if applicable
$service = new CookieAuthenticationService($sm);
$service->setEventManager($em);
$service->loginFrom($request, $response);
}
public function getAutoloaderConfig()
{
return [
'Zend\Loader\StandardAutoloader' => [
'namespaces' => [
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
],
],
];
}
}
|
Allow injecting of cache through factory | <?php
namespace Addr;
use Alert\Reactor,
LibDNS\Decoder\DecoderFactory,
LibDNS\Encoder\EncoderFactory,
LibDNS\Messages\MessageFactory,
LibDNS\Records\QuestionFactory;
class ResolverFactory
{
/**
* Create a new resolver instance
*
* @param Reactor $reactor
* @param string $serverAddr
* @param int $serverPort
* @param int $requestTimeout
* @param Cache $cache
* @param string $hostsFilePath
* @return Resolver
*/
public function createResolver(
Reactor $reactor,
$serverAddr = null,
$serverPort = null,
$requestTimeout = null,
Cache $cache = null,
$hostsFilePath = null
) {
$nameValidator = new NameValidator;
$client = new Client(
$reactor,
new RequestBuilder(
new MessageFactory,
new QuestionFactory,
(new EncoderFactory)->create()
),
new ResponseInterpreter(
(new DecoderFactory)->create()
),
$serverAddr, $serverPort, $requestTimeout
);
$cache = $cache ?: new MemoryCache;
$hostsFile = new HostsFile($nameValidator, $hostsFilePath);
return new Resolver($reactor, $nameValidator, $client, $cache, $hostsFile);
}
}
| <?php
namespace Addr;
use Alert\Reactor,
LibDNS\Decoder\DecoderFactory,
LibDNS\Encoder\EncoderFactory,
LibDNS\Messages\MessageFactory,
LibDNS\Records\QuestionFactory;
class ResolverFactory
{
/**
* Create a new resolver instance
*
* @param Reactor $reactor
* @param string $serverAddr
* @param int $serverPort
* @param int $requestTimeout
* @param string $hostsFilePath
* @return Resolver
*/
public function createResolver(
Reactor $reactor,
$serverAddr = null,
$serverPort = null,
$requestTimeout = null,
$hostsFilePath = null
) {
$nameValidator = new NameValidator;
$client = new Client(
$reactor,
new RequestBuilder(
new MessageFactory,
new QuestionFactory,
(new EncoderFactory)->create()
),
new ResponseInterpreter(
(new DecoderFactory)->create()
),
$serverAddr, $serverPort, $requestTimeout
);
$cache = new MemoryCache;
$hostsFile = new HostsFile($nameValidator, $hostsFilePath);
return new Resolver($reactor, $nameValidator, $client, $cache, $hostsFile);
}
}
|
Add Javadoc to the generated private c-tor | /*
* Copyright 2020, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.code.gen.java;
import com.squareup.javapoet.MethodSpec;
import static javax.lang.model.element.Modifier.PRIVATE;
public final class EmptyPrivateCtor {
private static final MethodSpec PRIVATE_CTOR = privateCtorSpec();
private EmptyPrivateCtor() {
}
public static MethodSpec spec() {
return PRIVATE_CTOR;
}
private static MethodSpec privateCtorSpec() {
MethodSpec result = MethodSpec
.constructorBuilder()
.addModifiers(PRIVATE)
.addJavadoc("Prevents instantiation of this class.")
.build();
return result;
}
}
| /*
* Copyright 2020, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.code.gen.java;
import com.squareup.javapoet.MethodSpec;
import static javax.lang.model.element.Modifier.PRIVATE;
public final class EmptyPrivateCtor {
private static final MethodSpec PRIVATE_CTOR = privateCtorSpec();
private EmptyPrivateCtor() {
}
public static MethodSpec spec() {
return PRIVATE_CTOR;
}
private static MethodSpec privateCtorSpec() {
MethodSpec result = MethodSpec
.constructorBuilder()
.addModifiers(PRIVATE)
.build();
return result;
}
}
|
Fix error `AttributeError: 'module' object has no attribute 'PY2'` | from setuptools import setup
setup(
name='django-cacheops',
version='1.2',
author='Alexander Schepanovski',
author_email='[email protected]',
description='A slick ORM cache with automatic granular event-driven invalidation for Django.',
long_description=open('README.rst').read(),
url='http://github.com/Suor/django-cacheops',
license='BSD',
packages=[
'cacheops',
'cacheops.management',
'cacheops.management.commands',
'cacheops.templatetags'
],
install_requires=[
'django>=1.2',
'redis>=2.4.12',
'simplejson>=2.2.0',
'six>=1.4.0',
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Framework :: Django',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
| from setuptools import setup
setup(
name='django-cacheops',
version='1.2',
author='Alexander Schepanovski',
author_email='[email protected]',
description='A slick ORM cache with automatic granular event-driven invalidation for Django.',
long_description=open('README.rst').read(),
url='http://github.com/Suor/django-cacheops',
license='BSD',
packages=[
'cacheops',
'cacheops.management',
'cacheops.management.commands',
'cacheops.templatetags'
],
install_requires=[
'django>=1.2',
'redis>=2.4.12',
'simplejson>=2.2.0',
'six',
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Framework :: Django',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
|
Remove conditional in at rules | const MiniCSSExtractPlugin = require('mini-css-extract-plugin');
const styleFunctions = require('../../src/styles/functions/index.js');
module.exports = (env) => {
const styleLoaders = {
production: MiniCSSExtractPlugin.loader,
development: 'style-loader'
};
return {
test: /\.css$/,
exclude: /node_modules/,
use: [
{
loader: styleLoaders[env] // Creates style nodes from JS strings
},
{
loader: 'css-loader' // Translates CSS into CommonJS
},
{
loader: 'postcss-loader', // More CSS Plugins
options: {
postcssOptions: {
plugins: [
require('postcss-import'),
require('postcss-at-rules-variables')({ atRules: ['each', 'mixin', 'media'] }),
require('postcss-simple-vars'),
require('postcss-replace')({ pattern: /##/g, data: { replaceAll: '$' } }),
require('postcss-mixins'),
require('postcss-functions')({ functions: styleFunctions }),
require('postcss-each'),
require('postcss-calc'),
require('postcss-fontpath'),
require('postcss-nested'),
require('autoprefixer'),
require('postcss-discard-comments')
]
}
}
}
]
};
};
| const MiniCSSExtractPlugin = require('mini-css-extract-plugin');
const styleFunctions = require('../../src/styles/functions/index.js');
module.exports = (env) => {
const styleLoaders = {
production: MiniCSSExtractPlugin.loader,
development: 'style-loader'
};
return {
test: /\.css$/,
exclude: /node_modules/,
use: [
{
loader: styleLoaders[env] // Creates style nodes from JS strings
},
{
loader: 'css-loader' // Translates CSS into CommonJS
},
{
loader: 'postcss-loader', // More CSS Plugins
options: {
postcssOptions: {
plugins: [
require('postcss-import'),
require('postcss-at-rules-variables')({ atRules: ['for', 'if', 'else', 'each', 'mixin', 'media'] }),
require('postcss-simple-vars'),
require('postcss-replace')({ pattern: /##/g, data: { replaceAll: '$' } }),
require('postcss-mixins'),
require('postcss-functions')({ functions: styleFunctions }),
require('postcss-each'),
require('postcss-calc'),
require('postcss-fontpath'),
require('postcss-nested'),
require('autoprefixer'),
require('postcss-discard-comments')
]
}
}
}
]
};
};
|
Change default user image (when user is logged in) | define('app/views/user_menu', ['text!app/templates/user_menu.html', 'ember'],
/**
* User Menu View
*
* @returns Class
*/
function(user_menu_html) {
return Ember.View.extend({
/**
* Properties
*/
isNotCore: !IS_CORE,
accountUrl: URL_PREFIX + '/account',
template: Ember.Handlebars.compile(user_menu_html),
//TODO: change the logo_splash.png to user.png
gravatarURL: EMAIL && ('https://www.gravatar.com/avatar/' + md5(EMAIL) + '?d=' +
encodeURIComponent('https://mist.io/resources/images/user.png') +'&s=36'),
/**
*
* Actions
*
*/
actions: {
meClicked: function(){
$('#user-menu-popup').popup('open');
},
loginClicked: function() {
$('#user-menu-popup').popup('close');
Ember.run.later(function() {
Mist.loginController.open();
}, 300);
},
logoutClicked: function() {
Mist.loginController.logout();
}
}
});
}
);
| define('app/views/user_menu', ['text!app/templates/user_menu.html', 'ember'],
/**
* User Menu View
*
* @returns Class
*/
function(user_menu_html) {
return Ember.View.extend({
/**
* Properties
*/
isNotCore: !IS_CORE,
accountUrl: URL_PREFIX + '/account',
template: Ember.Handlebars.compile(user_menu_html),
//TODO: change the logo_splash.png to user.png
gravatarURL: EMAIL && ('https://www.gravatar.com/avatar/' + md5(EMAIL) + '?d=' +
encodeURIComponent('https://mist.io/resources/logo_splash.png') +'&s=36'),
/**
*
* Actions
*
*/
actions: {
meClicked: function(){
$('#user-menu-popup').popup('open');
},
loginClicked: function() {
$('#user-menu-popup').popup('close');
Ember.run.later(function() {
Mist.loginController.open();
}, 300);
},
logoutClicked: function() {
Mist.loginController.logout();
}
}
});
}
);
|
Change random for inset color | package com.jpardogo.android.listbuddies.models;
import android.content.Context;
import com.jpardogo.android.listbuddies.R;
import com.jpardogo.android.listbuddies.adapters.CustomizeSpinnersAdapter;
/**
* Created by jpardogo on 22/02/2014.
*/
public class KeyValuePair {
private String key;
private Object value;
public KeyValuePair(String key, Object value) {
this.key = key;
this.value = value;
}
public int getColor(Context context) {
int color = -1;
if (value instanceof CustomizeSpinnersAdapter.OptionTypes) {
switch ((CustomizeSpinnersAdapter.OptionTypes) value) {
case BLACK:
color = context.getResources().getColor(R.color.black);
break;
case INSET:
color = context.getResources().getColor(R.color.inset);
break;
}
} else {
throw new ClassCastException("Wrong type of value, the value must be CustomizeSpinnersAdapter.OptionTypes");
}
return color;
}
public String getKey() {
return key;
}
public int getScrollOption() {
return (Integer) value;
}
}
| package com.jpardogo.android.listbuddies.models;
import android.content.Context;
import android.graphics.Color;
import com.jpardogo.android.listbuddies.R;
import com.jpardogo.android.listbuddies.adapters.CustomizeSpinnersAdapter;
import java.util.Random;
/**
* Created by jpardogo on 22/02/2014.
*/
public class KeyValuePair {
private String key;
private Object value;
public KeyValuePair(String key, Object value) {
this.key = key;
this.value = value;
}
public int getColor(Context context) {
int color = -1;
if (value instanceof CustomizeSpinnersAdapter.OptionTypes) {
switch ((CustomizeSpinnersAdapter.OptionTypes) value) {
case BLACK:
color = context.getResources().getColor(R.color.black);
break;
case RANDOM:
Random rnd = new Random();
color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
break;
}
} else {
throw new ClassCastException("Wrong type of value, the value must be CustomizeSpinnersAdapter.OptionTypes");
}
return color;
}
public String getKey() {
return key;
}
public int getScrollOption() {
return (Integer) value;
}
}
|
Update user list when reaping. | #!/usr/bin/python
from redis import Redis
import time
from messages import addSystemMessage
STARTTIME = 1302231346
PING_PERIOD = 10
SEARCH_PERIOD = 1
def getTime():
return time.time() - STARTTIME
def getD(db, session, key, defaultValue=''):
v = db.hget("session-"+session, key)
if v is not None:
return v
return defaultValue
if __name__=='__main__':
db = Redis(host='localhost')
while True:
for dead in db.zrangebyscore('chats-alive', 0, getTime()-PING_PERIOD*2):
chat, session = dead.split('/') # FIXME: what if a user fucks this up by sticking a / in their uid?
db.zrem('chats-alive', dead)
db.srem(('chat-%s-sessions' % chat), session)
db.srem('sessions-chatting', session)
name = getD(db, session, 'name', 'UNKNOWN USER')
print 'dead', dead, name
addSystemMessage(db, chat, '%s\'s connection timed out. Please don\'t quit straight away; they could be back.' % (name), True)
for dead in db.zrangebyscore('searchers', 0, getTime()-SEARCH_PERIOD*2):
print 'reaping searcher', dead
db.zrem('searchers', dead)
time.sleep(1)
| #!/usr/bin/python
from redis import Redis
import time
from messages import addSystemMessage
STARTTIME = 1302231346
PING_PERIOD = 10
SEARCH_PERIOD = 1
def getTime():
return time.time() - STARTTIME
def getD(db, session, key, defaultValue=''):
v = db.hget("session-"+session, key)
if v is not None:
return v
return defaultValue
if __name__=='__main__':
db = Redis(host='localhost')
while True:
for dead in db.zrangebyscore('chats-alive', 0, getTime()-PING_PERIOD*2):
chat, session = dead.split('/') # FIXME: what if a user fucks this up by sticking a / in their uid?
db.zrem('chats-alive', dead)
db.srem(('chat-%s-sessions' % chat), session)
db.srem('sessions-chatting', session)
name = getD(db, session, 'name', 'UNKNOWN USER')
print 'dead', dead, name
addSystemMessage(db, chat, '%s\'s connection timed out. Please don\'t quit straight away; they could be back.' % (name))
for dead in db.zrangebyscore('searchers', 0, getTime()-SEARCH_PERIOD*2):
print 'reaping searcher', dead
db.zrem('searchers', dead)
time.sleep(1)
|
Update migration file to lose dependency from discarded migration file | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wagtaildocs', '0007_merge'),
('resources', '0006_add_field_for_absolute_slideshare_url'),
]
operations = [
migrations.RemoveField(
model_name='resource',
name='absolute_url',
),
migrations.RemoveField(
model_name='resource',
name='embed_thumbnail',
),
migrations.RemoveField(
model_name='resource',
name='embed_url',
),
migrations.AddField(
model_name='resource',
name='document',
field=models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.SET_NULL, blank=True, to='wagtaildocs.Document', max_length=500, null=True),
),
migrations.AddField(
model_name='resource',
name='thumbnail',
field=models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.SET_NULL, blank=True, to='core.AffixImage', max_length=500, null=True),
),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wagtaildocs', '0007_merge'),
('core', '0026_auto_20180306_1150'),
('resources', '0006_add_field_for_absolute_slideshare_url'),
]
operations = [
migrations.RemoveField(
model_name='resource',
name='absolute_url',
),
migrations.RemoveField(
model_name='resource',
name='embed_thumbnail',
),
migrations.RemoveField(
model_name='resource',
name='embed_url',
),
migrations.AddField(
model_name='resource',
name='document',
field=models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.SET_NULL, blank=True, to='wagtaildocs.Document', max_length=500, null=True),
),
migrations.AddField(
model_name='resource',
name='thumbnail',
field=models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.SET_NULL, blank=True, to='core.AffixImage', max_length=500, null=True),
),
]
|
Use setElement to set the view's element properly. | //----------------------------------------------------------------------------
// Copyright (C) 2013 The IPython Development Team
//
// Distributed under the terms of the BSD License. The full license is in
// the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------
//============================================================================
// ButtonWidget
//============================================================================
/**
* @module IPython
* @namespace IPython
**/
define(["notebook/js/widget"], function(widget_manager){
var ButtonWidgetModel = IPython.WidgetModel.extend({});
widget_manager.register_widget_model('ButtonWidgetModel', ButtonWidgetModel);
var ButtonView = IPython.WidgetView.extend({
// Called when view is rendered.
render : function(){
var that = this;
this.setElement($("<button />")
.addClass('btn')
.click(function() {
that.model.set('clicks', that.model.get('clicks') + 1);
that.model.update_other_views(that);
}));
this.update(); // Set defaults.
},
// Handles: Backend -> Frontend Sync
// Frontent -> Frontend Sync
update : function(){
var description = this.model.get('description');
description = description.replace(/ /g, ' ', 'm');
description = description.replace(/\n/g, '<br>\n', 'm');
if (description.length == 0) {
this.$el.html(' '); // Preserve button height
} else {
this.$el.html(description);
}
return IPython.WidgetView.prototype.update.call(this);
},
});
widget_manager.register_widget_view('ButtonView', ButtonView);
});
| //----------------------------------------------------------------------------
// Copyright (C) 2013 The IPython Development Team
//
// Distributed under the terms of the BSD License. The full license is in
// the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------
//============================================================================
// ButtonWidget
//============================================================================
/**
* @module IPython
* @namespace IPython
**/
define(["notebook/js/widget"], function(widget_manager){
var ButtonWidgetModel = IPython.WidgetModel.extend({});
widget_manager.register_widget_model('ButtonWidgetModel', ButtonWidgetModel);
var ButtonView = IPython.WidgetView.extend({
// Called when view is rendered.
render : function(){
var that = this;
this.$el = $("<button />")
.addClass('btn')
.click(function() {
that.model.set('clicks', that.model.get('clicks') + 1);
that.model.update_other_views(that);
});
this._ensureElement();
this.update(); // Set defaults.
},
// Handles: Backend -> Frontend Sync
// Frontent -> Frontend Sync
update : function(){
var description = this.model.get('description');
description = description.replace(/ /g, ' ', 'm');
description = description.replace(/\n/g, '<br>\n', 'm');
if (description.length == 0) {
this.$el.html(' '); // Preserve button height
} else {
this.$el.html(description);
}
return IPython.WidgetView.prototype.update.call(this);
},
});
widget_manager.register_widget_view('ButtonView', ButtonView);
});
|
Add tokenization and part of speech to the plugin.reply args dict. | define(
[
'jquery',
'pos'
], function(jquery, pos) {
var jQuery = jquery,
Pos = pos;
console.log("Pos",Pos);
return {
responsePlugins: [],
persistentStorage: {},
sessionStorage: {},
initializePlugins: function(pluginNames) {
var that = this;
// Walk through the list of plugins passed in and load it into
// memory. Add it to the list of plugins we can use
//
// TODO: hook an 'init' method in the plugins
jQuery.each(pluginNames, function(index, name) {
requirejs([name],
function(plugin) {
that.responsePlugins.push(plugin);
console.log("Loaded plugin: "+name);
});
});
},
handleQuery: function(input) {
var that = this;
var responses = {};
var tokens = new Pos.Lexer().lex(input);
var tags = new Pos.Tagger().tag(tokens);
var args = {
rawInput: input,
tokens: tokens,
pos: tags,
jQuery: jQuery,
sessionStorage: that.sessionStorage,
persistentStorage: that.persistentStorage
};
// TODO: do some NLP here
jQuery.each(that.responsePlugins, function(index, plugin) {
console.log("Asking "+plugin.name+" about "+input);
responses[plugin.name] = plugin.reply(args);
});
return responses;
}
}
});
| define(
['jquery'], function(jquery) {
var jQuery = jquery;
return {
responsePlugins: [],
persistentStorage: {},
sessionStorage: {},
initializePlugins: function(pluginNames) {
var that = this;
// Walk through the list of plugins passed in and load it into
// memory. Add it to the list of plugins we can use
//
// TODO: hook an 'init' method in the plugins
jQuery.each(pluginNames, function(index, name) {
requirejs([name],
function(plugin) {
that.responsePlugins.push(plugin);
console.log("Loaded plugin: "+name);
});
});
},
handleQuery: function(input) {
var that = this;
var responses = {};
// TODO: do some NLP here
jQuery.each(that.responsePlugins, function(index, plugin) {
console.log("Asking "+plugin.name+" about "+input);
responses[plugin.name] = plugin.reply({
rawInput: input,
jQuery: jQuery,
sessionStorage: that.sessionStorage,
persistentStorage: that.persistentStorage
});
});
return responses;
}
}
});
|
Fix memory cache lookup handling | <?php
namespace Addr;
class MemoryCache implements Cache
{
/**
* Mapped names stored in the cache
*
* @var array
*/
private $data = [
AddressModes::INET4_ADDR => [],
AddressModes::INET6_ADDR => [],
];
/**
* Look up an entry in the cache
*
* @param string $name
* @param int $type
* @param callable $callback
*/
public function resolve($name, $type, callable $callback)
{
if (!isset($this->data[$type][$name]) || $this->data[$type][$name][1] < time()) {
unset($this->data[$type][$name]);
$callback(null);
} else {
$callback($this->data[$type][$name][0]);
}
}
/**
* Store an entry in the cache
*
* @param string $name
* @param string $addr
* @param int $type
* @param int $ttl
*/
public function store($name, $addr, $type, $ttl)
{
$this->data[$type][$name] = [$addr, time() + $ttl];
}
/**
* Remove expired records from the cache
*/
public function collectGarbage()
{
$now = time();
foreach ([AddressModes::INET4_ADDR, AddressModes::INET6_ADDR] as $type) {
while (list($name, $data) = each($this->data[$type])) {
if ($data[1] < $now) {
unset($this->data[$type][$name]);
}
}
}
}
}
| <?php
namespace Addr;
class MemoryCache implements Cache
{
/**
* Mapped names stored in the cache
*
* @var array
*/
private $data = [
AddressModes::INET4_ADDR => [],
AddressModes::INET6_ADDR => [],
];
/**
* Look up an entry in the cache
*
* @param string $name
* @param int $type
* @param callable $callback
*/
public function resolve($name, $type, callable $callback)
{
if (isset($this->data[$type][$name])) {
if ($this->data[$type][$name][1] >= time()) {
$callback($this->data[$type][$name][0]);
}
unset($this->data[$type][$name]);
}
$callback($this->data[$type][$name][0]);
}
/**
* Store an entry in the cache
*
* @param string $name
* @param string $addr
* @param int $type
* @param int $ttl
*/
public function store($name, $addr, $type, $ttl)
{
$this->data[$type][$name] = [$addr, time() + $ttl];
}
/**
* Remove expired records from the cache
*/
public function collectGarbage()
{
$now = time();
foreach ([AddressModes::INET4_ADDR, AddressModes::INET6_ADDR] as $type) {
while (list($name, $data) = each($this->data[$type])) {
if ($data[1] < $now) {
unset($this->data[$type][$name]);
}
}
}
}
}
|
Add dismiss method for progress dialog on builder | package com.kogimobile.android.baselibrary.app.busevents;
/**
* @author Julian Cardona on 7/11/14.
*/
public class EventProgressDialog {
public static Builder getBuilder() {
return new Builder();
}
private boolean show = true;
private String progressDialogMessage = "";
private EventProgressDialog(Builder builder){
this.show = builder.show;
this.progressDialogMessage = builder.message;
}
public boolean isShown() {
return show;
}
public String getProgressDialogMessage() {
return progressDialogMessage;
}
public static class Builder {
private boolean show;
private String message;
public Builder withShow(boolean show) {
this.show = show;
return this;
}
public Builder withMessage(String message) {
this.message = message;
return this;
}
public Builder dismiss(){
this.show = false;
return this;
}
public EventProgressDialog build() {
return new EventProgressDialog(this);
}
}
/**
*
* @deprecated Please use builder pattern
*/
@Deprecated
private EventProgressDialog(boolean show, String message){
setShow(show);
setProgressDialogMessage(message);
}
/**
*
* @deprecated Please use builder pattern
*/
@Deprecated
public EventProgressDialog setShow(boolean show) {
this.show = show;
return this;
}
/**
*
* @deprecated Please use builder pattern
*/
@Deprecated
public EventProgressDialog setProgressDialogMessage(String progressDialogMessage) {
this.progressDialogMessage = progressDialogMessage;
return this;
}
} | package com.kogimobile.android.baselibrary.app.busevents;
/**
* @author Julian Cardona on 7/11/14.
*/
public class EventProgressDialog {
public static Builder getBuilder() {
return new Builder();
}
private boolean show = false;
private String progressDialogMessage = "";
private EventProgressDialog(Builder builder){
this.show = builder.show;
this.progressDialogMessage = builder.message;
}
public boolean isShown() {
return show;
}
public String getProgressDialogMessage() {
return progressDialogMessage;
}
public static class Builder {
private boolean show;
private String message;
public Builder withShow(boolean show) {
this.show = show;
return this;
}
public Builder withMessage(String message) {
this.message = message;
return this;
}
public EventProgressDialog build() {
return new EventProgressDialog(this);
}
}
/**
*
* @deprecated Please use builder pattern
*/
@Deprecated
private EventProgressDialog(boolean show, String message){
setShow(show);
setProgressDialogMessage(message);
}
/**
*
* @deprecated Please use builder pattern
*/
@Deprecated
public EventProgressDialog setShow(boolean show) {
this.show = show;
return this;
}
/**
*
* @deprecated Please use builder pattern
*/
@Deprecated
public EventProgressDialog setProgressDialogMessage(String progressDialogMessage) {
this.progressDialogMessage = progressDialogMessage;
return this;
}
} |
Set content type of api response to JSON. | var helpers = require('./helpers');
var db = helpers.db;
/* /users */
exports.getAllUsers = function(req, res) {
helpers.getRequestingUser(req, function(err, user) {
if ( err ) {
res.status(500).end();
console.log("getAllUsers:", err);
} else {
if ( !user ) {
res.status(403).end();
} else {
// TODO filter for type
helpers.getAllUsers(function(err, users) {
if ( err ) {
res.status(500).end();
} else {
res.set('Content-Type', 'application/json');
res.end(JSON.stringify(users));
}
});
}
}
});
};
/* /user/:id/cards */
exports.getCardsOfUser = function(req, res) {
helpers.getRequestingUser(req, function(err, user) {
if ( err ) {
res.status(500).end();
} else {
if ( !user ) {
res.status(403).end();
} else {
// TODO filter for type
var id = req.params.id;
helpers.getUser({
id: id
}, function(err, user) {
if ( user ) {
user.getCards().success(function(cards) {
if ( cards ) {
res.set('Content-Type', 'application/json');
res.end(JSON.stringify(cards));
} else {
res.status(500).end();
}
});
}
});
}
}
});
};
| var helpers = require('./helpers');
var db = helpers.db;
/* /users */
exports.getAllUsers = function(req, res) {
helpers.getRequestingUser(req, function(err, user) {
if ( err ) {
res.status(500).end();
console.log("getAllUsers:", err);
} else {
if ( !user ) {
res.status(403).end();
} else {
// TODO filter for type
helpers.getAllUsers(function(err, users) {
if ( err ) {
res.status(500).end();
} else {
res.end(JSON.stringify(users));
}
});
}
}
});
};
/* /user/:id/cards */
exports.getCardsOfUser = function(req, res) {
helpers.getRequestingUser(req, function(err, user) {
if ( err ) {
res.status(500).end();
} else {
if ( !user ) {
res.status(403).end();
} else {
// TODO filter for type
var id = req.params.id;
helpers.getUser({
id: id
}, function(err, user) {
if ( user ) {
user.getCards().success(function(cards) {
if ( cards ) {
res.end(JSON.stringify(cards));
} else {
res.status(500).end();
}
});
}
});
}
}
});
};
|
Change if...else statement to switch for better code organization | (function () {
angular
.module("ng-geocoder")
.factory("ngGeocoderService", ngGeocoderService);
ngGeocoderService.$inject = ["$q"];
function ngGeocoderService ($q) {
var geocoder = new google.maps.Geocoder();
var service = {
"geocodeById": geocodeById,
"geocodeByQuery": geocodeByQuery
}
return service;
function handleReply (defer, results, status) {
switch (status) {
case google.maps.GeocoderStatus.OK:
return defer.resolve(results);
case google.maps.GeocoderStatus.ZERO_RESULTS:
return defer.resolve([]);
case google.maps.GeocoderStatus.OVER_QUERY_LIMIT:
return defer.reject("Over query limit");
case google.maps.GeocoderStatus.REQUEST_DENIED:
return defer.reject("Request denied");
default:
return defer.reject("Unknown error");
}
}
function geocodeById (placeId) {
return geocode({ "placeId": placeId });
}
function geocodeByQuery (query, region) {
var params = {
"address": query,
"region": region
}
return geocode(params);
}
function geocode (options) {
var defer = $q.defer();
geocoder.geocode(options, function (results, status) {
handleReply(defer, results, status);
});
return defer.promise;
}
}
})();
| (function () {
angular
.module("ng-geocoder")
.factory("ngGeocoderService", ngGeocoderService);
ngGeocoderService.$inject = ["$q"];
function ngGeocoderService ($q) {
var geocoder = new google.maps.Geocoder();
var service = {
"geocodeById": geocodeById,
"geocodeByQuery": geocodeByQuery
}
return service;
function handleReply (defer, results, status) {
if (status == google.maps.GeocoderStatus.OK) {
return defer.resolve(results);
} else if (status === google.maps.GeocoderStatus.ZERO_RESULTS) {
return defer.resolve([]);
} else if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
return defer.reject("Over query limit");
} else if (status === google.maps.GeocoderStatus.REQUEST_DENIED) {
return defer.reject("Request denied");
}
return defer.reject("Unknown error");
}
function geocodeById (placeId) {
return geocode({ "placeId": placeId });
}
function geocodeByQuery (query, region) {
return geocode({ "address": query, "region": region });
}
function geocode (options) {
var defer = $q.defer();
geocoder.geocode(options, function (results, status) {
handleReply(defer, results, status);
});
return defer.promise;
}
}
})();
|
Add valid http url validation | <?php
class BotController extends ControllerBase {
public function update( $boturl = '' ) {
require_once 'models/curl.php';
require_once 'models/grader/bot.php';
if ( empty( $boturl ) ) {
go( 'bot', 'update', [ 'boturl_empty' => true ] );
}
if ( !filter_var( $boturl, FILTER_VALIDATE_URL ) ) {
go( 'bot', 'update', [ 'boturl_invalid' => true ] );
}
if ( isset( $_SESSION[ 'user' ] ) ) {
$user = $_SESSION[ 'user' ];
}
$user->boturl = $boturl;
$bot = new GraderBot( $user );
try {
$bot->sendInitiateRequest();
}
catch ( GraderBotException $e ) {
$error = end( $bot->errors );
$error = str_replace( "initiate_", "", $error );
if ( strpos( $error, '_not_set' ) ) {
$error = 'invalid_json_dictionary';
}
go( 'bot', 'update', [ 'bot_not_success' => true, 'error' => $error ] );
}
$user->save();
go( 'bot', 'update', [ 'bot_success' => true ] );
}
public function updateView( $boturl_empty, $boturl_invalid, $bot_success, $bot_not_success, $error ) {
require_once 'views/bots/update.php';
}
}
?>
| <?php
class BotController extends ControllerBase {
public function update( $boturl = '' ) {
require_once 'models/curl.php';
require_once 'models/grader/bot.php';
if ( empty( $boturl ) ) {
go( 'bot', 'update', [ 'boturl_empty' => true ] );
}
if ( isset( $_SESSION[ 'user' ] ) ) {
$user = $_SESSION[ 'user' ];
}
$user->boturl = $boturl;
$bot = new GraderBot( $user );
try {
$bot->sendInitiateRequest();
}
catch ( GraderBotException $e ) {
$error = end( $bot->errors );
$error = str_replace( "initiate_", "", $error );
if ( strpos( $error, '_not_set' ) ) {
$error = 'invalid_json_dictionary';
}
go( 'bot', 'update', [ 'bot_not_success' => true, 'error' => $error ] );
}
$user->save();
go( 'bot', 'update', [ 'bot_success' => true ] );
}
public function updateView( $boturl_empty, $boturl_invalid, $bot_success, $bot_not_success, $error ) {
require_once 'views/bots/update.php';
}
}
?>
|
Fix user picker search request
The users API controller expects the search params to be contains in a
`q` node. | $.fn.userAutocomplete = function () {
'use strict';
function formatUser(user) {
return Select2.util.escapeMarkup(user.email);
}
this.select2({
minimumInputLength: 1,
multiple: true,
initSelection: function (element, callback) {
Spree.ajax({
url: Spree.routes.users_api,
data: {
ids: element.val()
},
success: function(data) {
callback(data.users);
}
});
},
ajax: {
url: Spree.routes.users_api,
datatype: 'json',
params: { "headers": { "X-Spree-Token": Spree.api_key } },
data: function (term) {
return {
q: {
m: 'or',
email_start: term,
addresses_firstname_start: term,
addresses_lastname_start: term
}
};
},
results: function (data) {
return {
results: data.users,
more: data.current_page < data.pages
};
}
},
formatResult: formatUser,
formatSelection: formatUser
});
};
$(document).ready(function () {
$('.user_picker').userAutocomplete();
});
| $.fn.userAutocomplete = function () {
'use strict';
function formatUser(user) {
return Select2.util.escapeMarkup(user.email);
}
this.select2({
minimumInputLength: 1,
multiple: true,
initSelection: function (element, callback) {
Spree.ajax({
url: Spree.routes.users_api,
data: {
ids: element.val()
},
success: function(data) {
callback(data.users);
}
});
},
ajax: {
url: Spree.routes.users_api,
datatype: 'json',
params: { "headers": { "X-Spree-Token": Spree.api_key } },
data: function (term) {
return {
m: 'or',
email_start: term,
addresses_firstname_start: term,
addresses_lastname_start: term
};
},
results: function (data) {
return {
results: data.users,
more: data.current_page < data.pages
};
}
},
formatResult: formatUser,
formatSelection: formatUser
});
};
$(document).ready(function () {
$('.user_picker').userAutocomplete();
});
|
Remove other Google Analytics reference | // =============================================
//
// WWW.QUIS.CC
// ---------------------------------------------
//
// By Chris Hill-Scott, except where noted.
//
// =============================================
$(function() {
for (var module in QUIS) {
if (QUIS[module].init) QUIS[module].init();
}
if (!QUIS.isMobile) {
$(".next-link")
.hide();
}
// Automatically load new photos when scrolling near bottom of page
$("#photos")
.infinitescroll(
{
navSelector: "footer",
nextSelector: ".next-link a",
itemSelector: ".unit",
loadingText: "Loading more photos",
donetext: "No more photos",
callback: function(path, pageID) {
QUIS.map.renderMap();
}
}
);
// Keyboard navigation controller
$(document)
.keydown(
function(event) {
switch (event.keyCode || event.which) {
case 74: // j
case 40: // down arrow
return scrollPhotos.go(1);
case 75: // k
case 38: // up arrow
return scrollPhotos.go(-1);
}
}
);
});
| // =============================================
//
// WWW.QUIS.CC
// ---------------------------------------------
//
// By Chris Hill-Scott, except where noted.
//
// =============================================
$(function() {
for (var module in QUIS) {
if (QUIS[module].init) QUIS[module].init();
}
if (!QUIS.isMobile) {
$(".next-link")
.hide();
}
// Automatically load new photos when scrolling near bottom of page
$("#photos")
.infinitescroll(
{
navSelector: "footer",
nextSelector: ".next-link a",
itemSelector: ".unit",
loadingText: "Loading more photos",
donetext: "No more photos",
callback: function(path, pageID) {
QUIS.map.renderMap();
if (_gaq) {
// Notify Google Analytics of page view
_gaq.push(['_trackPageview', path]);
}
}
}
);
// Keyboard navigation controller
$(document)
.keydown(
function(event) {
switch (event.keyCode || event.which) {
case 74: // j
case 40: // down arrow
return scrollPhotos.go(1);
case 75: // k
case 38: // up arrow
return scrollPhotos.go(-1);
}
}
);
});
|
Fix lint build error from Fonts patch.
Reviewed at https://reviews.apache.org/r/63129/ | import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import SchedulerClient from 'client/scheduler-client';
import Navigation from 'components/Navigation';
import Home from 'pages/Home';
import Instance from 'pages/Instance';
import Job from 'pages/Job';
import Jobs from 'pages/Jobs';
import Update from 'pages/Update';
import Updates from 'pages/Updates';
import 'bootstrap/dist/css/bootstrap.css';
import '../resources/source-sans-pro.css';
import '../sass/app.scss';
const injectApi = (Page) => (props) => <Page api={SchedulerClient} {...props} />;
const SchedulerUI = () => (
<Router>
<div>
<Navigation />
<Route component={injectApi(Home)} exact path='/beta/scheduler' />
<Route component={injectApi(Jobs)} exact path='/beta/scheduler/:role' />
<Route component={injectApi(Jobs)} exact path='/beta/scheduler/:role/:environment' />
<Route component={injectApi(Job)} exact path='/beta/scheduler/:role/:environment/:name' />
<Route
component={injectApi(Instance)}
exact
path='/beta/scheduler/:role/:environment/:name/:instance' />
<Route
component={injectApi(Update)}
exact
path='/beta/scheduler/:role/:environment/:name/update/:uid' />
<Route component={injectApi(Updates)} exact path='/beta/updates' />
</div>
</Router>
);
ReactDOM.render(<SchedulerUI />, document.getElementById('root'));
| import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import SchedulerClient from 'client/scheduler-client';
import Navigation from 'components/Navigation';
import Home from 'pages/Home';
import Instance from 'pages/Instance';
import Job from 'pages/Job';
import Jobs from 'pages/Jobs';
import Update from 'pages/Update';
import Updates from 'pages/Updates';
import 'bootstrap/dist/css/bootstrap.css';
import '../resources/source-sans-pro.css'
import '../sass/app.scss';
const injectApi = (Page) => (props) => <Page api={SchedulerClient} {...props} />;
const SchedulerUI = () => (
<Router>
<div>
<Navigation />
<Route component={injectApi(Home)} exact path='/beta/scheduler' />
<Route component={injectApi(Jobs)} exact path='/beta/scheduler/:role' />
<Route component={injectApi(Jobs)} exact path='/beta/scheduler/:role/:environment' />
<Route component={injectApi(Job)} exact path='/beta/scheduler/:role/:environment/:name' />
<Route
component={injectApi(Instance)}
exact
path='/beta/scheduler/:role/:environment/:name/:instance' />
<Route
component={injectApi(Update)}
exact
path='/beta/scheduler/:role/:environment/:name/update/:uid' />
<Route component={injectApi(Updates)} exact path='/beta/updates' />
</div>
</Router>
);
ReactDOM.render(<SchedulerUI />, document.getElementById('root'));
|
[DEV] Return only "operators" without the leading `$` in order to make them less harmful if you want to log them or even store them in a database. | var mongoOperators = require('./operators');
var operatorRegEx = new RegExp(/(\$\w+)/g);
var replacer = '_';
var invalidReplaceChars = ['$'];
module.exports = {
checkStr: function checkStr (str) {
var strType = typeof str;
var injections = [];
var escaped;
if (strType === 'string') {
escaped = str.replace(operatorRegEx, function (match) {
if (mongoOperators.isOperator(match)) {
injections.push(match.substr(1));
return replacer;
}
return match;
});
} else if (strType === 'number') {
escaped = str;
} else {
throw new Error('<mongo-interceptor> Trying to escape a "' + strType + '"!', str);
}
return {
escaped: escaped,
injections: injections,
isIntrusion: injections.length > 0
}
},
setOperatorReplacer: function setOperatorReplacer (str) {
if (typeof str !== 'string') {
throw new Error('The operator replacer must be of type "string" - got "' + typeof str + '" instead!');
}
var strLength = str.length;
if (strLength > 1) {
str = str.trim();
}
if (invalidReplaceChars.indexOf(str) !== -1) {
throw new Error('The replacement character "' + str + '" is invalid as it could harm the db safety!');
} else if (mongoOperators.isOperator(str)) {
throw new Error('The replacement string "' + str + '" is a mongodb-operator itself!');
}
replacer = str;
}
}; | var mongoOperators = require('./operators');
var operatorRegEx = new RegExp(/(\$\w+)/g);
var replacer = '_';
var invalidReplaceChars = ['$'];
module.exports = {
checkStr: function checkStr (str) {
var strType = typeof str;
var injections = [];
var escaped;
if (strType === 'string') {
escaped = str.replace(operatorRegEx, function (match) {
if (mongoOperators.isOperator(match)) {
injections.push(match);
return replacer;
}
return match;
});
} else if (strType === 'number') {
escaped = str;
} else {
throw new Error('<mongo-interceptor> Trying to escape a "' + strType + '"!', str);
}
return {
escaped: escaped,
injections: injections,
isIntrusion: injections.length > 0
}
},
setOperatorReplacer: function setOperatorReplacer (str) {
if (typeof str !== 'string') {
throw new Error('The operator replacer must be of type "string" - got "' + typeof str + '" instead!');
}
var strLength = str.length;
if (strLength > 1) {
str = str.trim();
}
if (invalidReplaceChars.indexOf(str) !== -1) {
throw new Error('The replacement character "' + str + '" is invalid as it could harm the db safety!');
} else if (mongoOperators.isOperator(str)) {
throw new Error('The replacement string "' + str + '" is a mongodb-operator itself!');
}
replacer = str;
}
}; |
Patch job scheduler avoiding possibilities for concurrent runs of the same | # -*- coding: UTF-8
# jobs/base
# *********
#
# Base class for implement the scheduled tasks
import sys
from twisted.internet import task
from twisted.python.failure import Failure
from globaleaks.utils.utility import log
from globaleaks.utils.mailutils import mail_exception
class GLJob(task.LoopingCall):
def __init__(self):
task.LoopingCall.__init__(self, self._operation)
def _operation(self):
ret = None
try:
ret = self.operation()
except Exception as e:
log.err("Exception while performin scheduled operation %s: %s" % \
(type(self).__name__, e))
try:
if isinstance(e, Failure):
exc_type = e.type
exc_value = e.value
exc_tb = e.getTracebackObject()
else:
exc_type, exc_value, exc_tb = sys.exc_info()
mail_exception(exc_type, exc_value, exc_tb)
except Exception:
pass
return ret
def operation(self):
pass # dummy skel for GLJob objects
| # -*- coding: UTF-8
# jobs/base
# *********
#
# Base class for implement the scheduled tasks
import sys
from twisted.internet import task
from twisted.python.failure import Failure
from globaleaks.utils.utility import log
from globaleaks.utils.mailutils import mail_exception
class GLJob(task.LoopingCall):
def __init__(self):
task.LoopingCall.__init__(self, self._operation)
def _operation(self):
try:
self.operation()
except Exception as e:
log.err("Exception while performin scheduled operation %s: %s" % \
(type(self).__name__, e))
try:
if isinstance(e, Failure):
exc_type = e.type
exc_value = e.value
exc_tb = e.getTracebackObject()
else:
exc_type, exc_value, exc_tb = sys.exc_info()
mail_exception(exc_type, exc_value, exc_tb)
except Exception:
pass
def operation(self):
pass # dummy skel for GLJob objects
|
Fix header in facilities view | (function (angular) {
"use strict";
angular.module("mfl.facilities.base", [
"ui.router"
])
.config(["$stateProvider", function ($stateProvider) {
$stateProvider
.state("facilities", {
url: "/facilities",
views: {
"main": {
templateUrl: "facilities/tpls/common/main.tpl.html"
},
"header@facilities": {
controller: "mfl.common.controllers.header",
templateUrl: "common/tpls/header.tpl.html"
},
"sidebar@facilities": {
templateUrl: "facilities/tpls/common/sidebar.tpl.html"
},
"main-content@facilities": {
templateUrl: "facilities/tpls/grid/index.tpl.html",
controller: "mfl.facilities.controllers.home.list"
}
},
data : { pageTitle: "Facility Management" }
});
}]);
})(angular);
| (function (angular) {
"use strict";
angular.module("mfl.facilities.base", [
"ui.router"
])
.config(["$stateProvider", function ($stateProvider) {
$stateProvider
.state("facilities", {
url: "/facilities",
views: {
"main": {
templateUrl: "facilities/tpls/common/main.tpl.html"
},
"header@facilities": {
templateUrl: "common/tpls/header.tpl.html"
},
"sidebar@facilities": {
templateUrl: "facilities/tpls/common/sidebar.tpl.html"
},
"main-content@facilities": {
templateUrl: "facilities/tpls/grid/index.tpl.html",
controller: "mfl.facilities.controllers.home.list"
}
},
data : { pageTitle: "Facility Management" }
});
}]);
})(angular);
|
Add ability to delete earnings from earnings' index view | @extends('layout')
@section('title', __('general.earnings'))
@section('body')
<div class="wrapper my-3">
<h2>{{ __('general.earnings') }}</h2>
<div class="box mt-3">
@if (count($earnings))
@foreach ($earnings as $earning)
<div class="box__section row">
<div class="row__column">
<div class="color-dark">{{ $earning->description }}</div>
<div class="mt-1" style="font-size: 14px; font-weight: 600;">{{ $earning->formatted_happened_on }}</div>
</div>
<div class="row__column row__column--middle color-dark">€ {{ $earning->formatted_amount }}</div>
<div class="row__column row__column--middle row__column--compact">
<form method="POST" action="/earnings/{{ $earning->id }}">
{{ method_field('DELETE') }}
{{ csrf_field() }}
<button class="button link">
<i class="far fa-trash-alt"></i>
</button>
</form>
</div>
</div>
@endforeach
@else
<div class="box__section text-center">You don't have any earnings</div>
@endif
</div>
</div>
@endsection
| @extends('layout')
@section('title', __('general.earnings'))
@section('body')
<div class="wrapper my-3">
<h2>{{ __('general.earnings') }}</h2>
<div class="box mt-3">
@if (count($earnings))
@foreach ($earnings as $earning)
<div class="box__section row">
<div class="row__column">
<div class="color-dark">{{ $earning->description }}</div>
<div class="mt-1" style="font-size: 14px; font-weight: 600;">{{ $earning->formatted_happened_on }}</div>
</div>
<div class="row__column row__column--middle color-dark text-right">€ {{ $earning->formatted_amount }}</div>
</div>
@endforeach
@else
<div class="box__section text-center">You don't have any earnings</div>
@endif
</div>
</div>
@endsection
|
Add key for elements rendered by map | import { View } from 'react-native';
import Button from '../Button';
import React, { Component, PropTypes } from 'react';
const propTypes = {
actions: PropTypes.array.isRequired,
onActionPress: PropTypes.func.isRequired,
};
const defaultStyles = {
dialogContainer: {
flexDirection: 'row',
},
actionContainer: {
marginLeft: 8,
}
};
class DialogDefaultActions extends Component {
constructor(props) {
super(props);
this.onActionPressed = this.onActionPressed.bind(this);
}
onActionPressed(action) {
const { onActionPress } = this.props;
if (onActionPress) {
onActionPress(action);
}
}
render() {
const { actions } = this.props;
return (
<View style={defaultStyles.dialogContainer}>
{actions.map(action =>
<View key={action} style={defaultStyles.actionContainer}>
<Button text={action} onPress={this.onActionPressed} />
</View>
)}
</View>
);
}
}
DialogDefaultActions.propTypes = propTypes;
export default DialogDefaultActions;
| import { View } from 'react-native';
import Button from '../Button';
import React, { Component, PropTypes } from 'react';
const propTypes = {
actions: PropTypes.array.isRequired,
onActionPress: PropTypes.func.isRequired,
};
const defaultStyles = {
dialogContainer: {
flexDirection: 'row',
},
actionContainer: {
marginLeft: 8,
}
};
class DialogDefaultActions extends Component {
constructor(props) {
super(props);
this.onActionPressed = this.onActionPressed.bind(this);
}
onActionPressed(action) {
const { onActionPress } = this.props;
if (onActionPress) {
onActionPress(action);
}
}
render() {
const { actions } = this.props;
return (
<View style={defaultStyles.dialogContainer}>
{actions.map(action =>
<View style={defaultStyles.actionContainer}>
<Button text={action} onPress={this.onActionPressed} />
</View>
)}
</View>
);
}
}
DialogDefaultActions.propTypes = propTypes;
export default DialogDefaultActions;
|
Add a watch grunt task to use karma's autoWatch | module.exports = function (grunt) {
'use strict';
var initConfig;
// Loading external tasks
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-karma');
// Project configuration.
initConfig = {
bower: 'bower_components',
pkg: grunt.file.readJSON('package.json'),
watch: {
test: {
// Lint & run unit tests in Karma
// Just running `$ grunt watch` will only lint your code; to run tests
// on watch, use `$ grunt watch:karma` to start a Karma server first
files: ['src/select2.js', 'test/select2Spec.js'],
tasks: ['jshint', 'karma:unit:run']
}
},
karma: {
options: {
configFile: 'test/karma.conf.js',
browsers: ['Firefox', 'PhantomJS']
},
unit: {
singleRun: true
},
watch: {
autoWatch: true
},
server: {
background: true
}
},
jshint: {
all:[
'gruntFile.js',
'src/**/*.js',
'test/**/*Spec.js'
],
options: {
jshintrc: '.jshintrc'
}
},
};
// Register tasks
grunt.registerTask('default', ['jshint', 'karma:unit']);
grunt.registerTask('watch', ['jshint', 'karma:watch']);
grunt.initConfig(initConfig);
};
| module.exports = function (grunt) {
'use strict';
var initConfig;
// Loading external tasks
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-karma');
// Project configuration.
initConfig = {
bower: 'bower_components',
pkg: grunt.file.readJSON('package.json'),
watch: {
test: {
// Lint & run unit tests in Karma
// Just running `$ grunt watch` will only lint your code; to run tests
// on watch, use `$ grunt watch:karma` to start a Karma server first
files: ['src/select2.js', 'test/select2Spec.js'],
tasks: ['jshint', 'karma:unit:run']
}
},
karma: {
options: {
configFile: 'test/karma.conf.js'
},
unit: {
singleRun: true,
browsers: ['Firefox', 'PhantomJS']
},
server: {
background: true,
browsers: ['Firefox', 'PhantomJS']
}
},
jshint: {
all:[
'gruntFile.js',
'src/**/*.js',
'test/**/*Spec.js'
],
options: {
jshintrc: '.jshintrc'
}
},
};
// Register tasks
grunt.registerTask('default', ['jshint', 'karma:unit']);
grunt.initConfig(initConfig);
};
|
Test fixed for CategoryService
Test updated for UrlObject after change | <?php
/*
* This file is part of the ONGR package.
*
* (c) NFQ Technologies UAB <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ONGR\ContentBundle\Tests\Unit\Document;
use ONGR\ContentBundle\Document\UrlObject;
/**
* Provides tests for url object.
*/
class UrlObjectTest extends \PHPUnit_Framework_TestCase
{
/**
* Provides data for testUrlObject().
*
* @return array
*/
public function urlObjectDataProvider()
{
$data = [
[
[
'url' => 'http://ongr.io',
'key' => 'key1',
],
],
[
[
'url' => 'http://ongr.io/use-case/',
'key' => 'key2',
],
],
];
return $data;
}
/**
* Tests url object.
*
* @param array $data
*
* @dataProvider urlObjectDataProvider()
*/
public function testUrlObject(array $data)
{
/** @var UrlObject $url */
$url = $this->getMock('ONGR\ContentBundle\Document\UrlObject', null);
$url->setUrl($data['url']);
$this->assertEquals($data['url'], $url->getUrl());
$url->setKey($data['key']);
$this->assertEquals($data['key'], $url->getKey());
}
}
| <?php
/*
* This file is part of the ONGR package.
*
* (c) NFQ Technologies UAB <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ONGR\ContentBundle\Tests\Unit\Document;
use ONGR\ContentBundle\Document\UrlObject;
/**
* Provides tests for url object.
*/
class UrlObjectTest extends \PHPUnit_Framework_TestCase
{
/**
* Provides data for testUrlObject().
*
* @return array
*/
public function urlObjectDataProvider()
{
$data = [
[
[
'url' => 'http://ongr.io',
'key' => 'key1',
],
],
[
[
'url' => 'http://ongr.io/use-case/',
'key' => 'key2',
],
],
];
return $data;
}
/**
* Tests url object.
*
* @param array $data
*
* @dataProvider urlObjectDataProvider()
*/
public function testUrlObject(array $data)
{
/** @var UrlObject $url */
$url = $this->getMock('ONGR\ContentBundle\Document\UrlObject', null);
$url->setUrl($data['url']);
$this->assertEquals($data['url'], $url->getUrl());
$url->setUrlKey($data['key']);
$this->assertEquals($data['key'], $url->getUrlKey());
}
}
|
Initialize bolt progress bar widget | /**
* Main mixin for the Bolt buic module.
*
* @mixin
* @namespace Bolt.buic
*
* @param {Object} bolt - The Bolt module.
* @param {Object} $ - jQuery.
*/
(function (bolt, $) {
'use strict';
/**
* Bolt.buic mixin container.
*
* @private
* @type {Object}
*/
var buic = {};
/**
* Initializes the fields, optionally based on a context.
*
* @function init
* @memberof Bolt.buic
* @param context
*/
buic.init = function(context) {
if (typeof context === 'undefined') {
context = $(document.documentElement);
}
$('.buic-checkbox', context).each(function () {
bolt.buic.checkbox.init(this);
});
$('.buic-listing', context).each(function () {
bolt.buic.listing.init(this);
});
$('.buic-moment', context).each(function () {
bolt.buic.moment.init(this);
});
$('.buic-select', context).each(function () {
bolt.buic.select.init(this);
});
// Widgets
$('.buic-progress', context).progress();
};
// Add placeholder for buic.
bolt.buic = buic;
})(Bolt || {}, jQuery);
| /**
* Main mixin for the Bolt buic module.
*
* @mixin
* @namespace Bolt.buic
*
* @param {Object} bolt - The Bolt module.
* @param {Object} $ - jQuery.
*/
(function (bolt, $) {
'use strict';
/**
* Bolt.buic mixin container.
*
* @private
* @type {Object}
*/
var buic = {};
/**
* Initializes the fields, optionally based on a context.
*
* @function init
* @memberof Bolt.buic
* @param context
*/
buic.init = function(context) {
if (typeof context === 'undefined') {
context = $(document.documentElement);
}
$('.buic-checkbox', context).each(function () {
bolt.buic.checkbox.init(this);
});
$('.buic-listing', context).each(function () {
bolt.buic.listing.init(this);
});
$('.buic-moment', context).each(function () {
bolt.buic.moment.init(this);
});
$('.buic-progress', context).each(function () {
bolt.buic.progress.init(this);
});
$('.buic-select', context).each(function () {
bolt.buic.select.init(this);
});
};
// Add placeholder for buic.
bolt.buic = buic;
})(Bolt || {}, jQuery);
|
Fix bad initial count in slug creation helper | from django.db import IntegrityError
from django.template.defaultfilters import slugify
def save_obj_with_slug(obj, attribute='title', **kwargs):
obj.slug = slugify(getattr(obj, attribute))
return save_obj_unique(obj, 'slug', **kwargs)
def save_obj_unique(obj, attr, count=0, postfix_format='-{count}'):
klass = obj.__class__
MAX_COUNT = 10000 # max 10 thousand loops
base_attr = getattr(obj, attr)
initial_count = count
first_round = count == 0
postfix = ''
while True:
try:
while initial_count - count < MAX_COUNT:
if not first_round:
postfix = postfix_format.format(count=count)
if not klass.objects.filter(**{
attr: getattr(obj, attr) + postfix
}).exists():
break
if first_round:
first_round = False
count = max(
klass.objects.filter(**{
'%s__startswith' % attr: base_attr
}).count(),
initial_count
)
else:
count += 1
setattr(obj, attr, base_attr + postfix)
obj.save()
except IntegrityError:
if count - initial_count < MAX_COUNT:
if first_round:
first_round = False
count = max(
klass.objects.filter(**{
'%s__startswith' % attr: base_attr
}).count(),
initial_count
)
count += 1
else:
raise
else:
break
| from django.db import IntegrityError
from django.template.defaultfilters import slugify
def save_obj_with_slug(obj, attribute='title', **kwargs):
obj.slug = slugify(getattr(obj, attribute))
return save_obj_unique(obj, 'slug', **kwargs)
def save_obj_unique(obj, attr, count=0, postfix_format='-{count}'):
klass = obj.__class__
MAX_COUNT = 10000 # max 10 thousand loops
base_attr = getattr(obj, attr)
initial_count = count
first_round = count == 0
postfix = ''
while True:
try:
while initial_count - count < MAX_COUNT:
if not first_round:
postfix = postfix_format.format(count=count)
if not klass.objects.filter(**{
attr: getattr(obj, attr) + postfix
}).exists():
break
if first_round:
first_round = False
count = klass.objects.filter(**{
'%s__startswith' % attr: base_attr
}).count()
else:
count += 1
setattr(obj, attr, base_attr + postfix)
obj.save()
except IntegrityError:
if count - initial_count < MAX_COUNT:
first_round = False
count = klass.objects.filter(**{
'%s__startswith' % attr: base_attr
}).count()
else:
raise
else:
break
|
Fix for reference line point projection | var cornerstoneTools = (function ($, cornerstone, cornerstoneTools) {
"use strict";
if(cornerstoneTools === undefined) {
cornerstoneTools = {};
}
if(cornerstoneTools.referenceLines === undefined) {
cornerstoneTools.referenceLines = {};
}
// projects a patient point to an image point
function projectPatientPointToImagePlane(patientPoint, imagePlane)
{
var point = patientPoint.clone().sub(imagePlane.imagePositionPatient);
var x = imagePlane.columnCosines.dot(point) / imagePlane.columnPixelSpacing;
var y = imagePlane.rowCosines.dot(point) / imagePlane.rowPixelSpacing;
var imagePoint = {x: x, y: y};
return imagePoint;
}
// projects an image point to a patient point
function imagePointToPatientPoint(imagePoint, imagePlane)
{
var x = imagePlane.columnCosines.clone().multiplyScalar(imagePoint.x);
x.multiplyScalar(imagePlane.columnPixelSpacing);
var y = imagePlane.rowCosines.clone().multiplyScalar(imagePoint.y);
y.multiplyScalar(imagePlane.rowPixelSpacing);
var patientPoint = x.add(y);
patientPoint.add(imagePlane.imagePositionPatient);
return patientPoint;
}
// module/private exports
cornerstoneTools.projectPatientPointToImagePlane = projectPatientPointToImagePlane;
cornerstoneTools.imagePointToPatientPoint = imagePointToPatientPoint;
return cornerstoneTools;
}($, cornerstone, cornerstoneTools)); | var cornerstoneTools = (function ($, cornerstone, cornerstoneTools) {
"use strict";
if(cornerstoneTools === undefined) {
cornerstoneTools = {};
}
if(cornerstoneTools.referenceLines === undefined) {
cornerstoneTools.referenceLines = {};
}
// projects a patient point to an image point
function projectPatientPointToImagePlane(patientPoint, imagePlane)
{
var point = patientPoint.clone().sub(imagePlane.imagePositionPatient);
var x = imagePlane.rowCosines.dot(point) / imagePlane.columnPixelSpacing;
var y = imagePlane.columnCosines.dot(point) / imagePlane.rowPixelSpacing;
var imagePoint = {x: x, y: y};
return imagePoint;
}
// projects an image point to a patient point
function imagePointToPatientPoint(imagePoint, imagePlane)
{
var x = imagePlane.rowCosines.clone().multiplyScalar(imagePoint.x);
x.multiplyScalar(imagePlane.columnPixelSpacing);
var y = imagePlane.columnCosines.clone().multiplyScalar(imagePoint.y);
y.multiplyScalar(imagePlane.rowPixelSpacing);
var patientPoint = x.add(y);
patientPoint.add(imagePlane.imagePositionPatient);
return patientPoint;
}
// module/private exports
cornerstoneTools.projectPatientPointToImagePlane = projectPatientPointToImagePlane;
cornerstoneTools.imagePointToPatientPoint = imagePointToPatientPoint;
return cornerstoneTools;
}($, cornerstone, cornerstoneTools)); |
Make compatible with Python <2.7
The argparse module was added in Python 2.7, but the Python bundled
with Inkscape is 2.6. Switching to optparse makes this extension
compatible with the Python bundled with Inkscape. | #!/usr/bin/env python
import csv
import optparse
import shutil
import subprocess
import sys
if __name__ == '__main__':
parser = optparse.OptionParser(description="Chain together Inkscape extensions",
usage="%prog [options] svgpath")
parser.add_option('--id', dest='ids', action='append', type=str, default=[],
help="ID attributes of objects to manipulate. Passed to all extensions.")
parser.add_option('--csvpath', dest='csvpath', type=str,
help="Path to .csv file containing command lines")
options, args = parser.parse_args()
with open(options.csvpath, 'rb') as f:
# Make an argument list of the ids
id_args = []
for id in options.ids:
id_args.extend(('--id', id))
# Take input for the first call from temporary file or stdin
if args:
stream = open(args[0])
else:
stream = sys.stdin
# Execute all the calls
for row in csv.reader(f):
# Insert the ids into the call
call = row[:1] + id_args + row[1:]
# Make the call
p = subprocess.Popen(call, stdin=stream, stdout=subprocess.PIPE)
# Close our handle to the input pipe because we no longer need it
stream.close()
# Grab the output pipe for input into the next call
stream = p.stdout
# Send output from last call on stdout
shutil.copyfileobj(stream, sys.stdout)
| #!/usr/bin/env python
import argparse
import csv
import shutil
import subprocess
import sys
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Chain together Inkscape extensions")
parser.add_argument('--id', type=str, action='append', dest='ids', default=[],
help="ID attributes of objects to manipulate. Passed to all extensions.")
parser.add_argument('--csvpath', type=str, required=True,
help="Path to .csv file containing command lines")
parser.add_argument('svgpath', type=str, nargs='?', default='',
help="Path to temporary SVG file to use for input to the first extension")
args = parser.parse_args()
with open(args.csvpath, 'rb') as f:
# Make an argument list of the ids
id_args = []
for id in args.ids:
id_args.extend(('--id', id))
# Take input for the first call from temporary file or stdin
if args.svgpath:
stream = open(args.svgpath)
else:
stream = sys.stdin
# Execute all the calls
for row in csv.reader(f):
# Insert the ids into the call
call = row[:1] + id_args + row[1:]
# Make the call
p = subprocess.Popen(call, stdin=stream, stdout=subprocess.PIPE)
# Close our handle to the input pipe because we no longer need it
stream.close()
# Grab the output pipe for input into the next call
stream = p.stdout
# Send output from last call on stdout
shutil.copyfileobj(stream, sys.stdout)
|
Fix images not included in assets.json | var path = require('path'),
grunt = require('grunt');
module.exports = {
scripts: {
files: [{
'build/js/jquery.min.map': 'client/components/jquery/dist/jquery.min.map'
}]
},
images: {
files: [{
expand: true,
cwd: 'client/img',
src: '*',
dest: '.grunt/build/img/',
}, {
expand: true,
cwd: 'client/swagger/img',
src: '*',
dest: '.grunt/build/img/',
}]
},
dist: {
files: [{
expand: true,
cwd: '.grunt/build',
src: '**/*.*',
dest: 'build',
filter: function (filepath) {
var dest = path.join(
'build',
// Remove the parent 'js/src' from filepath
filepath.split(path.sep).slice(2).join(path.sep)
);
var doesntExist = !grunt.file.exists(dest);
if (!doesntExist) {
grunt.log.writeln('Skipping existing file: ' + dest);
}
return doesntExist;
},
}]
}
}; | var path = require('path'),
grunt = require('grunt');
module.exports = {
scripts: {
files: [{
'build/js/jquery.min.map': 'client/components/jquery/dist/jquery.min.map'
}]
},
images: {
files: [{
expand: true,
cwd: 'client/img',
src: '*',
dest: 'build/img/',
}, {
expand: true,
cwd: 'client/swagger/img',
src: '*',
dest: 'build/img/',
}]
},
dist: {
files: [{
expand: true,
cwd: '.grunt/build',
src: '**/*.*',
dest: 'build',
filter: function (filepath) {
var dest = path.join(
'build',
// Remove the parent 'js/src' from filepath
filepath.split(path.sep).slice(2).join(path.sep)
);
var doesntExist = !grunt.file.exists(dest);
if (!doesntExist) {
grunt.log.writeln('Skipping existing file: ' + dest);
}
return doesntExist;
},
}]
}
}; |
Make `grunt test` not invoke jenkins tests as well
This makes running tests directly on the commandline more responsive
since it isn't running the sets twice with less useful reporters the
second time. | module.exports = function(grunt){
'use strict';
require('load-grunt-tasks')(grunt);
grunt.loadNpmTasks('grunt-contrib-jshint');
var jsFiles = ['npactweb/static/js/**/*.js'];
grunt.initConfig({
jshint: {
options: {
jshintrc: true
},
all: jsFiles,
jenkins: {
files: {src: jsFiles},
options: {
reporter: 'checkstyle',
reporterOutput: 'jshint.xml',
force: true
}
}
},
karma: {
options: {
configFile: 'karma.conf.js'
},
unit: {
reporters: 'dots'
},
jenkins: {
reporters: 'junit',
outputFile: 'test-results.xml',
singleRun: true
}
},
html2js: {
options:{
singleModule:true
},
main: {
src: ['npactweb/static/js/**/*.html'],
dest: '.tmp/templates.js'
}
}
});
grunt.registerTask('test', ['karma:unit']);
grunt.registerTask('jenkins', ['jshint:jenkins',
'html2js:main',
'karma:jenkins']);
};
| module.exports = function(grunt){
'use strict';
require('load-grunt-tasks')(grunt);
grunt.loadNpmTasks('grunt-contrib-jshint');
var jsFiles = ['npactweb/static/js/**/*.js'];
grunt.initConfig({
jshint: {
options: {
jshintrc: true
},
all: jsFiles,
jenkins: {
files: {src: jsFiles},
options: {
reporter: 'checkstyle',
reporterOutput: 'jshint.xml',
force: true
}
}
},
karma: {
options: {
configFile: 'karma.conf.js'
},
unit: {
reporters: 'dots'
},
jenkins: {
reporters: 'junit',
outputFile: 'test-results.xml',
singleRun: true
}
},
html2js: {
options:{
singleModule:true
},
main: {
src: ['npactweb/static/js/**/*.html'],
dest: '.tmp/templates.js'
}
}
});
grunt.registerTask('test', ['karma']);
grunt.registerTask('jenkins', ['jshint:jenkins',
'html2js:main',
'karma:jenkins']);
};
|
Extend display product details to show product number in the list | <?php
namespace App\Catalog\Category;
use Moltin\SDK\Facade\Moltin as Moltin;
use Moltin\SDK\Facade\Product as Product;
class CategoryList
{
/**
* @var \Psr\Http\Message\ResponseInterface
*/
private $response;
public function __invoke(
\Psr\Http\Message\ServerRequestInterface $request,
\Psr\Http\Message\ResponseInterface $response
) {
$this->response = $response;
// Authenticate credentials
Moltin::Authenticate('ClientCredentials', [
'client_id' => getenv('MOLTIN_CLIENT_ID'),
'client_secret' => getenv('MOLTIN_CLIENT_SECRET')
]);
$products = Product::Listing();
if (!empty($products)) {
$this->response->write(
sprintf(
'We have %d product(s)!',
count($products['result'])
)
);
array_walk(
$products['result'],
[$this, 'displayProductDetails']
);
}
return $this->response;
}
private function displayProductDetails($product, $key)
{
$this->response->write('<br />');
$this->response->write('ProductNumber: ' . $key . '<br />');
$this->response->write(
sprintf(
'Sku: %s',
$product['sku']
)
);
}
} | <?php
namespace App\Catalog\Category;
use Moltin\SDK\Facade\Moltin as Moltin;
use Moltin\SDK\Facade\Product as Product;
class CategoryList
{
private $response;
public function __invoke(
\Psr\Http\Message\ServerRequestInterface $request,
\Psr\Http\Message\ResponseInterface $response
) {
$this->response = $response;
// Authenticate credentials
Moltin::Authenticate('ClientCredentials', [
'client_id' => getenv('MOLTIN_CLIENT_ID'),
'client_secret' => getenv('MOLTIN_CLIENT_SECRET')
]);
$products = Product::Listing();
if (!empty($products)) {
$this->response->write(
sprintf(
'We have %d product(s)!',
count($products['result'])
)
);
array_walk(
$products['result'],
[$this, 'displayProductDetails']
);
}
return $this->response;
}
private function displayProductDetails($product)
{
$this->response->write($product['sku']);
}
} |
Fix augmented system form interface type selection | $(document).ready(function() {
var form = document.getElementById('inner-form');
var interface_type = document.getElementsByName('interface_type');
var static_form = document.getElementById('static-form');
var static_clone = static_form.cloneNode(true);
static_clone.id ="static_clone";
$(static_clone).removeAttr('style');
var dynamic_form = document.getElementById('dynamic-form');
var dynamic_clone = dynamic_form.cloneNode(true);
dynamic_clone.id ="static_clone";
$(dynamic_clone).removeAttr('style');
for(var i = 0; i < interface_type.length; i++) {
if (interface_type[i].checked) {
if (form.lastChild.textContent != '') {
form.removeChild(form.childNodes[form.childNodes.length -1]);
};
if (interface_type[i].value =='static_interface') {
form.appendChild(static_clone);
} else {
form.appendChild(dynamic_clone);
};
};
interface_type[i].onclick = function() {
if (form.lastChild.textContent != '') {
form.removeChild(form.childNodes[form.childNodes.length -1]);
};
if (this.value =='static_interface') {
form.appendChild(static_clone);
} else {
form.appendChild(dynamic_clone);
};
};
};
});
| $(document).ready(function() {
var form = document.getElementById('inner-form');
var interface_type = document.getElementsByName('interface_type');
var static_form = document.getElementById('static-form');
var static_clone = static_form.cloneNode(true);
static_clone.id ="static_clone";
$(static_clone).removeAttr('style');
var dynamic_form = document.getElementById('dynamic-form');
var dynamic_clone = dynamic_form.cloneNode(true);
dynamic_clone.id ="static_clone";
$(dynamic_clone).removeAttr('style');
for(var i = 0; i < interface_type.length; i++) {
if (interface_type[i].checked) {
if (form.lastChild.textContent != '') {
form.removeChild(form.childNodes[form.childNodes.length -1]);
};
if (interface_type[i].value =='Static') {
form.appendChild(static_clone);
} else {
form.appendChild(dynamic_clone);
};
};
interface_type[i].onclick = function() {
if (form.lastChild.textContent != '') {
form.removeChild(form.childNodes[form.childNodes.length -1]);
};
if (this.value =='Static') {
form.appendChild(static_clone);
} else {
form.appendChild(dynamic_clone);
};
};
};
});
|
Remove default locale for prefix_except_default strategy | <?php
namespace Umpirsky\I18nRoutingBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
class UmpirskyI18nRoutingExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
$processor = new Processor();
$config = $processor->processConfiguration(new Configuration(), $configs);
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
$container->getDefinition('umpirsky_i18n_routing.routing.loader.i18n_route_loader')->addArgument(
new Reference(sprintf('umpirsky_i18n_routing.routing.strategy.%s_strategy', $config['strategy']))
);
$container->setParameter('umpirsky_i18n_routing.route_name_suffix', $config['route_name_suffix']);
$container->setParameter('umpirsky_i18n_routing.default_locale', $config['default_locale']);
if ('prefix_except_default' === $config['strategy']) {
$config['locales'] = array_diff($config['locales'], [$config['default_locale']]);
}
$container->setParameter('umpirsky_i18n_routing.locales', $config['locales']);
$container->setParameter('umpirsky_i18n_routing.strategy', $config['strategy']);
}
}
| <?php
namespace Umpirsky\I18nRoutingBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
class UmpirskyI18nRoutingExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
$processor = new Processor();
$config = $processor->processConfiguration(new Configuration(), $configs);
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
$container->getDefinition('umpirsky_i18n_routing.routing.loader.i18n_route_loader')->addArgument(
new Reference(sprintf('umpirsky_i18n_routing.routing.strategy.%s_strategy', $config['strategy']))
);
$container->setParameter('umpirsky_i18n_routing.route_name_suffix', $config['route_name_suffix']);
$container->setParameter('umpirsky_i18n_routing.default_locale', $config['default_locale']);
$container->setParameter('umpirsky_i18n_routing.locales', $config['locales']);
$container->setParameter('umpirsky_i18n_routing.strategy', $config['strategy']);
}
}
|
Return 404 if questionnaire does not exist | <?php
namespace Api\Controller;
use Zend\View\Model\JsonModel;
class QuestionController extends AbstractRestfulController
{
protected function getJsonConfig($questionnaire = null)
{
return array(
'name',
'category' => array(
'name',
'parent' => array(
'name',
'parent' => array(
'name',
),
),
),
// Here we use a closure to get the questions' answers, but only for the current questionnaire
'answers' => function(AbstractRestfulController $controller, \Application\Model\Question $question) use($questionnaire) {
$answerRepository = $controller->getEntityManager()->getRepository('Application\Model\Answer');
$answers = $answerRepository->findBy(array(
'question' => $question,
'questionnaire' => $questionnaire,
));
return $controller->arrayOfObjectsToArray($answers, array(
'valuePercent',
'valueAbsolute',
'questionnaire' => array(),
'part' => array(
'name',
)
));
}
);
}
public function getList()
{
$idQuestionnaire = $this->params('idQuestionnaire');
$questionnaireRepository = $this->getEntityManager()->getRepository('Application\Model\Questionnaire');
$questionnaire = $questionnaireRepository->find($idQuestionnaire);
if (!$questionnaire) {
$this->getResponse()->setStatusCode(404);
return;
}
$questions = $this->getRepository()->findBy(array(
'survey' => $questionnaire->getSurvey(),
));
return new JsonModel($this->arrayOfObjectsToArray($questions, $this->getJsonConfig($questionnaire)));
}
}
| <?php
namespace Api\Controller;
use Zend\View\Model\JsonModel;
class QuestionController extends AbstractRestfulController
{
protected function getJsonConfig($questionnaire = null)
{
return array(
'name',
'category' => array(
'name',
'parent' => array(
'name',
'parent' => array(
'name',
),
),
),
// Here we use a closure to get the questions' answers, but only for the current questionnaire
'answers' => function(AbstractRestfulController $controller, \Application\Model\Question $question) use($questionnaire) {
$answerRepository = $controller->getEntityManager()->getRepository('Application\Model\Answer');
$answers = $answerRepository->findBy(array(
'question' => $question,
'questionnaire' => $questionnaire,
));
return $controller->arrayOfObjectsToArray($answers, array(
'valuePercent',
'valueAbsolute',
'questionnaire' => array(),
'part' => array(
'name',
)
));
}
);
}
public function getList()
{
$idQuestionnaire = $this->params('idQuestionnaire');
$questionnaireRepository = $this->getEntityManager()->getRepository('Application\Model\Questionnaire');
$questionnaire = $questionnaireRepository->find($idQuestionnaire);
$questions = $this->getRepository()->findBy(array(
'survey' => $questionnaire->getSurvey(),
));
return new JsonModel($this->arrayOfObjectsToArray($questions, $this->getJsonConfig($questionnaire)));
}
}
|
Handle a zero result set for a query in the JSONResponseHandler
Turns out that when a query has no results the response document does
not have a key named after the object that contains an empty array. It
simply does not have the key. | <?php
namespace HGG\Pardot\ResponseHandler;
use HGG\Pardot\Exception\RuntimeException;
use HGG\Pardot\Exception\AuthenticationErrorException;
/**
* JsonResponseHandler
*
* @author Henning Glatter-Götz <[email protected]>
*/
class JsonResponseHandler extends AbstractResponseHandler
{
/**
* parse
*
* @param mixed $document
* @param mixed $object
*
* @access protected
* @return void
*/
protected function parse($document, $object)
{
if ('ok' !== $document['@attributes']['stat']) {
$errorCode = $document['@attributes']['err_code'];
$errorMessage = $document['err'];
if (15 === $errorCode) {
throw new AuthenticationErrorException($errorMessage, $errorCode);
} else {
throw new RuntimeException($errorMessage, $errorCode);
}
} else {
if (array_key_exists('result', $document)) {
$this->resultCount = $document['result']['total_results'];
$this->result = (0 === $this->resultCount) ? array() : $document['result'][$object];
} elseif (array_key_exists($object, $document)) {
$this->resultCount = 1;
$this->result = $document[$object];
} elseif (array_key_exists('api_key', $document)) {
$this->resultCount = 0;
$this->result = $document['api_key'];
} else {
throw new RuntimeException('Unknown response format '.json_encode($document));
}
}
}
}
| <?php
namespace HGG\Pardot\ResponseHandler;
use HGG\Pardot\Exception\RuntimeException;
use HGG\Pardot\Exception\AuthenticationErrorException;
/**
* JsonResponseHandler
*
* @author Henning Glatter-Götz <[email protected]>
*/
class JsonResponseHandler extends AbstractResponseHandler
{
/**
* parse
*
* @param mixed $document
* @param mixed $object
*
* @access protected
* @return void
*/
protected function parse($document, $object)
{
if ('ok' !== $document['@attributes']['stat']) {
$errorCode = $document['@attributes']['err_code'];
$errorMessage = $document['err'];
if (15 === $errorCode) {
throw new AuthenticationErrorException($errorMessage, $errorCode);
} else {
throw new RuntimeException($errorMessage, $errorCode);
}
} else {
if (array_key_exists('result', $document)) {
$this->resultCount = $document['result']['total_results'];
$this->result = $document['result'][$object];
} elseif (array_key_exists($object, $document)) {
$this->resultCount = 1;
$this->result = $document[$object];
} elseif (array_key_exists('api_key', $document)) {
$this->resultCount = 0;
$this->result = $document['api_key'];
} else {
throw new RuntimeException('Unknown response format '.json_encode($document));
}
}
}
}
|
Make setup.py test honor migrations
Kudos to django-setuptest project | # This file mainly exists to allow python setup.py test to work.
import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'nodeconductor.server.test_settings'
test_dir = os.path.abspath(os.path.join(os.path.dirname(os.path.dirname(__file__)), '..'))
sys.path.insert(0, test_dir)
from django.test.utils import get_runner
from django.conf import settings
def run_tests():
test_runner_class = get_runner(settings)
try:
from south.management.commands import patch_for_test_db_setup
patch_for_test_db_setup()
except ImportError:
pass
try:
import xmlrunner
class XMLTestRunner(test_runner_class):
def run_suite(self, suite, **kwargs):
verbosity = getattr(settings, 'TEST_OUTPUT_VERBOSE', 1)
if isinstance(verbosity, bool):
verbosity = (1, 2)[verbosity]
descriptions = getattr(settings, 'TEST_OUTPUT_DESCRIPTIONS', False)
output = getattr(settings, 'TEST_OUTPUT_DIR', '.')
return xmlrunner.XMLTestRunner(
verbosity=verbosity,
descriptions=descriptions,
output=output
).run(suite)
test_runner_class = XMLTestRunner
except ImportError:
print "Not generating XML reports, run 'pip install unittest-xml-reporting' to enable XML report generation"
test_runner = test_runner_class(verbosity=1, interactive=True)
failures = test_runner.run_tests([])
sys.exit(bool(failures))
if __name__ == '__main__':
run_tests()
| # This file mainly exists to allow python setup.py test to work.
import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'nodeconductor.server.test_settings'
test_dir = os.path.abspath(os.path.join(os.path.dirname(os.path.dirname(__file__)), '..'))
sys.path.insert(0, test_dir)
from django.test.utils import get_runner
from django.conf import settings
def run_tests():
test_runner_class = get_runner(settings)
try:
import xmlrunner
class XMLTestRunner(test_runner_class):
def run_suite(self, suite, **kwargs):
verbosity = getattr(settings, 'TEST_OUTPUT_VERBOSE', 1)
if isinstance(verbosity, bool):
verbosity = (1, 2)[verbosity]
descriptions = getattr(settings, 'TEST_OUTPUT_DESCRIPTIONS', False)
output = getattr(settings, 'TEST_OUTPUT_DIR', '.')
return xmlrunner.XMLTestRunner(
verbosity=verbosity,
descriptions=descriptions,
output=output
).run(suite)
test_runner_class = XMLTestRunner
except ImportError:
print "Not generating XML reports, run 'pip install unittest-xml-reporting' to enable XML report generation"
test_runner = test_runner_class(verbosity=1, interactive=True)
failures = test_runner.run_tests([])
sys.exit(bool(failures))
if __name__ == '__main__':
runtests()
|
Use one regex instead of 3 |
var http = require('http');
var cheerio = require('cheerio');
exports.translate = function(text, lang, trans, cb){
http.get('http://tyda.se/search/'+text+'?lang%5B0%5D='+lang+'&lang%5B1%5D='+trans, function(res){
var body = '';
res.on('data', function(d){
body+= d;
});
res.on('end', function(e){
var c = cheerio.load(body.toString());
var lastLang = '';
var translations = { };
c('.list-translations').children('li:not(.item-title)').find('a').each(function(i, obj){
var item = c(this);
var translatedText = item.text().replace(/(^\s+|\s+$|\n)/,'');
var lang = item.parent().parent().find('.item-title').text().replace(/(^\s+|\s+$|\n)/,'');
if(lastLang != lang){
if(lang.length > 0){
translations[lang] = [];
lastLang = lang;
}
}
if(translatedText.length > 0){
translations[lang].push(translatedText);
}
});
cb(null, translations);
});
res.on('error', function(err){
return cb(err);
});
}).on('error', function(err){
return cb(err);
});
};
|
var http = require('http');
var cheerio = require('cheerio');
exports.translate = function(text, lang, trans, cb){
http.get('http://tyda.se/search/'+text+'?lang%5B0%5D='+lang+'&lang%5B1%5D='+trans, function(res){
var body = '';
res.on('data', function(d){
body+= d;
});
res.on('end', function(e){
var c = cheerio.load(body.toString());
var lastLang = '';
var translations = { };
c('.list-translations').children('li:not(.item-title)').find('a').each(function(i, obj){
var item = c(this);
var translatedText = item.text().replace(/^\s+/,'').replace(/\s+/,'').replace(/\n/g, '');
var lang = item.parent().parent().find('.item-title').text().replace(/(^\s+|\s+$|\n)/,'').replace(/\s+$/,'').replace(/\n/g,'');
if(lastLang != lang){
if(lang.length > 0){
translations[lang] = [];
lastLang = lang;
}
}
if(translatedText.length > 0){
translations[lang].push(translatedText);
}
});
cb(null, translations);
});
res.on('error', function(err){
return cb(err);
});
}).on('error', function(err){
return cb(err);
});
};
|
Make usage of parse_str() cleaner | <?php
/*
* This file is part of the Purl package, a project by Jonathan H. Wage.
*
* (c) 2013 Jonathan H. Wage
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Purl;
/**
* Query represents the part of a Url after the question mark (?).
*
* @author Jonathan H. Wage <[email protected]>
*/
class Query extends AbstractPart
{
/**
* @var string The original query string.
*/
private $query;
/**
* Construct a new Query instance.
*
* @param string $query
*/
public function __construct($query = null)
{
$this->query = $query;
}
/**
* Builds a string query from this Query instance internal data and returns it.
*
* @return string
*/
public function getQuery()
{
$this->initialize();
return http_build_query($this->data);
}
/**
* Set the string query for this Query instance and sets initialized to false.
*
* @param string
*/
public function setQuery($query)
{
$this->initialized = false;
$this->query = $query;
}
/**
* @inheritDoc
*/
public function __toString()
{
return $this->getQuery();
}
/**
* @inheritDoc
*/
protected function doInitialize()
{
parse_str($this->query, $data);
$this->data = $data;
}
}
| <?php
/*
* This file is part of the Purl package, a project by Jonathan H. Wage.
*
* (c) 2013 Jonathan H. Wage
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Purl;
/**
* Query represents the part of a Url after the question mark (?).
*
* @author Jonathan H. Wage <[email protected]>
*/
class Query extends AbstractPart
{
/**
* @var string The original query string.
*/
private $query;
/**
* Construct a new Query instance.
*
* @param string $query
*/
public function __construct($query = null)
{
$this->query = $query;
}
/**
* Builds a string query from this Query instance internal data and returns it.
*
* @return string
*/
public function getQuery()
{
$this->initialize();
return http_build_query($this->data);
}
/**
* Set the string query for this Query instance and sets initialized to false.
*
* @param string
*/
public function setQuery($query)
{
$this->initialized = false;
$this->query = $query;
}
/**
* @inheritDoc
*/
public function __toString()
{
return $this->getQuery();
}
/**
* @inheritDoc
*/
protected function doInitialize()
{
parse_str($this->query);
$this->data = get_defined_vars();
}
}
|
Revert "Made a sexist comment more PC."
This reverts commit 3632fc802ba9c537653e633b12d9430c7ed3f0b6. | # First bug quest tile.
from weatbag import words
import weatbag
class Tile:
def __init__(self):
self.bug_is_here = True
self.first_visit = True
self.hasnt_gone_south = True
pass
def describe(self):
print("There is a stream here. "
"It runs from South to North.")
if self.bug_is_here:
print("You see a huge, ugly bug rush past you, "
"following the river South.")
self.bug_is_here = False
else:
print("You remember this is where you saw that bug going South.")
# Nothing to do here.
def action(self, player, do):
pass
# Player can only exit the bug quest going back North.
# Player gets different messages the first time he
# exits this tile, depending on his direction.
def leave(self, player, direction):
restricted_directions = { 'w', 'e' }
if direction in restricted_directions:
print("The undergrowth in that direction "
"is impassable. You turn back.")
return False
elif direction == 's' and hasnt_gone_south:
print("Bugs are the enemy and must be crushed!\n"
"So you decide to follow the bug upstream.")
input()
self.first_visit = False
self.hasnt_gone_south = False
return True
else:
if self.first_visit:
print("Bugs do not interest you very much.\n"
"Lets get out of here.")
self.first_visit = False
input()
return True
| # First bug quest tile.
from weatbag import words
import weatbag
class Tile:
def __init__(self):
self.bug_is_here = True
self.first_visit = True
self.hasnt_gone_south = True
pass
def describe(self):
print("There is a stream here. "
"It runs from South to North.")
if self.bug_is_here:
print("You see a huge, ugly bug rush past you, "
"following the river South.")
self.bug_is_here = False
else:
print("You remember this is where you saw that bug going South.")
# Nothing to do here.
def action(self, player, do):
pass
# Player can only exit the bug quest going back North.
# Player gets different messages the first time he
# exits this tile, depending on their direction.
def leave(self, player, direction):
restricted_directions = { 'w', 'e' }
if direction in restricted_directions:
print("The undergrowth in that direction "
"is impassable. You turn back.")
return False
elif direction == 's' and hasnt_gone_south:
print("Bugs are the enemy and must be crushed!\n"
"So you decide to follow the bug upstream.")
input()
self.first_visit = False
self.hasnt_gone_south = False
return True
else:
if self.first_visit:
print("Bugs do not interest you very much.\n"
"Lets get out of here.")
self.first_visit = False
input()
return True
|
Remove usage of deprecated `Ember.keys` | import { beforeEach, afterEach, describe } from 'mocha';
import Ember from 'ember';
import { getContext } from 'ember-test-helpers';
export function createModule(Constructor, name, description, callbacks, tests, method) {
var module;
if (!tests) {
if (!callbacks) {
tests = description;
callbacks = {};
} else {
tests = callbacks;
callbacks = description;
}
module = new Constructor(name, callbacks);
} else {
module = new Constructor(name, description, callbacks);
}
function moduleBody() {
beforeEach(function() {
var self = this;
return module.setup().then(function() {
var context = getContext();
var keys = Object.keys(context);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
self[key] = context[key];
}
});
});
afterEach(function() {
return module.teardown();
});
tests = tests || function() {};
tests();
}
if (method) {
describe[method](module.name, moduleBody);
} else {
describe(module.name, moduleBody);
}
}
export function createOnly(Constructor) {
return function(name, description, callbacks, tests) {
createModule(Constructor, name, description, callbacks, tests, "only");
};
}
export function createSkip(Constructor) {
return function(name, description, callbacks, tests) {
createModule(Constructor, name, description, callbacks, tests, "skip");
};
}
| import { beforeEach, afterEach, describe } from 'mocha';
import Ember from 'ember';
import { getContext } from 'ember-test-helpers';
export function createModule(Constructor, name, description, callbacks, tests, method) {
var module;
if (!tests) {
if (!callbacks) {
tests = description;
callbacks = {};
} else {
tests = callbacks;
callbacks = description;
}
module = new Constructor(name, callbacks);
} else {
module = new Constructor(name, description, callbacks);
}
function moduleBody() {
beforeEach(function() {
var self = this;
return module.setup().then(function() {
var context = getContext();
var keys = Ember.keys(context);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
self[key] = context[key];
}
});
});
afterEach(function() {
return module.teardown();
});
tests = tests || function() {};
tests();
}
if (method) {
describe[method](module.name, moduleBody);
} else {
describe(module.name, moduleBody);
}
}
export function createOnly(Constructor) {
return function(name, description, callbacks, tests) {
createModule(Constructor, name, description, callbacks, tests, "only");
};
}
export function createSkip(Constructor) {
return function(name, description, callbacks, tests) {
createModule(Constructor, name, description, callbacks, tests, "skip");
};
}
|
Fix Spring CORS Filter impl | package com.porterhead.filter.spring;
import com.porterhead.filter.BaseCORSFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by iainporter on 26/07/2014.
*/
@Component
public class SpringCrossOriginResourceSharingFilter extends BaseCORSFilter implements Filter {
@Value("${cors.allowed.origins}")
String allowedOriginsString;
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
if(req instanceof HttpServletRequest) {
if (((HttpServletRequest) req).getHeader("Origin") != null) {
String origin = ((HttpServletRequest) req).getHeader("Origin");
if (getAllowedOrigins(allowedOriginsString).contains(origin)) {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Authorization, Content-Type");
}
}
}
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
} | package com.porterhead.filter.spring;
import com.porterhead.filter.BaseCORSFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by iainporter on 26/07/2014.
*/
@Component
public class SpringCrossOriginResourceSharingFilter extends BaseCORSFilter implements Filter {
@Value("${cors.allowed.origins}")
String allowedOriginsString;
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
if(req instanceof HttpServletRequest) {
if (((HttpServletRequest) req).getHeader("Origin") != null) {
String origin = ((HttpServletRequest) req).getHeader("Origin");
if (getAllowedOrigins(allowedOriginsString).contains(origin)) {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, OPTIONS");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Authorization, Content-Type");
}
}
}
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
} |
Load blog data from command line | from blogtrans.ui.MainWindow import *
import sys, traceback
import getopt
import wx
# Importers / Exporters
from blogtrans.wretch.WretchImporter import WretchImporter
from blogtrans.mt import *
from blogtrans.blogger.BloggerExporter import *
from blogtrans.blogger.BloggerImporter import *
def trap_error(func) :
def f() :
try:
func()
except Exception, inst :
type, value, tb = sys.exc_info()
print "\n".join(traceback.format_exception(type, value, tb))
raw_input()
return f
@trap_error
def main() :
long_opts = [ "import-wretch=", "import-blogger=" ]
opts, args = getopt.getopt(sys.argv[1:], "n", long_opts)
blogdata = None
no_window = False
for o, a in opts :
if o=="-n" :
no_window = True
if o=="--import-wretch" :
blogdata = WretchImporter(a).parse()
print "%d articles, %d comments" % ( blogdata.article_count(), blogdata.comment_count() )
if o=="--import-blogger" :
blogdata = BloggerImporter(a).parse()
print "%d articles, %d comments" % ( blogdata.article_count(), blogdata.comment_count() )
if not no_window :
app = wx.PySimpleApp()
frame = MainWindow()
if blogdata!=None:
frame.setBlogData(blogdata)
app.MainLoop()
if __name__ == "__main__" :
main()
| from blogtrans.ui.MainWindow import *
import sys, traceback
import getopt
import wx
# Importers / Exporters
from blogtrans.wretch.WretchImporter import WretchImporter
from blogtrans.mt import *
from blogtrans.blogger.BloggerExporter import *
from blogtrans.blogger.BloggerImporter import *
def trap_error(func) :
def f() :
try:
func()
except Exception, inst :
type, value, tb = sys.exc_info()
print "\n".join(traceback.format_exception(type, value, tb))
raw_input()
return f
@trap_error
def main() :
long_opts = [ "import-wretch=", "import-blogger=" ]
opts, args = getopt.getopt(sys.argv[1:], "n", long_opts)
no_window = False
for o, a in opts :
if o=="-n" :
no_window = True
if o=="--import-wretch" :
blogdata = WretchImporter(a).parse()
print "%d articles, %d comments" % ( blogdata.article_count(), blogdata.comment_count() )
if o=="--import-blogger" :
blogdata = BloggerImporter(a).parse()
print "%d articles, %d comments" % ( blogdata.article_count(), blogdata.comment_count() )
if not no_window :
app = wx.PySimpleApp()
frame=MainWindow()
app.MainLoop()
if __name__ == "__main__" :
main()
|
Simplify the code: while sorting the ends are placed before the starts |
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
public class CallAggregator {
private static class CallPart {
private long ts;
private boolean isStart;
public CallPart(long ts, boolean isStart) {
this.ts = ts;
this.isStart = isStart;
}
}
private static class CallPartComparator implements Comparator<CallPart> {
@Override
public int compare(CallPart o1, CallPart o2) {
if (o1.ts == o2.ts) {
return o1.isStart ? 1 : -1; // the ends are before the starts !!
}
return o1.ts > o2.ts ? 1 : -1;
}
}
public static int max(List<Call> calls) {
assert (calls != null);
final List<CallPart> startAndEnds = new LinkedList<>();
calls.forEach(call -> {
startAndEnds.add(new CallPart(call.getStartTs(), true));
startAndEnds.add(new CallPart(call.getEndTs(), false));
});
startAndEnds.sort(new CallPartComparator());
int max = 0;
int currentNumberOfCall = 0;
for (CallPart callPart : startAndEnds) {
if (callPart.isStart) {
currentNumberOfCall++;
} else {
currentNumberOfCall--;
}
max = Math.max(max, currentNumberOfCall); // because ends are before starts
}
return max;
}
}
|
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
public class CallAggregator {
private static class CallPart {
private long ts;
private boolean isStart;
public CallPart(long ts, boolean isStart) {
this.ts = ts;
this.isStart = isStart;
}
}
private static class CallPartComparator implements Comparator<CallPart> {
@Override
public int compare(CallPart o1, CallPart o2) {
if (o1.ts == o2.ts) {
return 0;
}
return o1.ts > o2.ts ? 1 : -1;
}
}
public static int max(List<Call> calls) {
assert (calls != null);
final List<CallPart> startAndEnds = new LinkedList<>();
calls.forEach(call -> {
startAndEnds.add(new CallPart(call.getStartTs(), true));
startAndEnds.add(new CallPart(call.getEndTs(), false));
});
startAndEnds.sort(new CallPartComparator());
int max = 0;
int currentNumberOfCall = 0;
long lastTs = -1;
for (CallPart callPart : startAndEnds) {
if (lastTs != callPart.ts) {
max = Math.max(max, currentNumberOfCall);
}
if (callPart.isStart) {
currentNumberOfCall++;
} else {
currentNumberOfCall--;
}
}
max = Math.max(max, currentNumberOfCall);
return max;
}
}
|
Increase number of Kociemba test iterations to 100 | from src.Move import Move
from src.NaiveCube import NaiveCube
from src.Cubie import Cube
from src.Solver import Kociemba
import timeout_decorator
import unittest
class TestKociembaSolver(unittest.TestCase):
@timeout_decorator.timeout(300)
def _test_solution(self, c):
solver = Kociemba.KociembaSolver(c)
return solver.solution()
def test_solution(self):
for i in range(100):
c = Cube()
cr = Cube()
c.shuffle(i)
solution = self._test_solution(c)
for s in solution:
c.move(s)
# Align faces
while cr.cubies['F'].facings['F'] != c.cubies['F'].facings['F']:
c.move(Move('Y'))
for cubie in cr.cubies:
for facing in cr.cubies[cubie].facings:
self.assertEqual(cr.cubies[cubie].facings[facing], c.cubies[cubie].facings[facing])
def test_timeout(self):
c = Cube()
nc = NaiveCube()
nc.set_cube("orgyyybbbwgobbbyrywowwrwrwyrorogboogwygyorrwobrggwgbgy")
c.from_naive_cube(nc)
with self.assertRaises(Kociemba.Search.TimeoutError):
solver = Kociemba.KociembaSolver(c)
solver.solution(timeOut = 1)
| from src.Move import Move
from src.NaiveCube import NaiveCube
from src.Cubie import Cube
from src.Solver import Kociemba
import timeout_decorator
import unittest
class TestKociembaSolver(unittest.TestCase):
@timeout_decorator.timeout(300)
def _test_solution(self, c):
solver = Kociemba.KociembaSolver(c)
return solver.solution()
def test_solution(self):
for i in range(10):
c = Cube()
cr = Cube()
c.shuffle(i)
solution = self._test_solution(c)
for s in solution:
c.move(s)
# Align faces
while cr.cubies['F'].facings['F'] != c.cubies['F'].facings['F']:
c.move(Move('Y'))
for cubie in cr.cubies:
for facing in cr.cubies[cubie].facings:
self.assertEqual(cr.cubies[cubie].facings[facing], c.cubies[cubie].facings[facing])
def test_timeout(self):
c = Cube()
nc = NaiveCube()
nc.set_cube("orgyyybbbwgobbbyrywowwrwrwyrorogboogwygyorrwobrggwgbgy")
c.from_naive_cube(nc)
with self.assertRaises(Kociemba.Search.TimeoutError):
solver = Kociemba.KociembaSolver(c)
solver.solution(timeOut = 1)
|
Comment for info of save btn | package com.codemagic.powerhour;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class Dashboard extends Activity {
Preferences myPrefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
myPrefs = new Preferences(this);
}
// method to start playing random songs -- maybe add timer info here
public void startPlaying(View v) {
Toast.makeText(v.getContext(), "Clicked!", Toast.LENGTH_SHORT).show();
}
// will save to the preferences or send directly to timer class
public void saveOpts(View v) {
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.dashboard, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| package com.codemagic.powerhour;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class Dashboard extends Activity {
Preferences myPrefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
myPrefs = new Preferences(this);
}
// method to start playing random songs -- maybe add timer info here
public void startPlaying(View v) {
Toast.makeText(v.getContext(), "Clicked!", Toast.LENGTH_SHORT).show();
}
public void saveOpts(View v) {
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.dashboard, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
Set data default to array | <?php
namespace Jenky\LaravelNotification\Providers;
use Jenky\LaravelNotification\Contracts\Provider as ProviderContract;
abstract class AbstractProvider implements ProviderContract
{
/**
* Config key
*
* @var string
*/
protected $config;
/**
* @var string
*/
protected $view;
/**
* @var int
*/
protected $from;
/**
* @var int
*/
protected $to;
/**
* @var array
*/
protected $data = [];
/**
* Create a new provider instance.
*
* @param string $config
* @return void
*/
public function __construct($config)
{
$this->config = strval($config);
}
/**
* Set the sender id
*
* @param int $id
* @return \Jenky\LaravelNotification\Providers\AbstractProvider
*/
public function from($id)
{
$this->from = $id;
return $this;
}
/**
* Set the receiver id
*
* @param int $id
* @return \Jenky\LaravelNotification\Providers\AbstractProvider
*/
public function to($id)
{
$this->to = $id;
return $this;
}
/**
* Set the notification message.
*
* @return \Jenky\LaravelNotification\Providers\AbstractProvider
*/
abstract public function message();
/**
* Send the notification
*
* @return void
*/
abstract public function send();
protected function getConfig($key)
{
return config("notification.{$config}.{$key}");
}
} | <?php
namespace Jenky\LaravelNotification\Providers;
use Jenky\LaravelNotification\Contracts\Provider as ProviderContract;
abstract class AbstractProvider implements ProviderContract
{
/**
* Config key
*
* @var string
*/
protected $config;
/**
* @var string
*/
protected $view;
/**
* @var int
*/
protected $from;
/**
* @var int
*/
protected $to;
/**
* @var array
*/
protected $data;
/**
* Create a new provider instance.
*
* @param string $config
* @return void
*/
public function __construct($config)
{
$this->config = strval($config);
}
/**
* Set the sender id
*
* @param int $id
* @return \Jenky\LaravelNotification\Providers\AbstractProvider
*/
public function from($id)
{
$this->from = $id;
return $this;
}
/**
* Set the receiver id
*
* @param int $id
* @return \Jenky\LaravelNotification\Providers\AbstractProvider
*/
public function to($id)
{
$this->to = $id;
return $this;
}
/**
* Set the notification message.
*
* @return \Jenky\LaravelNotification\Providers\AbstractProvider
*/
abstract public function message();
/**
* Send the notification
*
* @return void
*/
abstract public function send();
protected function getConfig($key)
{
return config("notification.{$config}.{$key}");
}
} |
FIX Remove some js references | <?php
/**
* @author [email protected]
* @license BSD License http://silverstripe.org/bsd-license/
*/
class SiteDashboardPage extends Page
{
}
class SiteDashboardPage_Controller extends DashboardController
{
private static $dependencies = array(
'dataService' => '%$DataService',
);
public function init()
{
parent::init();
Requirements::css('frontend-dashboards/thirdparty/aristo/aristo.css');
if (class_exists('WebServiceController')) {
Requirements::javascript('webservices/javascript/webservices.js');
}
}
public function Link($action = null)
{
$dashboard = $this->currentDashboard;
if ($dashboard && $dashboard->URLSegment != 'main') {
$identifier = Member::get_unique_identifier_field();
$identifier = $dashboard->Owner()->$identifier;
$segment = $dashboard->URLSegment ? $dashboard->URLSegment : 'main';
return Controller::join_links(
$this->data()->Link(true), 'board', $segment, $dashboard->Owner()->ID, $action
);
} else {
return $this->data()->Link($action ? $action : true);
}
}
}
| <?php
/**
* @author [email protected]
* @license BSD License http://silverstripe.org/bsd-license/
*/
class SiteDashboardPage extends Page
{
}
class SiteDashboardPage_Controller extends DashboardController
{
private static $dependencies = array(
'dataService' => '%$DataService',
);
public function init()
{
parent::init();
Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js');
Requirements::javascript(FRAMEWORK_DIR . '/thirdparty/jquery-ui/jquery-ui.js'); // -1.8.5.custom.min.js');
Requirements::css('frontend-dashboards/thirdparty/aristo/aristo.css');
if (class_exists('WebServiceController')) {
Requirements::javascript('webservices/javascript/webservices.js');
}
}
public function Link($action = null)
{
$dashboard = $this->currentDashboard;
if ($dashboard && $dashboard->URLSegment != 'main') {
$identifier = Member::get_unique_identifier_field();
$identifier = $dashboard->Owner()->$identifier;
$segment = $dashboard->URLSegment ? $dashboard->URLSegment : 'main';
return Controller::join_links(
$this->data()->Link(true), 'board', $segment, $dashboard->Owner()->ID, $action
);
} else {
return $this->data()->Link($action ? $action : true);
}
}
}
|
Fix parsing of fragments without HTML elements. | """Shared utility functions"""
from django.conf import settings
from django.template.defaultfilters import slugify as django_slugify
from django.utils.translation import ugettext_lazy as _
def get_language_name(language_code):
"""Convert a language code into its full (localized) name"""
languages = dict(settings.LANGUAGES)
return _(languages[language_code])
def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
converts spaces to hyphens, and truncates to 50 characters.
"""
slug = django_slugify(value)
slug = slug[:50]
return slug.rstrip('-')
def simple_language_changer(func):
"""
Proxy for the menus.simple_language_changer decorator
If the menus app is not installed, the original function is returned.
This allows view code to be easily decoupled from Django CMS.
"""
if 'menus' in settings.INSTALLED_APPS:
from menus.utils import simple_language_changer
return simple_language_changer(func)
else:
return func
# TODO: Test this a bit, make signature match handlebars implementation
def first_paragraph(value):
import re
from lxml.html import fragments_fromstring, tostring
fragments = fragments_fromstring(value)
if len(fragments):
for fragment in fragments:
if getattr(fragment, 'tag', None) == 'p':
fragment.drop_tag()
return tostring(fragment)
graphs = re.split(r'[\r\n]{2,}', value)
return graphs[0]
| """Shared utility functions"""
from django.conf import settings
from django.template.defaultfilters import slugify as django_slugify
from django.utils.translation import ugettext_lazy as _
def get_language_name(language_code):
"""Convert a language code into its full (localized) name"""
languages = dict(settings.LANGUAGES)
return _(languages[language_code])
def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
converts spaces to hyphens, and truncates to 50 characters.
"""
slug = django_slugify(value)
slug = slug[:50]
return slug.rstrip('-')
def simple_language_changer(func):
"""
Proxy for the menus.simple_language_changer decorator
If the menus app is not installed, the original function is returned.
This allows view code to be easily decoupled from Django CMS.
"""
if 'menus' in settings.INSTALLED_APPS:
from menus.utils import simple_language_changer
return simple_language_changer(func)
else:
return func
# TODO: Test this a bit, make signature match handlebars implementation
def first_paragraph(value):
import re
from lxml.html import fragments_fromstring, tostring
fragments = fragments_fromstring(value)
if len(fragments):
for fragment in fragments:
if fragment.tag == 'p':
fragment.drop_tag()
return tostring(fragment)
graphs = re.split(r'[\r\n]{2,}', value)
return graphs[0]
|
Add convenience methods for creating/deleting all tables, for bootstrapping/testing use
Signed-off-by: Joonas Bergius <[email protected]> | from __future__ import unicode_literals
import os
import pdb
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
class Model(object):
def __repr__(self):
cols = self.__mapper__.c.keys()
class_name = self.__class__.__name__
items = ', '.join(['%s=%s' % (col, repr(getattr(self, col))) for col
in cols])
return '%s(%s)' % (class_name, items)
def attrs_dict(self):
keys = self.__mapper__.c.keys()
attrs = {}
for key in keys:
attrs[key] = getattr(self, key)
return attrs
class SQLAlchemy(object):
def __init__(self):
self.session = self.create_session()
self.Model = self.make_declarative_base()
@property
def engine(self):
dburl = os.environ['DATABASE_URL']
return create_engine(dburl)
def create_session(self):
session = scoped_session(sessionmaker())
session.configure(bind=self.engine)
return session
def make_declarative_base(self):
base = declarative_base(cls=Model)
base.query = self.session.query_property()
return base
def drop_all(self):
self.Model.metadata.drop_all(bind=self.engine)
def create_all(self):
self.Model.metadata.create_all(bind=self.engine)
db = SQLAlchemy()
all = [db]
def rollback(*_):
db.session.rollback() | from __future__ import unicode_literals
import os
import pdb
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
class Model(object):
def __repr__(self):
cols = self.__mapper__.c.keys()
class_name = self.__class__.__name__
items = ', '.join(['%s=%s' % (col, repr(getattr(self, col))) for col
in cols])
return '%s(%s)' % (class_name, items)
def attrs_dict(self):
keys = self.__mapper__.c.keys()
attrs = {}
for key in keys:
attrs[key] = getattr(self, key)
return attrs
class SQLAlchemy(object):
def __init__(self):
self.session = self.create_session()
self.Model = self.make_declarative_base()
@property
def engine(self):
dburl = os.environ['DATABASE_URL']
return create_engine(dburl)
def create_session(self):
session = scoped_session(sessionmaker())
session.configure(bind=self.engine)
return session
def make_declarative_base(self):
base = declarative_base(cls=Model)
base.query = self.session.query_property()
return base
db = SQLAlchemy()
all = [db]
def rollback(*_):
db.session.rollback() |
Remove multiline for node users | const through = require('through2');
const path = require('path');
const util = require('util');
function injectReact() {
return '' +
';const scope = window.__hmr = (window.__hmr || {});' +
'(function() {' +
'if (typeof window === \'undefined\') return;' +
'if (!scope.initialized) {' +
'require(\'browserify-react-live/browserify/injectReactDeps\')(scope);' +
'require(\'browserify-react-live/browserify/injectWebSocket\')(scope);' +
'scope.initialized = true;' +
'}' +
'})();';
}
function overrideRequire() {
return '' +
'require = require(\'browserify-react-live/browserify/overrideRequire\')' +
'(scope, require);';
}
function overrideExports() {
return '' +
';(function() {' +
'if (module.exports.name || module.exports.displayName) {' +
'module.exports = scope.makeHot(module.exports);' +
'}' +
'})();';
}
module.exports = function applyReactHotAPI(file, options) {
var content = [];
return through(
function transform(part, enc, next) {
content.push(part);
next();
},
function finish(done) {
content = content.join('');
const bundle = util.format('%s%s%s%s',
injectReact(),
overrideRequire(),
content,
overrideExports()
);
this.push(bundle);
done();
}
);
};
| const through = require('through2');
const path = require('path');
const util = require('util');
function injectReact() {
return `
;const scope = window.__hmr = (window.__hmr || {});
(function() {
if (typeof window === 'undefined') return;
if (!scope.initialized) {
require('browserify-react-live/browserify/injectReactDeps')(scope);
require('browserify-react-live/browserify/injectWebSocket')(scope);
scope.initialized = true;
}
})();
`;
}
function overrideRequire() {
return `
require = require('browserify-react-live/browserify/overrideRequire')(scope, require);
`;
}
function overrideExports() {
return `
;(function() {
if (module.exports.name || module.exports.displayName) {
module.exports = scope.makeHot(module.exports);
}
})();
`;
}
module.exports = function applyReactHotAPI(file, options) {
var content = [];
return through(
function transform(part, enc, next) {
content.push(part);
next();
},
function finish(done) {
content = content.join('');
const bundle = util.format('%s%s%s%s',
injectReact(),
overrideRequire(),
content,
overrideExports()
);
this.push(bundle);
done();
}
);
};
|
Remove "utility.hmac.hmac_creation" which causes circular imports
Hacky but re-implement `hmac_creation` as `create_hmac` | """This module contains gn2 decorators"""
import hashlib
import hmac
from flask import current_app, g
from typing import Dict
from functools import wraps
import json
import requests
def create_hmac(data: str, secret: str) -> str:
return hmac.new(bytearray(secret, "latin-1"),
bytearray(data, "utf-8"),
hashlib.sha1).hexdigest[:20]
def edit_access_required(f):
"""Use this for endpoints where admins are required"""
@wraps(f)
def wrap(*args, **kwargs):
resource_id: str = ""
if kwargs.get("inbredset_id"): # data type: dataset-publish
resource_id = create_hmac(
data=("dataset-publish:"
f"{kwargs.get('inbredset_id')}:"
f"{kwargs.get('name')}"),
secret=current_app.config.get("SECRET_HMAC_CODE"))
if kwargs.get("dataset_name"): # data type: dataset-probe
resource_id = create_hmac(
data=("dataset-probeset:"
f"{kwargs.get('dataset_name')}"),
secret=current_app.config.get("SECRET_HMAC_CODE"))
response: Dict = {}
try:
_user_id = g.user_session.record.get(b"user_id",
"").decode("utf-8")
response = json.loads(
requests.get(GN_PROXY_URL + "available?resource="
f"{resource_id}&user={_user_id}").content)
except:
response = {}
if "edit" not in response.get("data", []):
return "You need to be admin", 401
return f(*args, **kwargs)
return wrap
| """This module contains gn2 decorators"""
from flask import g
from typing import Dict
from functools import wraps
from utility.hmac import hmac_creation
from utility.tools import GN_PROXY_URL
import json
import requests
def edit_access_required(f):
"""Use this for endpoints where admins are required"""
@wraps(f)
def wrap(*args, **kwargs):
resource_id: str = ""
if kwargs.get("inbredset_id"): # data type: dataset-publish
resource_id = hmac_creation("dataset-publish:"
f"{kwargs.get('inbredset_id')}:"
f"{kwargs.get('name')}")
if kwargs.get("dataset_name"): # data type: dataset-probe
resource_id = hmac_creation("dataset-probeset:"
f"{kwargs.get('dataset_name')}")
response: Dict = {}
try:
_user_id = g.user_session.record.get(b"user_id",
"").decode("utf-8")
response = json.loads(
requests.get(GN_PROXY_URL + "available?resource="
f"{resource_id}&user={_user_id}").content)
except:
response = {}
if "edit" not in response.get("data", []):
return "You need to be admin", 401
return f(*args, **kwargs)
return wrap
|
Use INFOSYSTEM enviroment for Queue | import flask
from pika import BlockingConnection, PlainCredentials, ConnectionParameters
class RabbitMQ:
def __init__(self):
self.url = flask.current_app.config['INFOSYSTEM_QUEUE_URL']
self.port = flask.current_app.config['INFOSYSTEM_QUEUE_PORT']
self.virtual_host = \
flask.current_app.config['INFOSYSTEM_QUEUE_VIRTUAL_HOST']
self.username = flask.current_app.config['INFOSYSTEM_QUEUE_USERNAME']
self.password = flask.current_app.config['INFOSYSTEM_QUEUE_PASSWORD']
credentials = PlainCredentials(self.username, self.password)
self.params = ConnectionParameters(
self.url, self.port, self.virtual_host, credentials)
def connect(self):
try:
return BlockingConnection(self.params)
except Exception as e:
raise
class ProducerQueue:
def __init__(self, exchange, exchange_type):
rabbitMQ = RabbitMQ()
self.connection = rabbitMQ.connect()
self.exchange = exchange
self.channel = self.connection.channel()
self.channel.exchange_declare(
exchange=exchange, exchange_type=exchange_type, durable=True)
def publish(self, routing_key):
body = ""
self.channel.basic_publish(
exchange=self.exchange, routing_key=routing_key, body=body)
self.close()
def close(self):
self.channel.close()
self.connection.close()
| import flask
from pika import BlockingConnection, PlainCredentials, ConnectionParameters
class RabbitMQ:
def __init__(self):
self.url = flask.current_app.config['ORMENU_QUEUE_URL']
self.port = flask.current_app.config['ORMENU_QUEUE_PORT']
self.virtual_host = \
flask.current_app.config['ORMENU_QUEUE_VIRTUAL_HOST']
self.username = flask.current_app.config['ORMENU_QUEUE_USERNAME']
self.password = flask.current_app.config['ORMENU_QUEUE_PASSWORD']
credentials = PlainCredentials(self.username, self.password)
self.params = ConnectionParameters(
self.url, self.port, self.virtual_host, credentials)
def connect(self):
try:
return BlockingConnection(self.params)
except Exception as e:
raise
class ProducerQueue:
def __init__(self, exchange, exchange_type):
rabbitMQ = RabbitMQ()
self.connection = rabbitMQ.connect()
self.exchange = exchange
self.channel = self.connection.channel()
self.channel.exchange_declare(
exchange=exchange, exchange_type=exchange_type, durable=True)
def publish(self, routing_key):
body = ""
self.channel.basic_publish(
exchange=self.exchange, routing_key=routing_key, body=body)
self.close()
def close(self):
self.channel.close()
self.connection.close()
|
Update Complete checkpoint 7 Services Part 2 |
(function() {
function SongPlayer() {
var SongPlayer = {};
var currentSong = null;
var currentBuzzObject = null;
/**
* @function setSong
* @desc Stops currently playing song and loads new audio file as currentBuzzObject
* @param {Object} song
*/
var setSong = function(song) {
if (currentBuzzObject) {
currentBuzzObject.stop();
currentSong.playing = null;
}
/**
* @desc Buzz object audio file
* @type {Object}
*/
currentBuzzObject = new buzz.sound(song.audioUrl, {
formats: ['mp3'],
preload: true
});
currentSong = song;
};
SongPlayer.play = function(song) {
if (currentSong !== song) {
setSong(song);
currentBuzzObject.play();
song.playing = true;
} else if (currentSong === song) {
if (currentBuzzObject.isPaused()) {
currentBuzzObject.play();
}
}
};
SongPlayer.pause = function(song) {
currentBuzzObject.pause();
song.playing = false;
};
return SongPlayer;
}
angular
.module('blocJams')
.factory('SongPlayer', SongPlayer);
})(); |
(function() {
function SongPlayer() {
var SongPlayer = {};
var currentSong = null;
var currentBuzzObject = null;
var setSong = function(song) {
if (currentBuzzObject) {
currentBuzzObject.stop();
currentSong.playing = null;
}
currentBuzzObject = new buzz.sound(song.audioUrl, {
formats: ['mp3'],
preload: true
});
currentSong = song;
};
SongPlayer.play = function(song) {
if (currentSong !== song) {
if (currentBuzzObject) {
currentBuzzObject.stop();
currentSong.playing = null;
}
currentBuzzObject = new buzz.sound(song.audioUrl, {
formats: ['mp3'],
preload: true
});
currentSong = song;
currentBuzzObject.play();
song.playing = true;
} else if (currentSong === song) {
if (currentBuzzObject.isPaused()) {
currentBuzzObject.play();
}
}
};
SongPlayer.pause = function(song) {
currentBuzzObject.pause();
song.playing = false;
};
return SongPlayer;
}
angular
.module('blocJams')
.factory('SongPlayer', SongPlayer);
})(); |
Fix ambiguity in field of worker | <?php
require_once '../svg.php';
include '../init.php';
if (isset($_GET['id'])) {
$sql = "SELECT `wm_workers`.`id` as `woker_id`, `user_id`, ".
"`worker_name`, `wm_workers`.`description`, `url`, ".
"`latest_heartbeat`, ".
"`display_name` ".
"FROM `wm_workers` ".
"JOIN `wm_users` ON `user_id` = `wm_users`.`id`".
"WHERE `wm_workers`.`id` = :wid";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':wid', $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$worker = $stmt->fetchObject();
}
echo $twig->render('worker.twig', array('heading' => 'Worker',
'file' => "worker",
'logged_in' => is_logged_in(),
'display_name' => $_SESSION['display_name'],
'user_id' => $user->id,
'worker' => $worker
)
);
?> | <?php
require_once '../svg.php';
include '../init.php';
if (isset($_GET['id'])) {
$sql = "SELECT `wm_workers`.`id` as `woker_id`, `user_id`, ".
"`worker_name`, `description`, `url`, `latest_heartbeat`, ".
"`display_name` ".
"FROM `wm_workers` ".
"JOIN `wm_users` ON `user_id` = `wm_users`.`id`".
"WHERE `wm_workers`.`id` = :wid";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':wid', $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$worker = $stmt->fetchObject();
}
echo $twig->render('worker.twig', array('heading' => 'Worker',
'file' => "worker",
'logged_in' => is_logged_in(),
'display_name' => $_SESSION['display_name'],
'user_id' => $user->id,
'worker' => $worker
)
);
?> |
Make open_fred an optional dependency | import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="feedinlib",
version="0.1.0rc3",
description="Creating time series from pv or wind power plants.",
url="http://github.com/oemof/feedinlib",
author="oemof developer group",
author_email="[email protected]",
license="MIT",
packages=["feedinlib"],
long_description=read("README.rst"),
long_description_content_type="text/x-rst",
zip_safe=False,
install_requires=[
"cdsapi >= 0.1.4",
"geopandas",
"numpy >= 1.7.0",
"oedialect >= 0.0.6.dev0",
"pvlib >= 0.7.0",
"tables",
"windpowerlib >= 0.2.0",
"pandas >= 0.13.1",
"xarray >= 0.12.0",
"descartes"
],
extras_require={
"dev": [
"jupyter",
"nbformat",
"punch.py",
"pytest",
"sphinx_rtd_theme",
],
"data-sources": [
"open_FRED-cli",
],
"examples": ["jupyter",
"matplotlib",
"descartes"],
},
)
| import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="feedinlib",
version="0.1.0rc3",
description="Creating time series from pv or wind power plants.",
url="http://github.com/oemof/feedinlib",
author="oemof developer group",
author_email="[email protected]",
license="MIT",
packages=["feedinlib"],
long_description=read("README.rst"),
long_description_content_type="text/x-rst",
zip_safe=False,
install_requires=[
"cdsapi >= 0.1.4",
"geopandas",
"numpy >= 1.7.0",
"oedialect >= 0.0.6.dev0",
"open_FRED-cli",
"pvlib >= 0.7.0",
"tables",
"windpowerlib >= 0.2.0",
"pandas >= 0.13.1",
"xarray >= 0.12.0",
"descartes"
],
extras_require={
"dev": [
"jupyter",
"nbformat",
"punch.py",
"pytest",
"sphinx_rtd_theme",
],
"examples": ["jupyter",
"matplotlib",
"descartes"],
},
)
|
Remove unused "use statement" from the test | <?php
namespace Asmaster\EquipTwig\Tests;
use Asmaster\EquipTwig\TwigFormatter;
use Equip\Adr\PayloadInterface;
use PHPUnit_Framework_TestCase as TestCase;
use Twig_Environment as TwigEnvironment;
use Twig_Loader_Filesystem as TwigLoaderFilesystem;
class TwigFormatterTest extends TestCase
{
/**
* @var TwigFormatter
*/
private $formatter;
protected function setUp()
{
$loader = new TwigLoaderFilesystem(__DIR__.'/Asset/templates');
$this->formatter = new TwigFormatter(
new TwigEnvironment($loader)
);
}
public function testAccepts()
{
$this->assertEquals(['text/html'], TwigFormatter::accepts());
}
public function testType()
{
$this->assertEquals('text/html', $this->formatter->type());
}
public function testResponse()
{
$template = 'test.html.twig';
$output = [
'header' => 'header',
'body' => 'body',
'footer' => 'footer'
];
$payload = $this->getMock(PayloadInterface::class);
$payload->expects($this->any())
->method('getOutput')
->willReturn($output);
$payload->expects($this->any())
->method('getSetting')
->willReturn($template);
$body = $this->formatter->body($payload);
$this->assertEquals("<h1>header</h1>\n<p>body</p>\n<span>footer</span>\n", $body);
}
}
| <?php
namespace Asmaster\EquipTwig\Tests;
use Asmaster\EquipTwig\TwigFormatter;
use Equip\Adr\PayloadInterface;
use Lukasoppermann\Httpstatus\Httpstatus;
use PHPUnit_Framework_TestCase as TestCase;
use Twig_Environment as TwigEnvironment;
use Twig_Loader_Filesystem as TwigLoaderFilesystem;
class TwigFormatterTest extends TestCase
{
/**
* @var TwigFormatter
*/
private $formatter;
protected function setUp()
{
$loader = new TwigLoaderFilesystem(__DIR__.'/Asset/templates');
$this->formatter = new TwigFormatter(
new TwigEnvironment($loader),
new HttpStatus
);
}
public function testAccepts()
{
$this->assertEquals(['text/html'], TwigFormatter::accepts());
}
public function testType()
{
$this->assertEquals('text/html', $this->formatter->type());
}
public function testResponse()
{
$template = 'test.html.twig';
$output = [
'header' => 'header',
'body' => 'body',
'footer' => 'footer'
];
$payload = $this->getMock(PayloadInterface::class);
$payload->expects($this->any())
->method('getOutput')
->willReturn($output);
$payload->expects($this->any())
->method('getSetting')
->willReturn($template);
$body = $this->formatter->body($payload);
$this->assertEquals("<h1>header</h1>\n<p>body</p>\n<span>footer</span>\n", $body);
}
}
|
Add add function taking a functor as input to process connected primitives | """@package Primitive
This module provides an abstraction of the relationGraph using networkX
"""
import networkx as nx
import packages.primitive as primitive
class RelationGraph(object):
def __init__(self,primArray, assignArray):
self.G=nx.Graph()
self.indexedPrimArray = {}
# First create the nodes
for p in primArray:
self.G.add_node(p.uid, w=0)
self.indexedPrimArray[p.uid] = p
# Then their relations
for idx1, p1 in enumerate(primArray):
for idx2, p2 in enumerate(primArray):
if (idx2 > idx1):
self.G.add_edge(p1.uid, p2.uid)
# And finaly the node weights (number of samples)
# assignArray[][0] = point id
# assignArray[][1] = primitive uid
for a in assignArray:
if a[1] in self.G.node:
self.G.node[a[1]]['w'] += 1
#print "Number of primitives: ",self.G.number_of_nodes()
#print "Number of connections: ",self.G.number_of_edges()
# Call the functor over the primitives connected by and edge
def processConnectedNodes(self, functor):
for e in self.G.edges():
functor( self.indexedPrimArray[e[0]], self.indexedPrimArray[e[1]])
def draw(self):
nx.draw_spectral(self.G)
#nx.draw_networkx_labels(self.G,pos=nx.spectral_layout(self.G))
| """@package Primitive
This module provides an abstraction of the relationGraph using networkX
"""
import networkx as nx
import packages.primitive as primitive
class RelationGraph(object):
def __init__(self,primArray, assignArray):
self.G=nx.Graph()
# First create the nodes
for p in primArray:
self.G.add_node(p.uid, w=0)
# Then their relations
for idx1, p1 in enumerate(primArray):
for idx2, p2 in enumerate(primArray):
if (idx2 > idx1):
self.G.add_edge(p1.uid, p2.uid)
# And finaly the node weights (number of samples)
# assignArray[][0] = point id
# assignArray[][1] = primitive uid
for a in assignArray:
if a[1] in self.G.node:
self.G.node[a[1]]['w'] += 1
#print "Number of primitives: ",self.G.number_of_nodes()
#print "Number of connections: ",self.G.number_of_edges()
def draw(self):
nx.draw_spectral(self.G)
#nx.draw_networkx_labels(self.G,pos=nx.spectral_layout(self.G))
|
Update `git status` to use machine output -z. | /*jshint node: true */
var _ = require('underscore');
var _s = require('underscore.string');
var exec = require('shelljs').exec;
var fs = require('fs');
var cachedFileList;
module.exports = {
all: function() {
var list;
var response;
// Return cache if we have one
if (cachedFileList) {
return cachedFileList;
}
response = exec('git status --porcelain -z', {silent: true, async: false}).output;
list = _s.trim(response).split(/\0/);
// Staged files
list = _.filter(list, function(line) {
return line.match(/^A./);
});
// Remove prefixes
list = _.map(list, function(line) {
return line.substr(3);
});
// Expand paths
list = _.flatten(_.compact(_.map(list, function(name) {
if (name.match(/\/$/)) {
return fs.readdirSync(name);
} else {
return name;
}
})));
cachedFileList = list;
return list;
},
filter: function(suffix) {
suffix = _s.ltrim(suffix, '.');
return _.filter(module.exports.all(), function(name) {
return name.match(new RegExp('\\.' + suffix + '$'));
});
}
};
| /*jshint node: true */
var _ = require('underscore');
var _s = require('underscore.string');
var exec = require('shelljs').exec;
var fs = require('fs');
var cachedFileList;
module.exports = {
all: function() {
var list;
var response;
// Return cache if we have one
if (cachedFileList) {
return cachedFileList;
}
response = exec('git status --porcelain', {silent: true, async: false}).output;
list = _s.trim(response).split(/\n/);
// Staged files
list = _.filter(list, function(line) {
return line.match(/^A./);
});
// Remove prefixes
list = _.map(list, function(line) {
return line.substr(3);
});
// Expand paths
list = _.flatten(_.compact(_.map(list, function(name) {
if (name.match(/\/$/)) {
return fs.readdirSync(name);
} else {
return name;
}
})));
cachedFileList = list;
return list;
},
filter: function(suffix) {
suffix = _s.ltrim(suffix, '.');
return _.filter(module.exports.all(), function(name) {
return name.match(new RegExp('\\.' + suffix + '$'));
});
}
};
|
Make it compatible with old browsers | /* eslint-env amd */
(function (name, definition) {
if (typeof define === 'function') {
// AMD
define(definition)
} else if (typeof module !== 'undefined' && module.exports) {
// Node.js
module.exports = definition()
} else {
// Browser
window[name] = definition()
}
})('nullPrune', function () {
function isObject (input) {
return input && (typeof input === 'object')
}
function ownKeys (obj) {
var key
var ownKeys = []
var hasOwnProperty = Object.prototype.hasOwnProperty
for (key in obj) {
if (hasOwnProperty.call(obj, key)) {
ownKeys.push(key)
}
}
return ownKeys
}
function nullPrune (inputObject, context) {
var objectKey = context.objectKey
var parentObject = context.parentObject
var keys = ownKeys(inputObject)
var k
var key
var node
for (k in keys) {
key = keys[k]
node = inputObject[key]
if (isObject(node)) {
nullPrune(node, {
objectKey: key,
parentObject: inputObject
})
} else if (node == null) {
delete inputObject[key]
}
}
if (parentObject && ownKeys(inputObject).length === 0) {
delete parentObject[objectKey]
}
}
return function (inputObject) {
if (!isObject(inputObject)) {
return inputObject
}
nullPrune(inputObject, {})
return inputObject
}
})
| /* eslint-env amd */
(function (name, definition) {
if (typeof define === 'function') {
// AMD
define(definition)
} else if (typeof module !== 'undefined' && module.exports) {
// Node.js
module.exports = definition()
} else {
// Browser
window[name] = definition()
}
})('nullPrune', function () {
function hasOwnProperty (obj, property) {
return Object.prototype.hasOwnProperty.call(obj, property)
}
function isObject (input) {
return input && (typeof input === 'object')
}
function keys (obj) {
var key
var ownKeys = []
for (key in obj) {
if (hasOwnProperty(obj, key)) {
ownKeys.push(key)
}
}
return ownKeys
}
function nullPrune (inputObject, context) {
var objectKey = context.objectKey
var parentObject = context.parentObject
keys(inputObject).forEach(function (key) {
var node = inputObject[key]
if (isObject(node)) {
nullPrune(node, {
objectKey: key,
parentObject: inputObject
})
} else if (node == null) {
delete inputObject[key]
}
})
if (parentObject && keys(inputObject).length === 0) {
delete parentObject[objectKey]
}
}
return function (inputObject) {
if (!isObject(inputObject)) {
return inputObject
}
nullPrune(inputObject, {})
return inputObject
}
})
|
Use location.pathname as a key for transition | import React from 'react';
import Transition from 'react-transition-group/CSSTransitionGroup';
import {
BrowserRouter as Router,
Route,
Switch,
} from 'react-router-dom';
import Header from './Header';
import HomePage from './HomePage';
import BlogPage from './BlogPage';
import PostContainer from './PostContainer';
import ProjectsPage from './ProjectsPage';
import Footer from './Footer';
import PageNotFound from './PageNotFound';
function App() {
return (
<Router>
<div className="app">
<Header className="app__header" />
<div className="app__content">
<Route
render={({ location }) => (
<Transition
transitionName="fade"
transitionEnterTimeout={250}
transitionLeave={false}
>
<Switch key={location.pathname}>
<Route
exact path="/"
component={HomePage}
/>
<Route
exact path="/blog"
component={BlogPage}
/>
<Route
exact path="/blog/:slug"
component={PostContainer}
/>
<Route
exact path="/tag/:tag"
component={BlogPage}
/>
<Route
path="/projects"
component={ProjectsPage}
/>
<Route location={location} component={PageNotFound} />
</Switch>
</Transition>
)}
/>
</div>
<Footer className="app__footer" />
</div>
</Router>
);
}
export default App;
| import React from 'react';
import Transition from 'react-transition-group/CSSTransitionGroup';
import {
BrowserRouter as Router,
Route,
Switch,
} from 'react-router-dom';
import Header from './Header';
import HomePage from './HomePage';
import BlogPage from './BlogPage';
import PostContainer from './PostContainer';
import ProjectsPage from './ProjectsPage';
import Footer from './Footer';
import PageNotFound from './PageNotFound';
function App() {
return (
<Router>
<div className="app">
<Header className="app__header" />
<div className="app__content">
<Route
render={({ location }) => (
<Transition
transitionName="fade"
transitionAppear
transitionAppearTimeout={250}
transitionEnterTimeout={250}
transitionLeave={false}
>
<Switch key={location.key}>
<Route
exact path="/"
component={HomePage}
/>
<Route
exact path="/blog"
component={BlogPage}
/>
<Route
exact path="/blog/:slug"
component={PostContainer}
/>
<Route
exact path="/tag/:tag"
component={BlogPage}
/>
<Route
path="/projects"
component={ProjectsPage}
/>
<Route location={location} component={PageNotFound} />
</Switch>
</Transition>
)}
/>
</div>
<Footer className="app__footer" />
</div>
</Router>
);
}
export default App;
|
Fix call id parameter name | 'use strict';
/*
* Module for juggling call state.
*/
angular.module('call', [])
.factory('callFactory', function (apiFactory) {
var callStates = {
error: 'error',
not_answered: 'not_answered',
succeeded: 'succeeded'
};
var currentCallID = null;
var initiateCall = function (recipient) {
return new Promise(function (resolve, reject) {
apiFactory.call.initiate(recipient)
.then(function (newCall) {
console.log(newCall);
currentCallID = newCall.id;
resolve(newCall);
})
.catch(function (callErr) {
reject(callErr);
});
});
};
var endCall = function (finalStatus) {
return new Promise(function (resolve, reject) {
if (!currentCallID) {
return reject(new Error('Current call ID is null!'));
}
apiFactory.call.end(finalStatus, currentCallID)
.then(function (endedCall) {
resolve(endedCall);
})
.catch(function (error) {
reject(error);
})
.finally(function () {
currentCallID = null;
});
});
};
return {
initiateCall: initiateCall,
callStates: callStates,
callError: function () {
return endCall(callStates.error);
},
callSucceeded: function () {
return endCall(callStates.succeeded);
},
callNotAnswered: function () {
return endCall(callStates.not_answered);
}
};
});
| 'use strict';
/*
* Module for juggling call state.
*/
angular.module('call', [])
.factory('callFactory', function (apiFactory) {
var callStates = {
error: 'error',
not_answered: 'not_answered',
succeeded: 'succeeded'
};
var currentCallID = null;
var initiateCall = function (recipient) {
return new Promise(function (resolve, reject) {
apiFactory.call.initiate(recipient)
.then(function (newCall) {
currentCallID = newCall.CallId;
resolve(newCall);
})
.catch(function (callErr) {
reject(callErr);
});
});
};
var endCall = function (finalStatus) {
return new Promise(function (resolve, reject) {
if (!currentCallID) {
return reject(new Error('Current call ID is null!'));
}
apiFactory.call.end(finalStatus, currentCallID)
.then(function (endedCall) {
resolve(endedCall);
})
.catch(function (error) {
reject(error);
})
.finally(function () {
currentCallID = null;
});
});
};
return {
initiateCall: initiateCall,
callStates: callStates,
callError: function () {
return endCall(callStates.error);
},
callSucceeded: function () {
return endCall(callStates.succeeded);
},
callNotAnswered: function () {
return endCall(callStates.not_answered);
}
};
});
|
Implement feedback from rhys' comments | /*
* Copyright (C) 2016 IBM Corp. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.cloudant.sync.query;
/**
* Created by tomblench on 28/09/2016.
*/
public class FieldSort {
public final String field;
public final Direction sort;
public FieldSort(String field) {
this(field, Direction.ASCENDING);
}
public FieldSort(String field, Direction sort) {
this.field = field;
this.sort = sort;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FieldSort fieldSort = (FieldSort) o;
if (!field.equals(fieldSort.field)) {
return false;
}
return sort == fieldSort.sort;
}
@Override
public int hashCode() {
int result = field.hashCode();
result = 31 * result + sort.hashCode();
return result;
}
@Override
public String toString() {
return "FieldSort{" +
"field='" + field + '\'' +
", sort=" + sort +
'}';
}
public enum Direction {
ASCENDING,
DESCENDING
};
}
| package com.cloudant.sync.query;
/**
* Created by tomblench on 28/09/2016.
*/
public class FieldSort {
public final String field;
public final Direction sort;
public FieldSort(String field) {
this.field = field;
this.sort = Direction.ASCENDING;
}
public FieldSort(String field, Direction sort) {
this.field = field;
this.sort = sort;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FieldSort fieldSort = (FieldSort) o;
if (!field.equals(fieldSort.field)) {
return false;
}
return sort == fieldSort.sort;
}
@Override
public int hashCode() {
int result = field.hashCode();
result = 31 * result + sort.hashCode();
return result;
}
@Override
public String toString() {
return "FieldSort{" +
"field='" + field + '\'' +
", sort=" + sort +
'}';
}
public enum Direction {
ASCENDING,
DESCENDING
};
}
|
Add checks against invalid search input | var minimatch = require('minimatch');
var is = require('annois');
var fp = require('annofp');
var zip = require('annozip');
module.exports = function(model, query, cb) {
if(!is.object(query) || fp.count(query) === 0) {
return is.fn(cb)? cb(null, model._data): query(null, model._data);
}
var fields = query.fields;
var limit = query.limit;
var offset = query.offset || 0;
delete query.fields;
delete query.limit;
delete query.offset;
var zq = zip(query);
var ret = model._data;
if(fp.count(query)) {
ret = ret.filter(function(o) {
return zq.map(function(p) {
var a = o[p[0]]? o[p[0]].toLowerCase(): '';
var b = p[1]? p[1].toLowerCase(): '';
return minimatch(a, b);
}).filter(fp.id).length > 0;
});
}
if(fields) {
fields = is.array(fields)? fields: [fields];
ret = ret.map(function(o) {
var r = {};
fields.forEach(function(k) {
r[k] = o[k];
});
return r;
});
}
if(limit) {
ret = ret.slice(offset, offset + limit);
}
cb(null, ret);
};
| var minimatch = require('minimatch');
var is = require('annois');
var fp = require('annofp');
var zip = require('annozip');
module.exports = function(model, query, cb) {
if(!is.object(query) || fp.count(query) === 0) {
return is.fn(cb)? cb(null, model._data): query(null, model._data);
}
var fields = query.fields;
var limit = query.limit;
var offset = query.offset || 0;
delete query.fields;
delete query.limit;
delete query.offset;
var zq = zip(query);
var ret = model._data;
if(fp.count(query)) {
ret = ret.filter(function(o) {
return zq.map(function(p) {
return minimatch(o[p[0]].toLowerCase(), p[1].toLowerCase());
}).filter(fp.id).length > 0;
});
}
if(fields) {
fields = is.array(fields)? fields: [fields];
ret = ret.map(function(o) {
var r = {};
fields.forEach(function(k) {
r[k] = o[k];
});
return r;
});
}
if(limit) {
ret = ret.slice(offset, offset + limit);
}
cb(null, ret);
};
|
Remove let until upstream Ember-CLI issue is fixed | /* jshint node: true */
'use strict';
var request = require('request');
var BasePlugin = require('ember-cli-deploy-plugin');
module.exports = {
name: 'ember-cli-deploy-cdnify-purge-cache',
createDeployPlugin: function(options) {
var DeployPlugin = BasePlugin.extend({
name: options.name,
requiredConfig: ['cdnifyResourceId', 'cdnifyApiKey'],
didDeploy: function(context) {
var config = context.config['cdnify-purge-cache']
var apiKey = config['cdnifyApiKey'];
var resourceId = config['cdnifyResourceId'];
var endpoint = `cdnify.com/api/v1/resources/${resourceId}/cache`;
var credentials = `${apiKey}:x`;
var self = this;
return new Promise(function(resolve, reject) {
request({
url: `https://${credentials}@${endpoint}`,
method: "DELETE"
}, function(error, response, body) {
if(error) {
self.log("CDNIFY CACHE *NOT* PURGED!", { verbose: true });
reject(error);
} else {
self.log("CDNIFY CACHE PURGED!", { verbose: true });
resolve(body);
}
})
});
}
});
return new DeployPlugin();
}
};
| /* jshint node: true */
'use strict';
var request = require('request');
var BasePlugin = require('ember-cli-deploy-plugin');
module.exports = {
name: 'ember-cli-deploy-cdnify-purge-cache',
createDeployPlugin: function(options) {
var DeployPlugin = BasePlugin.extend({
name: options.name,
requiredConfig: ['cdnifyResourceId', 'cdnifyApiKey'],
didDeploy: function(context) {
let config = context.config['cdnify-purge-cache']
let apiKey = config['cdnifyApiKey'];
let resourceId = config['cdnifyResourceId'];
let endpoint = `cdnify.com/api/v1/resources/${resourceId}/cache`;
let credentials = `${apiKey}:x`;
var self = this;
return new Promise(function(resolve, reject) {
request({
url: `https://${credentials}@${endpoint}`,
method: "DELETE"
}, function(error, response, body) {
if(error) {
self.log("CDNIFY CACHE *NOT* PURGED!", { verbose: true });
reject(error);
} else {
self.log("CDNIFY CACHE PURGED!", { verbose: true });
resolve(body);
}
})
});
}
});
return new DeployPlugin();
}
};
|
Add iscroll reference into the element in order to allow the element to manipulate if (for instance the refresh) NOT REALY NICE WAY DO TO THAT, BUT SIMPLE |
vinisketch.directive ('vsScrollable', function () {
return {
replace: false,
restrict: 'A',
link: function (scope, element, attr) {
// default options
var options = {
// scroll only vertically
scrollX: false,
scrollY: true,
// paint scrollbars
scrollbars: true,
// make scrollbars draggable
interactiveScrollbars: true,
// allow scrolling by wheel
mouseWheel: true
};
// iScroll initialize function
function setScroll () {
element[0].__iscroll = new window.IScroll (element[0], options);
}
// watch for 'ng-scrollable' directive in html code
scope.$watch (attr.vsScrollable, function () {
if (attr.vsScrollable == undefined) {
// clean iscrall
if (element[0].__iscroll) {
element[0].__iscroll.destroy ();
element[0].__iscroll = null;
}
return;
}
setScroll ();
});
element.on ('$destroy', function() {
if (element[0].__iscroll) {
element[0].__iscroll.destroy ();
element[0].__iscroll = null;
}
console.log ("vsScrollable $destroy");
});
}
}
}); |
vinisketch.directive ('vsScrollable', function () {
return {
replace: false,
restrict: 'A',
link: function (scope, element, attr) {
// default options
var options = {
// scroll only vertically
scrollX: false,
scrollY: true,
// paint scrollbars
scrollbars: true,
// make scrollbars draggable
interactiveScrollbars: true,
// allow scrolling by wheel
mouseWheel: true
};
var iScrollRef;
// iScroll initialize function
function setScroll () {
iScrollRef = new window.IScroll (element[0], options);
}
// watch for 'ng-scrollable' directive in html code
scope.$watch (attr.vsScrollable, function () {
if (attr.vsScrollable == undefined) {
// clean iscrall
if (iScrollRef) {
iScrollRef.destroy ();
iScrollRef = null;
}
return;
}
setScroll ();
});
element.on ('$destroy', function() {
if (iScrollRef) {
iScrollRef.destroy ();
iScrollRef = null;
}
console.log ("vsScrollable $destroy");
});
}
}
}); |
Write buyer ID when converting delivery logs. | package com.pinterest.secor.io.impl;
import com.pinterest.secor.common.SecorConfig;
import com.pinterest.secor.io.AdgearReader;
import com.pinterest.secor.io.KeyValue;
import net.minidev.json.JSONObject;
import net.minidev.json.JSONValue;
// Converts delivery JSON to Beh TSV
public class AdgearDeliveryJsonReader implements AdgearReader {
private final String timestampFieldname;
public AdgearDeliveryJsonReader(SecorConfig secorConfig) {
timestampFieldname = secorConfig.getMessageTimestampName();
}
public String convert(KeyValue kv) {
JSONObject jsonObject = null;
Object value = JSONValue.parse(kv.getValue());
if (value instanceof JSONObject) {
jsonObject = (JSONObject) value;
} else {
return null;
}
Double timestamp = (Double) jsonObject.get(timestampFieldname);
String cookieId = (String) jsonObject.get("uid");
Integer buyerId = (Integer) jsonObject.get("buyer_id");
Integer segmentId = (Integer) jsonObject.get("segment_id");
Boolean segmentIsNew = (Boolean) jsonObject.get("segment_new");
if (timestamp == null || buyerId == null || cookieId == null || segmentId == null
|| segmentIsNew == null || !segmentIsNew) {
return null;
}
return String.format("%s\t%d\t%d:seg:%d\n",
cookieId, Math.round(timestamp), buyerId, segmentId);
}
}
| package com.pinterest.secor.io.impl;
import com.pinterest.secor.common.SecorConfig;
import com.pinterest.secor.io.AdgearReader;
import com.pinterest.secor.io.KeyValue;
import net.minidev.json.JSONObject;
import net.minidev.json.JSONValue;
// Converts delivery JSON to Beh TSV
public class AdgearDeliveryJsonReader implements AdgearReader {
private final String timestampFieldname;
public AdgearDeliveryJsonReader(SecorConfig secorConfig) {
timestampFieldname = secorConfig.getMessageTimestampName();
}
public String convert(KeyValue kv) {
JSONObject jsonObject = null;
Object value = JSONValue.parse(kv.getValue());
if (value instanceof JSONObject) {
jsonObject = (JSONObject) value;
} else {
return null;
}
Double timestamp = (Double) jsonObject.get(timestampFieldname);
String cookieId = (String) jsonObject.get("uid");
Integer segmentId = (Integer) jsonObject.get("segment_id");
Boolean segmentIsNew = (Boolean) jsonObject.get("segment_new");
if (timestamp == null || cookieId == null || segmentId == null
|| segmentIsNew == null || !segmentIsNew) {
return null;
}
return String.format("%s\t%d\tseg:%d\n",
cookieId, Math.round(timestamp), segmentId);
}
}
|
Handle SystemExit errors and add exit_code | # -*- coding: utf-8 -*-
import pytest
from cookiecutter.main import cookiecutter
class Cookies(object):
"""Class to provide convenient access to the cookiecutter API."""
exception = None
exit_code = 0
project = None
def __init__(self, template, output_dir):
self._template = template
self._output_dir = output_dir
def bake(self, extra_context=None):
try:
project_dir = cookiecutter(
self._template,
no_input=True,
extra_context=extra_context,
output_dir=self._output_dir
)
except SystemExit as e:
if e.code != 0:
self.exception = e
self.exit_code = e.code
except Exception as e:
self.exception = e
self.exit_code = -1
else:
self.project = project_dir
@pytest.fixture
def cookies(request, tmpdir):
output_dir = request.config.option.output_dir
if not output_dir:
output_dir = str(tmpdir.mkdir('cookies_output'))
_cookies = Cookies('.', output_dir)
return _cookies
def pytest_addoption(parser):
group = parser.getgroup('cookies')
group.addoption(
'--output-dir',
action='store',
dest='output_dir',
help='Set the output directory for Cookiecutter'
)
parser.addini('HELLO', 'Dummy pytest.ini setting')
| # -*- coding: utf-8 -*-
import pytest
from cookiecutter.main import cookiecutter
class Cookies(object):
"""Class to provide convenient access to the cookiecutter API."""
error = None
project = None
def __init__(self, template, output_dir):
self._template = template
self._output_dir = output_dir
def bake(self, extra_context=None):
try:
project_dir = cookiecutter(
self._template,
no_input=True,
extra_context=extra_context,
output_dir=self._output_dir
)
except Exception as e:
self.error = e
else:
self.project = project_dir
@pytest.fixture
def cookies(request, tmpdir):
output_dir = request.config.option.output_dir
if not output_dir:
output_dir = str(tmpdir.mkdir('cookies_output'))
_cookies = Cookies('.', output_dir)
return _cookies
def pytest_addoption(parser):
group = parser.getgroup('cookies')
group.addoption(
'--output-dir',
action='store',
dest='output_dir',
help='Set the output directory for Cookiecutter'
)
parser.addini('HELLO', 'Dummy pytest.ini setting')
|
Add name function in query | const express = require('express')
const router = express.Router()
const models = require('../models')
const response = require('./response')
router.post('/', function (req, res) {
const team = req.body
response.create(res, models.Team.create(
team, {
include: [{
model: models.Player,
as: 'players'
}]
}))
})
router.delete('/:id', function (req, res) {
response.delete(res,
models.sequelize.transaction(function (transaction) {
return models.Player.destroy(
{
where: {
teamId: req.params.id
}
},
{transaction: transaction})
.then(function () {
return models.Team.destroy(
{
where: {
id: req.params.id
}
},
{transaction: transaction})
})
})
)
})
router.get('/:id', function (req, res) {
response.get(res, models.Team.findById(
req.params.id,
{
attributes: ['id', 'name', 'area', 'establishedAt'],
include: [{
model: models.Player,
as: 'players',
attributes: ['id', 'age', [models.sequelize.fn('CONCAT', models.sequelize.col('firstName'), ' ', models.sequelize.col('lastName')), 'name']]
}]
}
))
})
router.put('/:id', function (req, res) {
const team = req.body
response.update(res, models.Team.update(team, {
where: {
id: req.params.id
}
}))
})
module.exports = router
| const express = require('express')
const router = express.Router()
const models = require('../models')
const response = require('./response')
router.post('/', function (req, res) {
const team = req.body
response.create(res, models.Team.create(
team, {
include: [{
model: models.Player,
as: 'players'
}]
}))
})
router.delete('/:id', function (req, res) {
response.delete(res,
models.sequelize.transaction(function (transaction) {
return models.Player.destroy(
{
where: {
teamId: req.params.id
}
},
{transaction: transaction})
.then(function () {
return models.Team.destroy(
{
where: {
id: req.params.id
}
},
{transaction: transaction})
})
})
)
})
router.get('/:id', function (req, res) {
response.get(res, models.Team.findById(
req.params.id, {
include: [{
model: models.Player,
as: 'players'
}]
}
))
})
router.put('/:id', function (req, res) {
const team = req.body
response.update(res, models.Team.update(team, {
where: {
id: req.params.id
}
}))
})
module.exports = router
|
Use stricter regex to validate date in DDMMYY | package seedu.utask.model.task;
import seedu.address.commons.exceptions.IllegalValueException;
/**
* Represents a Person's phone number in the address book.
* Guarantees: immutable; is valid as declared in {@link #isValidDeadline(String)}
*/
public class Deadline {
public static final String MESSAGE_DEADLINE_CONSTRAINTS = "Deadline for tasks should in format DDMMYY";
public static final String DEADLINE_VALIDATION_REGEX = "^(0[1-9]|[1-2][0-9]|"
+ "31(?!(?:0[2469]|11))|30(?!02))(0[1-9]|1[0-2])([1]\\d{1})";
public final String value;
/**
* Validates given deadline.
*
* @throws IllegalValueException if given phone string is invalid.
*/
public Deadline(String deadline) throws IllegalValueException {
assert deadline != null;
String trimmedDeadline = deadline.trim();
if (!isValidDeadline(trimmedDeadline)) {
throw new IllegalValueException(MESSAGE_DEADLINE_CONSTRAINTS);
}
this.value = trimmedDeadline;
}
/**
* Returns true if a given string is a valid task deadline.
*/
public static boolean isValidDeadline(String test) {
return test.matches(DEADLINE_VALIDATION_REGEX);
}
@Override
public String toString() {
return value;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Deadline // instanceof handles nulls
&& this.value.equals(((Deadline) other).value)); // state check
}
@Override
public int hashCode() {
return value.hashCode();
}
}
| package seedu.utask.model.task;
import seedu.address.commons.exceptions.IllegalValueException;
/**
* Represents a Person's phone number in the address book.
* Guarantees: immutable; is valid as declared in {@link #isValidDeadline(String)}
*/
public class Deadline {
public static final String MESSAGE_DEADLINE_CONSTRAINTS = "Deadline for tasks should in format DDMMYY";
public static final String DEADLINE_VALIDATION_REGEX = "\\d+";
public final String value;
/**
* Validates given deadline.
*
* @throws IllegalValueException if given phone string is invalid.
*/
public Deadline(String deadline) throws IllegalValueException {
assert deadline != null;
String trimmedDeadline = deadline.trim();
if (!isValidDeadline(trimmedDeadline)) {
throw new IllegalValueException(MESSAGE_DEADLINE_CONSTRAINTS);
}
this.value = trimmedDeadline;
}
/**
* Returns true if a given string is a valid task deadline.
*/
public static boolean isValidDeadline(String test) {
return test.matches(DEADLINE_VALIDATION_REGEX);
}
@Override
public String toString() {
return value;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Deadline // instanceof handles nulls
&& this.value.equals(((Deadline) other).value)); // state check
}
@Override
public int hashCode() {
return value.hashCode();
}
}
|
Add logging for docker debugging | let config = {
"url": process.env.CRN_SERVER_URL,
"port": 8111,
"location": process.env.CRN_SERVER_LOCATION,
"headers": {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS, PUT, PATCH, DELETE",
"Access-Control-Allow-Headers": "content-type, Authorization"
},
"scitran": {
"url": "http://localhost:8110/api/",
"secret": process.env.SCITRAN_CORE_DRONE_SECRET,
"fileStore": process.env.CRN_SERVER_CORE_FILE_STORE
},
"agave": {
"url": process.env.CRN_SERVER_AGAVE_URL,
"username": process.env.CRN_SERVER_AGAVE_USERNAME,
"password": process.env.CRN_SERVER_AGAVE_PASSWORD,
"clientName": process.env.CRN_SERVER_AGAVE_CLIENT_NAME,
"clientDescription": process.env.CRN_SERVER_AGAVE_CLIENT_DESCRIPTION,
"consumerKey": process.env.CRN_SERVER_AGAVE_CONSUMER_KEY,
"consumerSecret": process.env.CRN_SERVER_AGAVE_CONSUMER_SECRET,
"storage": process.env.CRN_SERVER_AGAVE_STORAGE
},
"mongo": {
"url": "mongodb://localhost:27017/crn"
}
};
console.log(config);
export default config; | export default {
"url": process.env.CRN_SERVER_URL,
"port": 8111,
"location": process.env.CRN_SERVER_LOCATION,
"headers": {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS, PUT, PATCH, DELETE",
"Access-Control-Allow-Headers": "content-type, Authorization"
},
"scitran": {
"url": "http://localhost:8110/api/",
"secret": process.env.SCITRAN_CORE_DRONE_SECRET,
"fileStore": process.env.CRN_SERVER_CORE_FILE_STORE
},
"agave": {
"url": process.env.CRN_SERVER_AGAVE_URL,
"username": process.env.CRN_SERVER_AGAVE_USERNAME,
"password": process.env.CRN_SERVER_AGAVE_PASSWORD,
"clientName": process.env.CRN_SERVER_AGAVE_CLIENT_NAME,
"clientDescription": process.env.CRN_SERVER_AGAVE_CLIENT_DESCRIPTION,
"consumerKey": process.env.CRN_SERVER_AGAVE_CONSUMER_KEY,
"consumerSecret": process.env.CRN_SERVER_AGAVE_CONSUMER_SECRET,
"storage": process.env.CRN_SERVER_AGAVE_STORAGE
},
"mongo": {
"url": "mongodb://localhost:27017/crn"
}
}; |
Make sure the returned results will contained LinkedIn count | /*
* Ping test suite
*/
var
vows = require('vows'),
assert = require('assert');
var
quero = {},
urls = [
'http://google.com',
'http://facebook.com',
'http://odesk.com',
'http://elance.com',
'http://parse.com',
'http://github.com',
'http://nodejs.org',
'http://npmjs.org'
];
function checkQueryResults (result) {
return (result.hasOwnProperty('linkedin') ||
result.hasOwnProperty('stumbleupon') ||
result.hasOwnProperty('facebook') ||
result.hasOwnProperty('twitter') ||
result.hasOwnProperty('pinterest'));
}
vows.describe('Should handle URLs argument properly')
.addBatch({
'Load module': {
topic: function () {
quero = require('./../');
return quero;
},
'should be loaded': function (topic) {
assert.isObject(topic);
assert.isNotNull(topic);
},
'should have a ping function': function (topic) {
assert.isFunction(topic.ping);
},
'Handle one URL': {
topic: function (quero) {
quero.ping([urls[0]], this.callback);
},
'should return a result if succeed': function (err, result) {
console.log('result', result);
assert.isNull(err);
assert.isObject(result);
assert.isTrue(checkQueryResults(result));
}
}
}
})
.export(module); | /*
* Ping test suite
*/
var
vows = require('vows'),
assert = require('assert');
var
quero = {},
urls = [
'http://google.com',
'http://facebook.com',
'http://odesk.com',
'http://elance.com',
'http://parse.com',
'http://github.com',
'http://nodejs.org',
'http://npmjs.org'
];
function checkQueryResults (result) {
return (result.hasOwnProperty('pinterest') ||
result.hasOwnProperty('stumbleupon') ||
result.hasOwnProperty('facebook') ||
result.hasOwnProperty('twitter') ||
result.hasOwnProperty('pinterest'));
}
vows.describe('Should handle URLs argument properly')
.addBatch({
'Load module': {
topic: function () {
quero = require('./../');
return quero;
},
'should be loaded': function (topic) {
assert.isObject(topic);
assert.isNotNull(topic);
},
'should have a ping function': function (topic) {
assert.isFunction(topic.ping);
},
'Handle one URL': {
topic: function (quero) {
quero.ping([urls[0]], this.callback);
},
'should return a result if succeed': function (err, result) {
console.log('result', result);
assert.isNull(err);
assert.isObject(result);
assert.isTrue(checkQueryResults(result));
}
}
}
})
.export(module); |
Remove unneeded initialization of gMap | /**
* @fileoverview Define the map component of the map module.
*/
'use strict';
angular.module('map').component('mapComponent', {
templateUrl: 'map/map.template.html',
controller: function($scope) {
//Define some hard-coded markers to be shown on the map
$scope.markers = [{
city: 'India',
lat: 23.200000,
long: 79.225487
}, {
city: 'Gorakhpur',
lat: 26.7588,
long: 83.3697
}];
let googleMapOption = {
zoom: 4,
center: new google.maps.LatLng(25, 80)
};
$scope.gMap = new google.maps.Map(document.getElementById('map-container'), googleMapOption);
// Add a marker to the map
let createMarker = function(marker) {
let markersInfo = new google.maps.Marker({
map: $scope.gMap,
position: new google.maps.LatLng(marker.lat, marker.long),
title: marker.city
});
};
//Iterate over the list of markers and add all of them to the map
for (let i = 0; i < $scope.markers.length; i++) {
createMarker($scope.markers[i]);
}
}
}); | /**
* @fileoverview Define the map component of the map module.
*/
'use strict';
angular.module('map').component('mapComponent', {
templateUrl: 'map/map.template.html',
controller: function($scope) {
//Define some hard-coded markers to be shown on the map
$scope.markers = [{
city: 'India',
lat: 23.200000,
long: 79.225487
}, {
city: 'Gorakhpur',
lat: 26.7588,
long: 83.3697
}];
$scope.gMap = null;
let googleMapOption = {
zoom: 4,
center: new google.maps.LatLng(25, 80)
};
$scope.gMap = new google.maps.Map(document.getElementById('map-container'), googleMapOption);
// Add a marker to the map
let createMarker = function(marker) {
let markersInfo = new google.maps.Marker({
map: $scope.gMap,
position: new google.maps.LatLng(marker.lat, marker.long),
title: marker.city
});
};
//Iterate over the list of markers and add all of them to the map
for (let i = 0; i < $scope.markers.length; i++) {
createMarker($scope.markers[i]);
}
}
}); |
Fix basic methods not assgin into vm | import pluck from './pluck';
import {
ref,
refs,
noop,
mixin,
insertCss,
emptyTemplate,
computedAll,
pureComputedAll
} from '../util/';
const modulePolyfill = {
constructor: noop,
defaults: {},
template: emptyTemplate
};
// Transform transiton component module to native component module
//
// @param {Object} module Transiton component module
// @return {Object} Native component module
function transform(module) {
const {
constructor,
defaults,
mixins,
methods,
computed,
pureComputed,
style,
template
} = Object.assign({}, modulePolyfill, module);
insertCss(module.style);
Object.assign(constructor.prototype, {
ref,
refs,
ready: noop
}, methods);
return {
viewModel: {
createViewModel(params, componentInfo) {
const opts = Object.assign(
defaults,
ko.toJS(params),
pluck(componentInfo.element)
);
const vm = new constructor(opts, componentInfo);
mixins && mixin(vm, opts, mixins)
computed && computedAll(vm, computed);
pureComputed && pureComputedAll(vm, pureComputed);
vm.$opts = opts;
vm.$defaults = defaults;
vm.$info = vm.componentInfo = componentInfo;
delete vm.$opts['$raw'];
delete vm.$defaults['$raw'];
return vm;
}
},
synchronous: true,
template
};
}
export default transform;
| import pluck from './pluck';
import {
ref,
refs,
noop,
mixin,
insertCss,
emptyTemplate,
computedAll,
pureComputedAll
} from '../util/';
const modulePolyfill = {
constructor: noop,
defaults: {},
template: emptyTemplate
};
// Transform transiton component module to native component module
//
// @param {Object} module Transiton component module
// @return {Object} Native component module
function transform(module) {
const {
constructor,
defaults,
mixins,
methods,
computed,
pureComputed,
style,
template
} = Object.assign({}, modulePolyfill, module);
insertCss(module.style);
methods && Object.assign(constructor.prototype, {
ref,
refs,
ready: noop
}, methods);
return {
viewModel: {
createViewModel(params, componentInfo) {
const opts = Object.assign(
defaults,
ko.toJS(params),
pluck(componentInfo.element)
);
const vm = new constructor(opts, componentInfo);
mixins && mixin(vm, opts, mixins)
computed && computedAll(vm, computed);
pureComputed && pureComputedAll(vm, pureComputed);
vm.$opts = opts;
vm.$defaults = defaults;
vm.$info = vm.componentInfo = componentInfo;
delete vm.$opts['$raw'];
delete vm.$defaults['$raw'];
return vm;
}
},
synchronous: true,
template
};
}
export default transform;
|
Remove @package & restart travis | <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace ZendTest\Form\TestAsset;
use DomainException;
use Zend\Stdlib\ArraySerializableInterface;
/**
* @category Zend
* @package Zend_Form
* @subpackage UnitTest
*/
class Model implements ArraySerializableInterface
{
protected $foo;
protected $bar;
protected $foobar;
public function __set($name, $value)
{
throw new DomainException('Overloading to set values is not allowed');
}
public function __get($name)
{
if (property_exists($this, $name)) {
return $this->$name;
}
throw new DomainException('Unknown attribute');
}
public function exchangeArray(array $array)
{
foreach ($array as $key => $value) {
if (!property_exists($this, $key)) {
continue;
}
$this->$key = $value;
}
}
public function getArrayCopy()
{
return array(
'foo' => $this->foo,
'bar' => $this->bar,
'foobar' => $this->foobar,
);
}
}
| <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @package Zend_Form
*/
namespace ZendTest\Form\TestAsset;
use DomainException;
use Zend\Stdlib\ArraySerializableInterface;
/**
* @category Zend
* @package Zend_Form
* @subpackage UnitTest
*/
class Model implements ArraySerializableInterface
{
protected $foo;
protected $bar;
protected $foobar;
public function __set($name, $value)
{
throw new DomainException('Overloading to set values is not allowed');
}
public function __get($name)
{
if (property_exists($this, $name)) {
return $this->$name;
}
throw new DomainException('Unknown attribute');
}
public function exchangeArray(array $array)
{
foreach ($array as $key => $value) {
if (!property_exists($this, $key)) {
continue;
}
$this->$key = $value;
}
}
public function getArrayCopy()
{
return array(
'foo' => $this->foo,
'bar' => $this->bar,
'foobar' => $this->foobar,
);
}
}
|
Use import instead of require | /** @babel */
import {Disposable, CompositeDisposable} from 'atom'
const ViewURI = 'atom://deprecation-cop'
let DeprecationCopView
class DeprecationCopPackage {
activate () {
this.disposables = new CompositeDisposable()
this.disposables.add(atom.workspace.addOpener((uri) => {
if (uri === ViewURI) {
return this.deserializeDeprecationCopView({uri})
}
}))
this.disposables.add(atom.commands.add('atom-workspace', 'deprecation-cop:view', () => {
atom.workspace.open(ViewURI)
}))
}
deactivate () {
this.disposables.dispose()
const pane = atom.workspace.paneForURI(ViewURI)
if (pane) {
pane.destroyItem(pane.itemForURI(ViewURI))
}
}
deserializeDeprecationCopView (state) {
if (!DeprecationCopView) {
DeprecationCopView = require('./deprecation-cop-view')
}
return new DeprecationCopView(state)
}
consumeStatusBar (statusBar) {
const DeprecationCopStatusBarView = require('./deprecation-cop-status-bar-view')
const statusBarView = new DeprecationCopStatusBarView()
const statusBarTile = statusBar.addRightTile({item: statusBarView, priority: 150})
this.disposables.add(new Disposable(() => { statusBarView.destroy() }))
this.disposables.add(new Disposable(() => { statusBarTile.destroy() }))
}
}
const instance = new DeprecationCopPackage()
export default instance
| /** @babel */
const {Disposable, CompositeDisposable} = require('atom')
const ViewURI = 'atom://deprecation-cop'
let DeprecationCopView
class DeprecationCopPackage {
activate () {
this.disposables = new CompositeDisposable()
this.disposables.add(atom.workspace.addOpener((uri) => {
if (uri === ViewURI) {
return this.deserializeDeprecationCopView({uri})
}
}))
this.disposables.add(atom.commands.add('atom-workspace', 'deprecation-cop:view', () => {
atom.workspace.open(ViewURI)
}))
}
deactivate () {
this.disposables.dispose()
const pane = atom.workspace.paneForURI(ViewURI)
if (pane) {
pane.destroyItem(pane.itemForURI(ViewURI))
}
}
deserializeDeprecationCopView (state) {
if (!DeprecationCopView) {
DeprecationCopView = require('./deprecation-cop-view')
}
return new DeprecationCopView(state)
}
consumeStatusBar (statusBar) {
const DeprecationCopStatusBarView = require('./deprecation-cop-status-bar-view')
const statusBarView = new DeprecationCopStatusBarView()
const statusBarTile = statusBar.addRightTile({item: statusBarView, priority: 150})
this.disposables.add(new Disposable(() => { statusBarView.destroy() }))
this.disposables.add(new Disposable(() => { statusBarTile.destroy() }))
}
}
const instance = new DeprecationCopPackage()
export default instance
|
Copy application specific cordova config.xml on build. | #!/usr/bin/env node
var cordova = require(process.env.framework + '/bin/cli-cordova');
var global = require(process.env.framework + '/bin/cli-global');
var shell = require('shelljs');
module.exports = {
/**
* @method build
*/
build: function() {
if (this.isInstalled()) {
cordova.copy();
cordova.exec(['build', 'android']);
} else {
console.log('Cordova platform Android is not installed.');
process.exit(0);
}
},
/**
* @method copy
*/
copy: function() {
shell.cp('-rf', global.project + '/app/cordova/config.xml', global.project + '/cordova');
},
/**
* @method install
*/
install: function() {
cordova.exec(['platform', 'remove', 'android']);
cordova.exec(['platform', 'add', 'android']);
cordova.exec(['plugin', 'remove', 'cordova-plugin-crosswalk-webview']);
cordova.exec(['plugin', 'add', 'cordova-plugin-crosswalk-webview']);
this.build();
},
/**
* @method isInstalled
* @returns {Boolean}
*/
isInstalled: function() {
return shell.test('-d', global.project + '/cordova/platforms/android/cordova');
},
/**
* @method run
*/
run: function() {
if (this.isInstalled()) {
this.copy();
cordova.copy();
cordova.exec(['run', 'android']);
} else {
console.log('Cordova platform Android is not installed.');
process.exit(0);
}
}
};
| #!/usr/bin/env node
var cordova = require(process.env.framework + '/bin/cli-cordova');
var global = require(process.env.framework + '/bin/cli-global');
var shell = require('shelljs');
module.exports = {
/**
* @method build
*/
build: function() {
if (this.isInstalled()) {
cordova.copy();
cordova.exec(['build', 'android']);
} else {
console.log('Cordova platform Android is not installed.');
process.exit(0);
}
},
/**
* @method install
*/
install: function() {
cordova.exec(['platform', 'remove', 'android']);
cordova.exec(['platform', 'add', 'android']);
cordova.exec(['plugin', 'remove', 'cordova-plugin-crosswalk-webview']);
cordova.exec(['plugin', 'add', 'cordova-plugin-crosswalk-webview']);
this.build();
},
/**
* @method isInstalled
* @returns {Boolean}
*/
isInstalled: function() {
return shell.test('-d', global.project + '/cordova/platforms/android/cordova');
},
/**
* @method run
*/
run: function() {
if (this.isInstalled()) {
cordova.copy();
cordova.exec(['run', 'android']);
} else {
console.log('Cordova platform Android is not installed.');
process.exit(0);
}
}
};
|
Use seed as the js interpreter. | import subprocess
from distutils.core import setup
from distutils.command.sdist import sdist
class SignedSDistCommand(sdist):
"""Sign the source archive with a detached signature."""
description = "Sign the source archive after it is generated."
def run(self):
sdist.run(self)
gpg_args = [
'gpg', '--armor', '--sign', '--detach-sig', self.archive_files[0]]
gpg = subprocess.Popen(
gpg_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
gpg.communicate()
setup(
name="pocketlint",
description="Pocket-lint a composite linter and style checker.",
version="0.5.19",
maintainer="Curtis C. Hovey",
maintainer_email="[email protected]",
url="https://launchpad.net/pocket-lint",
packages=[
'pocketlint', 'pocketlint/contrib', 'pocketlint/contrib/pyflakes'],
package_dir={
'pocketlint': 'pocketlint',
'pocketlint/contrib': 'pocketlint/contrib'},
package_data={
'pocketlint': ['jsreporter.js'],
'pocketlint/contrib': ['fulljslint.js'],
},
scripts=['scripts/pocketlint'],
cmdclass={
'signed_sdist': SignedSDistCommand,
},
)
| import subprocess
from distutils.core import setup
from distutils.command.sdist import sdist
class SignedSDistCommand(sdist):
"""Sign the source archive with a detached signature."""
description = "Sign the source archive after it is generated."
def run(self):
sdist.run(self)
gpg_args = [
'gpg', '--armor', '--sign', '--detach-sig', self.archive_files[0]]
gpg = subprocess.Popen(
gpg_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
gpg.communicate()
setup(
name="pocketlint",
description="Pocket-lint a composite linter and style checker.",
version="0.5.18",
maintainer="Curtis C. Hovey",
maintainer_email="[email protected]",
url="https://launchpad.net/pocket-lint",
packages=[
'pocketlint', 'pocketlint/contrib', 'pocketlint/contrib/pyflakes'],
package_dir={
'pocketlint': 'pocketlint',
'pocketlint/contrib': 'pocketlint/contrib'},
package_data={
'pocketlint': ['jsreporter.js'],
'pocketlint/contrib': ['fulljslint.js'],
},
scripts=['scripts/pocketlint'],
cmdclass={
'signed_sdist': SignedSDistCommand,
},
)
|
Put URL config option on the disk to make it obvious how to customize. | <?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application. Just store away!
|
*/
'default' => 'local',
/*
|--------------------------------------------------------------------------
| Default Cloud Filesystem Disk
|--------------------------------------------------------------------------
|
| Many applications store files both locally and in the cloud. For this
| reason, you may specify a default "cloud" driver here. This driver
| will be bound as the Cloud disk implementation in the container.
|
*/
'cloud' => 's3',
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Here you may configure as many filesystem "disks" as you wish, and you
| may even configure multiple disks of the same driver. Defaults have
| been setup for each driver as an example of the required options.
|
| Supported Drivers: "local", "ftp", "s3", "rackspace"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => url('storage'),
'visibility' => 'public',
],
's3' => [
'driver' => 's3',
'key' => 'your-key',
'secret' => 'your-secret',
'region' => 'your-region',
'bucket' => 'your-bucket',
],
],
];
| <?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application. Just store away!
|
*/
'default' => 'local',
/*
|--------------------------------------------------------------------------
| Default Cloud Filesystem Disk
|--------------------------------------------------------------------------
|
| Many applications store files both locally and in the cloud. For this
| reason, you may specify a default "cloud" driver here. This driver
| will be bound as the Cloud disk implementation in the container.
|
*/
'cloud' => 's3',
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Here you may configure as many filesystem "disks" as you wish, and you
| may even configure multiple disks of the same driver. Defaults have
| been setup for each driver as an example of the required options.
|
| Supported Drivers: "local", "ftp", "s3", "rackspace"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'visibility' => 'public',
],
's3' => [
'driver' => 's3',
'key' => 'your-key',
'secret' => 'your-secret',
'region' => 'your-region',
'bucket' => 'your-bucket',
],
],
];
|
Remove unused parameter in no-op closure | <?php
namespace League\Tactician;
use League\Tactician\Exception\InvalidCommandException;
use League\Tactician\Exception\InvalidMiddlewareException;
/**
* Receives a command and sends it through a chain of middleware for processing.
*
* @final
*/
class CommandBus
{
/**
* @var callable
*/
private $middlewareChain;
/**
* @param Middleware[] $middleware
*/
public function __construct(array $middleware)
{
$this->middlewareChain = $this->createExecutionChain($middleware);
}
/**
* Executes the given command and optionally returns a value
*
* @param object $command
*
* @return mixed
*/
public function handle($command)
{
if (!is_object($command)) {
throw InvalidCommandException::forUnknownValue($command);
}
$middlewareChain = $this->middlewareChain;
return $middlewareChain($command);
}
/**
* @param Middleware[] $middlewareList
*
* @return callable
*/
private function createExecutionChain($middlewareList)
{
$lastCallable = function () {
// the final callable is a no-op
};
while ($middleware = array_pop($middlewareList)) {
if (! $middleware instanceof Middleware) {
throw InvalidMiddlewareException::forMiddleware($middleware);
}
$lastCallable = function ($command) use ($middleware, $lastCallable) {
return $middleware->execute($command, $lastCallable);
};
}
return $lastCallable;
}
}
| <?php
namespace League\Tactician;
use League\Tactician\Exception\InvalidCommandException;
use League\Tactician\Exception\InvalidMiddlewareException;
/**
* Receives a command and sends it through a chain of middleware for processing.
*
* @final
*/
class CommandBus
{
/**
* @var callable
*/
private $middlewareChain;
/**
* @param Middleware[] $middleware
*/
public function __construct(array $middleware)
{
$this->middlewareChain = $this->createExecutionChain($middleware);
}
/**
* Executes the given command and optionally returns a value
*
* @param object $command
*
* @return mixed
*/
public function handle($command)
{
if (!is_object($command)) {
throw InvalidCommandException::forUnknownValue($command);
}
$middlewareChain = $this->middlewareChain;
return $middlewareChain($command);
}
/**
* @param Middleware[] $middlewareList
*
* @return callable
*/
private function createExecutionChain($middlewareList)
{
$lastCallable = function ($command) {
// the final callable is a no-op
};
while ($middleware = array_pop($middlewareList)) {
if (! $middleware instanceof Middleware) {
throw InvalidMiddlewareException::forMiddleware($middleware);
}
$lastCallable = function ($command) use ($middleware, $lastCallable) {
return $middleware->execute($command, $lastCallable);
};
}
return $lastCallable;
}
}
|
Add limit (relevant for gods) | // Module Route(s)
DevAAC.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/highscores', {
// When a module contains multiple routes, use 'moduleName/viewName' in PageUrl function.
templateUrl: PageUrl('highscores'),
controller: 'HighscoresController',
resolve: {
vocations: function(Server) {
return Server.vocations().$promise;
}
}
});
}]);
// Module Controller(s)
DevAAC.controller('HighscoresController', ['$scope', 'Player', 'Server', 'vocations',
function($scope, Player, Server, vocations) {
$scope.order = 'level';
$scope.$watch('order', function(val) {
$scope.loaded = false;
$scope.players = Player.query({sort: '-'+val+',-level', limit: 100}, function(val) {
$scope.loaded = true;
});
});
$scope.players = Player.query(function(val){
$scope.loaded = true;
return {sort: '-'+val+',-level', limit: 100};
});
$scope.vocation = function(id) {
return _.findWhere(vocations, {id: id});
};
}
]);
| // Module Route(s)
DevAAC.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/highscores', {
// When a module contains multiple routes, use 'moduleName/viewName' in PageUrl function.
templateUrl: PageUrl('highscores'),
controller: 'HighscoresController',
resolve: {
vocations: function(Server) {
return Server.vocations().$promise;
}
}
});
}]);
// Module Controller(s)
DevAAC.controller('HighscoresController', ['$scope', 'Player', 'Server', 'vocations',
function($scope, Player, Server, vocations) {
$scope.order = 'level';
$scope.$watch('order', function(val) {
$scope.loaded = false;
$scope.players = Player.query({sort: '-'+val+',-level'}, function(val) {
$scope.loaded = true;
});
});
$scope.players = Player.query(function(val){
$scope.loaded = true;
return {sort: '-'+val+',-level'};
});
$scope.vocation = function(id) {
return _.findWhere(vocations, {id: id});
};
}
]);
|
Fix bug in chain creation | # -*- coding: utf-8 -*-
from pollirio.reactors import expose
from pollirio import conf, choose_dest
import random
def create_chains(lines):
markov_chain = {}
has_prev = False
for line in lines:
for cur_word in line.split():
if cur_word != '':
cur_word = cur_word.lower()
if has_prev == False:
prev_word = cur_word
has_prev = True
else:
markov_chain.setdefault(prev_word, []).append(cur_word)
prev_word = cur_word
return markov_chain
def make_sentence(markov_chain, words=None):
while True:
if not words:
word = random.choice(markov_chain.keys())
else:
word = random.choice(words)
if word[-1] not in ('.','?'):
break
generated_sentence = word.capitalize()
while word[-1] not in ('.','?'):
newword = random.choice(markov_chain[word])
generated_sentence += ' '+newword
word = newword #TODO fix possible crash if this is not a key (last word parsed)
return generated_sentence
@expose('^%s' % conf.nickname)
def talk(bot, ievent):
source = 'data/pg28867.txt'
mc = create_chains(open(source))
bot.msg(choose_dest(ievent), '%s: %s' % (ievent.nick, make_sentence(mc)))
| # -*- coding: utf-8 -*-
from pollirio.reactors import expose
from pollirio import conf, choose_dest
import random
def create_chains(lines):
markov_chain = {}
hasPrev = False
for line in lines:
for curword in line.split():
if curword != '':
curword = curword.lower()
if hasPrev == False:
prevword = currWord
hasPrev = True
else:
markov_chain.setdefault(prevWord, []).append(currWord)
prevWord = currWord
return markov_chain
def make_sentence(markov_chain, words=None):
while True:
if not words:
word = random.choice(markov_chain.keys())
else:
word = random.choice(words)
if word[-1] not in ('.','?'):
break
generated_sentence = word.capitalize()
while word[-1] not in ('.','?'):
newword = random.choice(markov_chain[word])
generated_sentence += ' '+newword
word = newword #TODO fix possible crash if this is not a key (last word parsed)
return generated_sentence
@expose('^%s' % conf.nickname)
def talk(bot, ievent):
source = 'data/pg28867.txt'
mc = create_chains(open(source))
bot.msg(choose_dest(ievent), '%s: %s' % (ievent.nick, make_sentence(mc)))
|
Make test stricter to be safe. | import copy
import pytest
from ..core import Document, NotMutable
def test_immutable():
d = Document({'a': 1})
with pytest.raises(NotMutable):
# Update existing key
d['a'] = 2
with pytest.raises(NotMutable):
# Add new key
d['b'] = 2
with pytest.raises(NotMutable):
d.setdefault('a', 2)
with pytest.raises(NotMutable):
d.setdefault('b', 2)
with pytest.raises(NotMutable):
del d['a']
with pytest.raises(NotMutable):
d.pop('a')
with pytest.raises(NotMutable):
d.popitem()
with pytest.raises(NotMutable):
d.clear()
with pytest.raises(NotMutable):
# Update existing key
d.update({'a': 2})
with pytest.raises(NotMutable):
# Add new key
d.update({'b': 2})
def test_deep_copy():
a = Document({'x': {'y': {'z': 1}}})
b = copy.deepcopy(a)
b['x']['y']['z'] = 2
# Verify original is not modified.
assert a['x']['y']['z'] == 1
def test_to_dict():
a = Document({'x': {'y': {'z': 1}}})
b = a.to_dict()
assert type(b) is dict # i.e. not Document
b['x']['y']['z'] = 2
# Verify original is not modified.
assert a['x']['y']['z'] == 1
| import copy
import pytest
from ..core import Document, NotMutable
def test_immutable():
d = Document({'a': 1})
with pytest.raises(NotMutable):
# Update existing key
d['a'] = 2
with pytest.raises(NotMutable):
# Add new key
d['b'] = 2
with pytest.raises(NotMutable):
d.setdefault('a', 2)
with pytest.raises(NotMutable):
d.setdefault('b', 2)
with pytest.raises(NotMutable):
del d['a']
with pytest.raises(NotMutable):
d.pop('a')
with pytest.raises(NotMutable):
d.popitem()
with pytest.raises(NotMutable):
d.clear()
with pytest.raises(NotMutable):
# Update existing key
d.update({'a': 2})
with pytest.raises(NotMutable):
# Add new key
d.update({'b': 2})
def test_deep_copy():
a = Document({'x': {'y': {'z': 1}}})
b = copy.deepcopy(a)
b['x']['y']['z'] = 2
# Verify original is not modified.
assert a['x']['y']['z'] == 1
def test_to_dict():
a = Document({'x': {'y': {'z': 1}}})
b = a.to_dict()
assert not isinstance(b, Document)
assert isinstance(b, dict)
b['x']['y']['z'] = 2
# Verify original is not modified.
assert a['x']['y']['z'] == 1
|
Fix bug in hasNext when no result for a key is returned | /**
* This class will instill 'normal' iterator behavior to a ColumnFamilyResult.
* Simply instantiate this class while passing your ColumnFamilyResult as a
* constructor argument.
*
* Ex.
*
* ColumnFamilyResultIterator myResultsInterator =
* new ColumnFamilyResultIterator(someColumnFamilyResult);
*
* You can then use myResultsInterator with for loops or iterate with a while loop
* just as with any standard java iterator.
*
*/
package me.prettyprint.cassandra.service.template;
import java.util.Iterator;
import me.prettyprint.cassandra.service.template.ColumnFamilyResult;
public class ColumnFamilyResultIterator implements Iterator<ColumnFamilyResult<?,?>> {
private ColumnFamilyResult<?, ?> res;
private boolean isStart = true;
public ColumnFamilyResultIterator(ColumnFamilyResult<?, ?> res) {
this.res = res;
}
public boolean hasNext()
{
boolean retval = false;
if (isStart)
{
if(res.hasResults() || res.hasNext())
{
retval = true;
}
}
else
{
retval = res.hasNext();
}
return retval;
}
public ColumnFamilyResult<?, ?> getRes()
{
return res;
}
public void setRes(ColumnFamilyResult<?, ?> res)
{
this.res = res;
}
public ColumnFamilyResult<?, ?> next()
{
if (isStart)
{
isStart = false;
return res;
}
else
{
return (ColumnFamilyResult<?, ?>) res.next();
}
}
public void remove()
{
res.remove();
}
}
| /**
* This class will instill 'normal' iterator behavior to a ColumnFamilyResult.
* Simply instantiate this class while passing your ColumnFamilyResult as a
* constructor argument.
*
* Ex.
*
* ColumnFamilyResultIterator myResultsInterator =
* new ColumnFamilyResultIterator(someColumnFamilyResult);
*
* You can then use myResultsInterator with for loops or iterate with a while loop
* just as with any standard java iterator.
*
*/
package me.prettyprint.cassandra.service.template;
import java.util.Iterator;
import me.prettyprint.cassandra.service.template.ColumnFamilyResult;
public class ColumnFamilyResultIterator implements Iterator<ColumnFamilyResult<?,?>> {
private ColumnFamilyResult<?, ?> res;
private boolean isStart = true;
public ColumnFamilyResultIterator(ColumnFamilyResult<?, ?> res) {
this.res = res;
}
public boolean hasNext()
{
boolean retval = false;
if (isStart)
{
retval = res.hasResults();
}
else
{
retval = res.hasNext();
}
return retval;
}
public ColumnFamilyResult<?, ?> getRes()
{
return res;
}
public void setRes(ColumnFamilyResult<?, ?> res)
{
this.res = res;
}
public ColumnFamilyResult<?, ?> next()
{
if (isStart)
{
isStart = false;
return res;
}
else
{
return (ColumnFamilyResult<?, ?>) res.next();
}
}
public void remove()
{
res.remove();
}
}
|
REmove python 3 (not ready yet) | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.md') as readme_file:
readme = readme_file.read()
with open('HISTORY.md') as history_file:
history = history_file.read().replace('.. :changelog:', '')
requirements = [
# TODO: put package requirements here
]
test_requirements = [
# TODO: put package test requirements here
]
setup(
name='xyvio',
version='0.1.4',
description="Basic Url Shortener",
long_description=readme + '\n\n' + history,
author="Marcos Hernández",
author_email='[email protected]',
url='https://github.com/marcoslhc/xyvio',
packages=[
'xyvio',
],
package_dir={'xyvio':
'xyvio'},
include_package_data=True,
install_requires=requirements,
license="ISCL",
zip_safe=False,
keywords='xyvio',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
test_suite='tests',
tests_require=test_requirements
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.md') as readme_file:
readme = readme_file.read()
with open('HISTORY.md') as history_file:
history = history_file.read().replace('.. :changelog:', '')
requirements = [
# TODO: put package requirements here
]
test_requirements = [
# TODO: put package test requirements here
]
setup(
name='xyvio',
version='0.1.4',
description="Basic Url Shortener",
long_description=readme + '\n\n' + history,
author="Marcos Hernández",
author_email='[email protected]',
url='https://github.com/marcoslhc/xyvio',
packages=[
'xyvio',
],
package_dir={'xyvio':
'xyvio'},
include_package_data=True,
install_requires=requirements,
license="ISCL",
zip_safe=False,
keywords='xyvio',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
test_suite='tests',
tests_require=test_requirements
)
|
Add logging for health check | from django.core.management.base import BaseCommand, CommandError
import time
from django_celery_beat.models import PeriodicTask
from django.utils import timezone
from datetime import timedelta
from atlas.prodtask.views import send_alarm_message
class Command(BaseCommand):
args = 'None'
help = 'Check celery beat health'
def handle(self, *args, **options):
if not args:
self.stdout.write(f'Start celery beat health check {timezone.now()}')
try:
try:
last_executed_task = PeriodicTask.objects.all().order_by('-last_run_at')[0]
except Exception as e:
send_alarm_message('Alarm: the celery beat health check problem',
f'Celery beat health check problem {e}')
raise e
if (timezone.now() - last_executed_task.last_run_at) > timedelta(hours=3):
send_alarm_message('Alarm: the celery beat is stuck',
f'Celery beat last updated {last_executed_task.last_run_at}')
except Exception as e:
raise CommandError('Some problem during alarm mail sending check: %s'%e)
| from django.core.management.base import BaseCommand, CommandError
import time
from django_celery_beat.models import PeriodicTask
from django.utils import timezone
from datetime import timedelta
from atlas.prodtask.views import send_alarm_message
class Command(BaseCommand):
args = 'None'
help = 'Check celery beat health'
def handle(self, *args, **options):
if not args:
try:
try:
last_executed_task = PeriodicTask.objects.all().order_by('-last_run_at')[0]
except Exception as e:
send_alarm_message('Alarm: the celery beat health check problem',
f'Celery beat health check problem {e}')
raise e
if (timezone.now() - last_executed_task.last_run_at) > timedelta(hours=3):
send_alarm_message('Alarm: the celery beat is stuck',
f'Celery beat last updated {last_executed_task.last_run_at}')
except Exception as e:
raise CommandError('Some problem during alarm mail sending check: %s'%e)
|
Allow username, password and scheme for solr | <?php
/*
* This file is part of the Integrated package.
*
* (c) e-Active B.V. <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Integrated\Bundle\SolrBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* Configuration class for SolrBundle
*
* @author Jeroen van Leeuwen <[email protected]>
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$builder = new TreeBuilder;
$builder->root('integrated_solr')
->children()
->arrayNode('endpoints')
->prototype('array')
->children()
->scalarNode('scheme')->defaultValue('http')->end()
->scalarNode('host')->defaultValue('localhost')->end()
->scalarNode('port')->defaultValue(8983)->end()
->scalarNode('username')->defaultValue(null)->end()
->scalarNode('password')->defaultValue(null)->end()
->scalarNode('path')->defaultValue('/solr')->end()
->scalarNode('core')->end()
->scalarNode('timeout')->defaultValue(5)->end()
->end()
->end()
->end()
->end();
return $builder;
}
}
| <?php
/*
* This file is part of the Integrated package.
*
* (c) e-Active B.V. <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Integrated\Bundle\SolrBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* Configuration class for SolrBundle
*
* @author Jeroen van Leeuwen <[email protected]>
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$builder = new TreeBuilder;
$builder->root('integrated_solr')
->children()
->arrayNode('endpoints')
->prototype('array')
->children()
->scalarNode('host')->defaultValue('localhost')->end()
->scalarNode('port')->defaultValue(8983)->end()
->scalarNode('path')->defaultValue('/solr')->end()
->scalarNode('core')->end()
->scalarNode('timeout')->defaultValue(5)->end()
->end()
->end()
->end()
->end();
return $builder;
}
}
|
_BaseEnumField: Make run_validators method a no-op
See the comment in this commit-- I can't see value in allowing custom
validators on EnumFields and the implementation in the superclass causes
warnings in RichEnum.__eq__.
Arguably those warnings aren't useful (warning against []/falsy compare).
In that case, we can revert this when they're silenced.
Alternatively, if we need the warnings and need this functionality, we'd have
re-implement the method in the superclass without said check, or live with
warnings every time a form containing an EnumField is validated, which sucks. | from abc import ABCMeta
from abc import abstractmethod
from django import forms
class _BaseEnumField(forms.TypedChoiceField):
__metaclass__ = ABCMeta
def __init__(self, enum, *args, **kwargs):
self.enum = enum
kwargs.setdefault('empty_value', None)
if 'choices' in kwargs:
raise ValueError('Cannot explicitly supply choices to enum fields.')
if 'coerce' in kwargs:
raise ValueError('Cannot explicitly supply coercion function to enum fields.')
kwargs['choices'] = self.get_choices()
kwargs['coerce'] = self.coerce_value
super(_BaseEnumField, self).__init__(*args, **kwargs)
@abstractmethod
def get_choices(self):
pass
@abstractmethod
def coerce_value(self, val):
pass
def run_validators(self, value):
# These have to be from a set, so it's hard for me to imagine a useful
# custom validator.
# The run_validators method in the superclass checks the value against
# None, [], {}, etc, which causes warnings in the RichEnum.__eq__
# method... arguably we shouldn't warn in those cases, but for now we
# do.
pass
class CanonicalEnumField(_BaseEnumField):
"""
Uses the RichEnum/OrderedRichEnum canonical_name as form field values
"""
def get_choices(self):
return self.enum.choices()
def coerce_value(self, name):
return self.enum.from_canonical(name)
class IndexEnumField(_BaseEnumField):
"""
Uses the OrderedRichEnum index as form field values
"""
def get_choices(self):
return self.enum.choices(value_field='index')
def coerce_value(self, index):
return self.enum.from_index(int(index))
| from abc import ABCMeta
from abc import abstractmethod
from django import forms
class _BaseEnumField(forms.TypedChoiceField):
__metaclass__ = ABCMeta
def __init__(self, enum, *args, **kwargs):
self.enum = enum
kwargs.setdefault('empty_value', None)
if 'choices' in kwargs:
raise ValueError('Cannot explicitly supply choices to enum fields.')
if 'coerce' in kwargs:
raise ValueError('Cannot explicitly supply coercion function to enum fields.')
kwargs['choices'] = self.get_choices()
kwargs['coerce'] = self.coerce_value
super(_BaseEnumField, self).__init__(*args, **kwargs)
@abstractmethod
def get_choices(self):
pass
@abstractmethod
def coerce_value(self, val):
pass
class CanonicalEnumField(_BaseEnumField):
"""
Uses the RichEnum/OrderedRichEnum canonical_name as form field values
"""
def get_choices(self):
return self.enum.choices()
def coerce_value(self, name):
return self.enum.from_canonical(name)
class IndexEnumField(_BaseEnumField):
"""
Uses the OrderedRichEnum index as form field values
"""
def get_choices(self):
return self.enum.choices(value_field='index')
def coerce_value(self, index):
return self.enum.from_index(int(index))
|
Fix the MySQL issue with not nullable timestamp | <?php
use Arcanesoft\Blog\Bases\Migration;
use Illuminate\Database\Schema\Blueprint;
/**
* Class CreateBlogPostsTable
*
* @author ARCANEDEV <[email protected]>
*
* @see \Arcanesoft\Blog\Models\Post
*/
class CreateBlogPostsTable extends Migration
{
/* -----------------------------------------------------------------
| Constructor
| -----------------------------------------------------------------
*/
/**
* CreateBlogPostsTable constructor.
*/
public function __construct()
{
parent::__construct();
$this->setTable('posts');
}
/* -----------------------------------------------------------------
| Main Methods
| -----------------------------------------------------------------
*/
/**
* {@inheritdoc}
*/
public function up()
{
$this->createSchema(function(Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('author_id')->default(0);
$table->unsignedInteger('category_id');
$table->string('locale', 5)->default(config('app.locale'));
$table->string('title');
$table->string('slug');
$table->text('excerpt');
$table->string('thumbnail')->nullable();
$table->longtext('content_raw');
$table->longtext('content_html');
$table->boolean('is_draft')->default(false);
$table->timestamps();
$table->timestamp('published_at')->nullable();
$table->softDeletes();
$table->unique(['locale', 'slug']);
});
}
}
| <?php
use Arcanesoft\Blog\Bases\Migration;
use Illuminate\Database\Schema\Blueprint;
/**
* Class CreateBlogPostsTable
*
* @author ARCANEDEV <[email protected]>
*
* @see \Arcanesoft\Blog\Models\Post
*/
class CreateBlogPostsTable extends Migration
{
/* -----------------------------------------------------------------
| Constructor
| -----------------------------------------------------------------
*/
/**
* CreateBlogPostsTable constructor.
*/
public function __construct()
{
parent::__construct();
$this->setTable('posts');
}
/* -----------------------------------------------------------------
| Main Methods
| -----------------------------------------------------------------
*/
/**
* {@inheritdoc}
*/
public function up()
{
$this->createSchema(function(Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('author_id')->default(0);
$table->unsignedInteger('category_id');
$table->string('locale', 5)->default(config('app.locale'));
$table->string('title');
$table->string('slug');
$table->text('excerpt');
$table->string('thumbnail')->nullable();
$table->longtext('content_raw');
$table->longtext('content_html');
$table->boolean('is_draft')->default(false);
$table->timestamps();
$table->timestamp('published_at');
$table->softDeletes();
$table->unique(['locale', 'slug']);
});
}
}
|
Add missing slash so that Forward config error is rendered properly
Closes centerforopenscience/openscienceframework.org#941 | # -*- coding: utf-8 -*-
"""Forward addon routes."""
from framework.routing import Rule, json_renderer
from website.routes import OsfWebRenderer
from website.addons.forward import views
api_routes = {
'rules': [
Rule(
[
'/project/<pid>/forward/config/',
'/project/<pid>/node/<nid>/forward/config/'
],
'get',
views.config.forward_config_get,
json_renderer,
),
Rule(
[
'/project/<pid>/forward/config/',
'/project/<pid>/node/<nid>/forward/config/'
],
'put',
views.config.forward_config_put,
json_renderer,
),
Rule(
[
'/project/<pid>/forward/widget/',
'/project/<pid>/node/<nid>/forward/widget/',
],
'get',
views.widget.forward_widget,
OsfWebRenderer('../addons/forward/templates/forward_widget.mako'),
)
],
'prefix': '/api/v1',
}
| # -*- coding: utf-8 -*-
"""Forward addon routes."""
from framework.routing import Rule, json_renderer
from website.routes import OsfWebRenderer
from website.addons.forward import views
api_routes = {
'rules': [
Rule(
[
'/project/<pid>/forward/config/',
'/project/<pid>/node/<nid>/forward/config/'
],
'get',
views.config.forward_config_get,
json_renderer,
),
Rule(
[
'/project/<pid>/forward/config/',
'/project/<pid>/node/<nid>/forward/config/'
],
'put',
views.config.forward_config_put,
json_renderer,
),
Rule(
[
'/project/<pid>/forward/widget/',
'/project/<pid>/node/<nid>forward/widget/',
],
'get',
views.widget.forward_widget,
OsfWebRenderer('../addons/forward/templates/forward_widget.mako'),
)
],
'prefix': '/api/v1',
}
|
Fix a typo setting the port | const
express = require('express'),
bodyParser = require('body-parser');
const
{mongoose} = require('./db/mongoose'),
dbHandler = require('./db/dbHandler');
let app = express();
let port = process.env.PORT || 3000;
app.use(bodyParser.json());
app.route('/todos')
.get((req, res) => {
dbHandler.findTodos().then((value) => {
res.send({
todos: value.data
});
}).catch((err) => {
console.error('There was an error fetching the todos.', err);
res.status(err.code).send({message: err.message});
});
})
.post((req, res) => {
dbHandler.saveTodo(req.body.text).then((value) => {
res.send(value.data);
}).catch((err) => {
console.error('There was an error saving the todo.', err);
res.status(err.code).send({message: err.message});
});
});
app.route('/todos/:id')
.get((req, res) => {
dbHandler.findTodo(req.params.id).then((value) => {
res.send({
todo: value.data
});
}).catch((err) => {
console.error('There was an error fetching the todo.', err);
res.status(err.code).send({message: err.message});
})
})
app.listen(port, () => {
console.log(`Started up at port ${port}`);
});
module.exports = {app};
| const
express = require('express'),
bodyParser = require('body-parser');
const
{mongoose} = require('./db/mongoose'),
dbHandler = require('./db/dbHandler');
let app = express();
let port = porcess.env.PORT || 3000;
app.use(bodyParser.json());
app.route('/todos')
.get((req, res) => {
dbHandler.findTodos().then((value) => {
res.send({
todos: value.data
});
}).catch((err) => {
console.error('There was an error fetching the todos.', err);
res.status(err.code).send({message: err.message});
});
})
.post((req, res) => {
dbHandler.saveTodo(req.body.text).then((value) => {
res.send(value.data);
}).catch((err) => {
console.error('There was an error saving the todo.', err);
res.status(err.code).send({message: err.message});
});
});
app.route('/todos/:id')
.get((req, res) => {
dbHandler.findTodo(req.params.id).then((value) => {
res.send({
todo: value.data
});
}).catch((err) => {
console.error('There was an error fetching the todo.', err);
res.status(err.code).send({message: err.message});
})
})
app.listen(port, () => {
console.log(`Started up at port ${port}`);
});
module.exports = {app};
|
Add tests for admin client models | /* global ic */
var ajax = function () {
return ic.ajax.request.apply(null, arguments);
};
// Used in API request fail handlers to parse a standard api error
// response json for the message to display
function getRequestErrorMessage(request, performConcat) {
var message,
msgDetail;
// Can't really continue without a request
if (!request) {
return null;
}
// Seems like a sensible default
message = request.statusText;
// If a non 200 response
if (request.status !== 200) {
try {
// Try to parse out the error, or default to 'Unknown'
if (request.responseJSON.errors && Ember.isArray(request.responseJSON.errors)) {
message = request.responseJSON.errors.map(function (errorItem) {
return errorItem.message;
});
} else {
message = request.responseJSON.error || 'Unknown Error';
}
} catch (e) {
msgDetail = request.status ? request.status + ' - ' + request.statusText : 'Server was not available';
message = 'The server returned an error (' + msgDetail + ').';
}
}
if (performConcat && Ember.isArray(message)) {
message = message.join('<br />');
}
// return an array of errors by default
if (!performConcat && typeof message === 'string') {
message = [message];
}
return message;
}
export {getRequestErrorMessage, ajax};
export default ajax;
| /* global ic */
var ajax = window.ajax = function () {
return ic.ajax.request.apply(null, arguments);
};
// Used in API request fail handlers to parse a standard api error
// response json for the message to display
function getRequestErrorMessage(request, performConcat) {
var message,
msgDetail;
// Can't really continue without a request
if (!request) {
return null;
}
// Seems like a sensible default
message = request.statusText;
// If a non 200 response
if (request.status !== 200) {
try {
// Try to parse out the error, or default to 'Unknown'
if (request.responseJSON.errors && Ember.isArray(request.responseJSON.errors)) {
message = request.responseJSON.errors.map(function (errorItem) {
return errorItem.message;
});
} else {
message = request.responseJSON.error || 'Unknown Error';
}
} catch (e) {
msgDetail = request.status ? request.status + ' - ' + request.statusText : 'Server was not available';
message = 'The server returned an error (' + msgDetail + ').';
}
}
if (performConcat && Ember.isArray(message)) {
message = message.join('<br />');
}
// return an array of errors by default
if (!performConcat && typeof message === 'string') {
message = [message];
}
return message;
}
export {getRequestErrorMessage, ajax};
export default ajax;
|
Set minimum pyop version to v3.4.0 to ensure the needed methods are available
Signed-off-by: Ivan Kanakarakis <[email protected]> | """
setup.py
"""
from setuptools import setup, find_packages
setup(
name='SATOSA',
version='8.1.0',
description='Protocol proxy (SAML/OIDC).',
author='DIRG',
author_email='[email protected]',
license='Apache 2.0',
url='https://github.com/SUNET/SATOSA',
packages=find_packages('src/'),
package_dir={'': 'src'},
install_requires=[
"pyop >= v3.4.0",
"pysaml2 >= 6.5.1",
"pycryptodomex",
"requests",
"PyYAML",
"gunicorn",
"Werkzeug",
"click",
"chevron",
"cookies-samesite-compat",
],
extras_require={
"ldap": ["ldap3"],
"pyop_mongo": ["pyop[mongo]"],
"pyop_redis": ["pyop[redis]"],
},
zip_safe=False,
classifiers=[
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
],
entry_points={
"console_scripts": ["satosa-saml-metadata=satosa.scripts.satosa_saml_metadata:construct_saml_metadata"]
}
)
| """
setup.py
"""
from setuptools import setup, find_packages
setup(
name='SATOSA',
version='8.1.0',
description='Protocol proxy (SAML/OIDC).',
author='DIRG',
author_email='[email protected]',
license='Apache 2.0',
url='https://github.com/SUNET/SATOSA',
packages=find_packages('src/'),
package_dir={'': 'src'},
install_requires=[
"pyop >= 3.3.1",
"pysaml2 >= 6.5.1",
"pycryptodomex",
"requests",
"PyYAML",
"gunicorn",
"Werkzeug",
"click",
"chevron",
"cookies-samesite-compat",
],
extras_require={
"ldap": ["ldap3"],
"pyop_mongo": ["pyop[mongo]"],
"pyop_redis": ["pyop[redis]"],
},
zip_safe=False,
classifiers=[
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
],
entry_points={
"console_scripts": ["satosa-saml-metadata=satosa.scripts.satosa_saml_metadata:construct_saml_metadata"]
}
)
|
Fix vertical scrolling on race details activity on older devices
When the Google Maps workaround is needed on older devices, the
vertical scrolling was also inadvertently disabled.
Signed-off-by: Greg Meiste <[email protected]> | /*
* Copyright (C) 2014-2015 Gregory S. Meiste <http://gregmeiste.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.meiste.greg.ptw.view;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
public class ControllableViewPager extends ViewPager {
private boolean mPagingEnabled;
public ControllableViewPager(final Context context, final AttributeSet attrs) {
super(context, attrs);
mPagingEnabled = true;
}
@Override
public boolean onTouchEvent(final MotionEvent event) {
if (mPagingEnabled) {
return super.onTouchEvent(event);
}
return false;
}
@Override
public boolean onInterceptTouchEvent(final MotionEvent event) {
if (mPagingEnabled) {
return super.onInterceptTouchEvent(event);
}
return false;
}
public void setPagingEnabled(final boolean enabled) {
mPagingEnabled = enabled;
}
}
| /*
* Copyright (C) 2014 Gregory S. Meiste <http://gregmeiste.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.meiste.greg.ptw.view;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
public class ControllableViewPager extends ViewPager {
private boolean mPagingEnabled;
public ControllableViewPager(final Context context, final AttributeSet attrs) {
super(context, attrs);
mPagingEnabled = true;
}
@Override
public boolean onTouchEvent(final MotionEvent event) {
if (mPagingEnabled) {
return super.onTouchEvent(event);
}
return true;
}
@Override
public boolean onInterceptTouchEvent(final MotionEvent event) {
if (mPagingEnabled) {
return super.onInterceptTouchEvent(event);
}
return true;
}
public void setPagingEnabled(final boolean enabled) {
mPagingEnabled = enabled;
}
}
|
Add missing argument specification for cwd argument. | import os
import sys
from boto.utils import ShellCommand, get_ts
import boto
import boto.utils
class ScriptBase:
def __init__(self, config_file=None):
self.instance_id = boto.config.get('Instance', 'instance-id', 'default')
self.name = self.__class__.__name__
self.ts = get_ts()
if config_file:
boto.config.read(config_file)
def notify(self, subject, body=''):
boto.utils.notify(subject, body)
def mkdir(self, path):
if not os.path.isdir(path):
try:
os.mkdir(path)
except:
boto.log.error('Error creating directory: %s' % path)
def umount(self, path):
if os.path.ismount(path):
self.run('umount %s' % path)
def run(self, command, notify=True, exit_on_error=False, cwd=None):
self.last_command = ShellCommand(command, cwd=cwd)
if self.last_command.status != 0:
boto.log.error('Error running command: "%s". Output: "%s"' % (command, self.last_command.output))
if notify:
self.notify('Error encountered', \
'Error running the following command:\n\t%s\n\nCommand output:\n\t%s' % \
(command, self.last_command.output))
if exit_on_error:
sys.exit(-1)
return self.last_command.status
def main(self):
pass
| import os
import sys
from boto.utils import ShellCommand, get_ts
import boto
import boto.utils
class ScriptBase:
def __init__(self, config_file=None):
self.instance_id = boto.config.get('Instance', 'instance-id', 'default')
self.name = self.__class__.__name__
self.ts = get_ts()
if config_file:
boto.config.read(config_file)
def notify(self, subject, body=''):
boto.utils.notify(subject, body)
def mkdir(self, path):
if not os.path.isdir(path):
try:
os.mkdir(path)
except:
boto.log.error('Error creating directory: %s' % path)
def umount(self, path):
if os.path.ismount(path):
self.run('umount %s' % path)
def run(self, command, notify=True, exit_on_error=False, cwd=None):
self.last_command = ShellCommand(command, cwd)
if self.last_command.status != 0:
boto.log.error('Error running command: "%s". Output: "%s"' % (command, self.last_command.output))
if notify:
self.notify('Error encountered', \
'Error running the following command:\n\t%s\n\nCommand output:\n\t%s' % \
(command, self.last_command.output))
if exit_on_error:
sys.exit(-1)
return self.last_command.status
def main(self):
pass
|
Use print() function to fix install on python 3
clint 0.3.2 can't be installed on python 3.3 because of a print statement. | # -*- coding: utf8 -*-
"""
clint.textui.prompt
~~~~~~~~~~~~~~~~~~~
Module for simple interactive prompts handling
"""
from __future__ import absolute_import, print_function
from re import match, I
def yn(prompt, default='y', batch=False):
# A sanity check against default value
# If not y/n then y is assumed
if default not in ['y', 'n']:
default = 'y'
# Let's build the prompt
choicebox = '[Y/n]' if default == 'y' else '[y/N]'
prompt = prompt + ' ' + choicebox + ' '
# If input is not a yes/no variant or empty
# keep asking
while True:
# If batch option is True then auto reply
# with default input
if not batch:
input = raw_input(prompt).strip()
else:
print(prompt)
input = ''
# If input is empty default choice is assumed
# so we return True
if input == '':
return True
# Given 'yes' as input if default choice is y
# then return True, False otherwise
if match('y(?:es)?', input, I):
return True if default == 'y' else False
# Given 'no' as input if default choice is n
# then return True, False otherwise
elif match('n(?:o)?', input, I):
return True if default == 'n' else False
| # -*- coding: utf8 -*-
"""
clint.textui.prompt
~~~~~~~~~~~~~~~~~~~
Module for simple interactive prompts handling
"""
from __future__ import absolute_import
from re import match, I
def yn(prompt, default='y', batch=False):
# A sanity check against default value
# If not y/n then y is assumed
if default not in ['y', 'n']:
default = 'y'
# Let's build the prompt
choicebox = '[Y/n]' if default == 'y' else '[y/N]'
prompt = prompt + ' ' + choicebox + ' '
# If input is not a yes/no variant or empty
# keep asking
while True:
# If batch option is True then auto reply
# with default input
if not batch:
input = raw_input(prompt).strip()
else:
print prompt
input = ''
# If input is empty default choice is assumed
# so we return True
if input == '':
return True
# Given 'yes' as input if default choice is y
# then return True, False otherwise
if match('y(?:es)?', input, I):
return True if default == 'y' else False
# Given 'no' as input if default choice is n
# then return True, False otherwise
elif match('n(?:o)?', input, I):
return True if default == 'n' else False
|
Fix bew 'No info available' | # -*- coding: utf-8 -*-
__author__ = 'nickl-'
from aero.__version__ import __version__
from .base import BaseAdapter
class Brew(BaseAdapter):
"""
Homebrew adapter.
"""
adapter_command = 'brew'
def search(self, query):
response = self._execute_command(self.adapter_command, ['search', query])[0]
if 'No formula found' not in response and 'Error:' not in response:
return dict([(
self.adapter_command + ':' + line,
'\n'.join(map(
lambda k: k[0] if len(k) < 2 else k[0] + ': ' + k[1],
self.info(line)
))
) for line in response.splitlines() if line])
return {}
def info(self, query):
if '/' in query:
self._execute_command(self.adapter_command, ['tap', '/'.join(query.split('/')[:-1])])
response = self._execute_command(self.adapter_command, ['info', query])[0]
if 'Error:' not in response:
response = response.replace(query + ': ', 'version: ')
return [line.split(': ', 1) for line in response.splitlines() if 'homebrew' not in line]
return [['No info available']]
def install(self, query):
print
self._execute_shell(self.adapter_command, ['install', query])
return {}
| # -*- coding: utf-8 -*-
__author__ = 'nickl-'
from aero.__version__ import __version__
from .base import BaseAdapter
class Brew(BaseAdapter):
"""
Homebrew adapter.
"""
adapter_command = 'brew'
def search(self, query):
response = self._execute_command(self.adapter_command, ['search', query])[0]
if 'No formula found' not in response and 'Error:' not in response:
return dict([(
self.adapter_command + ':' + line,
'\n'.join(map(
lambda k: k[0] if len(k) < 2 else k[0] + ': ' + k[1],
self.info(line)
))
) for line in response.splitlines() if line])
return {}
def info(self, query):
if '/' in query:
self._execute_command(self.adapter_command, ['tap', '/'.join(query.split('/')[:-1])])
response = self._execute_command(self.adapter_command, ['info', query])[0]
if 'Error:' not in response:
response = response.replace(query + ': ', 'version: ')
return [line.split(': ', 1) for line in response.splitlines() if 'homebrew' not in line]
return 'No info available'
def install(self, query):
print
self._execute_shell(self.adapter_command, ['install', query])
return {}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.