text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Use a mock for Auth object | <?php
class BaseTest extends PHPUnit_Framework_TestCase {
/**
* @var PHPUnit_Framework_MockObject_MockObject
*/
protected $mockAuth;
/**
* @var PHPUnit_Framework_MockObject_MockObject
*/
protected $mockClient;
public function setUp()
{
$this->mockAuth = $this->getMockBuilder("\BulkSmsCenter\Auth")->setConstructorArgs([
'YOUR_USERNAME',
'YOUR_PASSWORD',
])->getMock();
$this->mockClient = $this->getMockBuilder("\BulkSmsCenter\HttpClient")->getMock();
}
public function testConstructor()
{
$client = new \BulkSmsCenter\Client();
$this->assertInstanceOf('BulkSmsCenter\Message',$client->getMessage());
}
public function testHttpClientMock()
{
$this->mockClient->expects($this->atLeastOnce())->method('setUserAgent');
$client = new \BulkSmsCenter\Client($this->auth,$this->mockClient);
}
}
| <?php
class BaseTest extends PHPUnit_Framework_TestCase {
/**
* @var \BulkSmsCenter\Auth
*/
protected $auth;
/**
* @var PHPUnit_Framework_MockObject_MockObject
*/
protected $mockClient;
public function setUp()
{
$this->auth = new \BulkSmsCenter\Auth('YOUR_USERNAME','YOUR_PASSWORD');
$this->mockClient = $this->getMockBuilder("\BulkSmsCenter\HttpClient")->getMock();
}
public function testConstructor()
{
$client = new \BulkSmsCenter\Client();
$this->assertInstanceOf('BulkSmsCenter\Message',$client->getMessage());
}
public function testHttpClientMock()
{
$this->mockClient->expects($this->atLeastOnce())->method('setUserAgent');
$client = new \BulkSmsCenter\Client($this->auth,$this->mockClient);
}
}
|
Fix issue with message extractor on Py2 | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from .ir import TranslatableTextNode
def gettext(s):
return s
def extract(fileobj, keywords, comment_tags, options):
'''Babel entry point that extracts translation strings from XML templates.
'''
from .xml_template import _Parser, _Compiler, expand
source = fileobj.read()
if isinstance(source, bytes):
source = source.decode('utf-8')
doc = _Parser(filename='<string>', source=source).parse()
expand(doc)
compiler = _Compiler(filename='<string>', doc=doc,
mode=options.get('mode', 'xml'),
is_fragment=options.get('is_fragment', False))
ir = compiler.compile()
for node in ir:
if isinstance(node, TranslatableTextNode):
if node.text.strip():
for line in node.text.split('\n'):
yield (node.lineno, '_', line, [])
| # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from .ir import TranslatableTextNode
def gettext(s):
return s
def extract(fileobj, keywords, comment_tags, options):
'''Babel entry point that extracts translation strings from XML templates.
'''
from .xml_template import _Parser, _Compiler, expand
doc = _Parser(filename='<string>', source=fileobj.read()).parse()
expand(doc)
compiler = _Compiler(filename='<string>', doc=doc,
mode=options.get('mode', 'xml'),
is_fragment=options.get('is_fragment', False))
ir = compiler.compile()
for node in ir:
if isinstance(node, TranslatableTextNode):
if node.text.strip():
for line in node.text.split('\n'):
yield (node.lineno, '_', line, [])
|
Use more generic event class. | <?php
namespace actsmart\actsmart\Stores;
use actsmart\actsmart\Conversations\Conversation;
use actsmart\actsmart\Sensors\UtteranceEvent;
use actsmart\actsmart\Interpreters\Intent;
use actsmart\actsmart\Sensors\SensorEvent;
interface ConversationTemplateStoreInterface
{
/**
* @param Conversation $conversation
*/
public function addConversation(Conversation $conversation);
/**
* @param array $conversations
*/
public function addConversations($conversations);
/**
* @param $conversation_template_id
* @return Conversation
*/
public function getConversation($conversation_template_id);
/**
* Returns the set of conversations whose opening utterance has an intent that
* matches the $intent.
*
* @param Intent $intent
* @return array | boolean
*/
public function getMatchingConversations(SensorEvent $e, Intent $intent);
/**
* Returns a single match - the first conversation that matchs for now.
*
* @todo This should become more sophisticated than simply return the first
* conversation.
*
* @param Intent $intent
* @return mixed
*/
public function getMatchingConversation(SensorEvent $e, Intent $intent);
/**
* Creates the conversations objects this store will deal with.
* @return mixed
*/
public function buildConversations();
}
| <?php
namespace actsmart\actsmart\Stores;
use actsmart\actsmart\Conversations\Conversation;
use actsmart\actsmart\Sensors\UtteranceEvent;
use actsmart\actsmart\Interpreters\Intent;
use actsmart\actsmart\Sensors\SensorEvent;
interface ConversationTemplateStoreInterface
{
/**
* @param Conversation $conversation
*/
public function addConversation(Conversation $conversation);
/**
* @param array $conversations
*/
public function addConversations($conversations);
/**
* @param $conversation_template_id
* @return Conversation
*/
public function getConversation($conversation_template_id);
/**
* Returns the set of conversations whose opening utterance has an intent that
* matches the $intent.
*
* @param Intent $intent
* @return array | boolean
*/
public function getMatchingConversations(UtteranceEvent $e, Intent $intent);
/**
* Returns a single match - the first conversation that matchs for now.
*
* @todo This should become more sophisticated than simply return the first
* conversation.
*
* @param Intent $intent
* @return mixed
*/
public function getMatchingConversation(SensorEvent $e, Intent $intent);
/**
* Creates the conversations objects this store will deal with.
* @return mixed
*/
public function buildConversations();
}
|
Fix if inbound state in none | import { Map } from 'immutable';
export const lastStateInit = new Map();
export function stateIterator(state, callback) {
return state.forEach(callback);
}
export function stateGetter(state, key) {
return state.get(key)
};
export function stateSetter(state, key, value) {
return state.set(key, value)
};
export function stateReconciler(state, inboundState, reducedState, logger) {
let newState = reducedState ? reducedState : new Map();
Object.keys(inboundState).forEach((key) => {
// if initialState does not have key, skip auto rehydration
if (!state.has(key)) return
// if reducer modifies substate, skip auto rehydration
if (state.get('key') !== reducedState.get('key')) {
if (logger) console.log('redux-persist/autoRehydrate: sub state for key `%s` modified, skipping autoRehydrate.', key)
newState = newState.set(key, reducedState.get(key))
return
}
// otherwise take the inboundState
if (state.has(key)) {
newState = state.merge(inboundState) // shallow merge
} else {
newState = state.set(key, inboundState[key]) // hard set
}
if (logger) console.log('redux-persist/autoRehydrate: key `%s`, rehydrated to ', key, newState[key])
})
return newState
};
| import { Map } from 'immutable';
export const lastStateInit = new Map();
export function stateIterator(state, callback) {
return state.forEach(callback);
}
export function stateGetter(state, key) {
return state.get(key)
};
export function stateSetter(state, key, value) {
return state.set(key, value)
};
export function stateReconciler(state, inboundState, reducedState, logger) {
let newState = new Map();
Object.keys(inboundState).forEach((key) => {
// if initialState does not have key, skip auto rehydration
if (!state.has(key)) return
// if reducer modifies substate, skip auto rehydration
if (state.get('key') !== reducedState.get('key')) {
if (logger) console.log('redux-persist/autoRehydrate: sub state for key `%s` modified, skipping autoRehydrate.', key)
newState = newState.set(key, reducedState.get(key))
return
}
// otherwise take the inboundState
if (state.has(key)) {
newState = state.merge(inboundState) // shallow merge
} else {
newState = state.set(key, inboundState[key]) // hard set
}
if (logger) console.log('redux-persist/autoRehydrate: key `%s`, rehydrated to ', key, newState[key])
})
return newState
};
|
Make sure context is not printed twice in processor exceptions
PiperOrigin-RevId: 307466258 | /*
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.j2cl.ast.processors.common;
/** Wrapper for exceptions thrown from processors. */
public class ProcessorError extends Error {
public ProcessorError(Object context, Object node, Throwable cause) {
super("Context:\n\n" + context + "\n");
initCause(
context != node
? new ProcessorError("Error while processing:\n\n" + node + "\n", cause)
: cause);
}
private ProcessorError(String msg, Throwable cause) {
super(msg, cause);
}
}
| /*
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.j2cl.ast.processors.common;
/** Wrapper for exceptions thrown from processors. */
public class ProcessorError extends Error {
public ProcessorError(Object context, Object node, Throwable cause) {
super("Context:\n\n" + context + "\n");
initCause(new ProcessorError("Error while processing:\n\n" + node + "\n", cause));
}
private ProcessorError(String msg, Throwable cause) {
super(msg, cause);
}
}
|
Fix class names for icons in trees for Bootstrap 3 | $(function () {
$('.tree li:has(ul)').addClass('parent_li').find(' > span').attr('title', 'Collapse this branch');
$('.tree li.parent_li > span').on('click', function (e) {
var children = $(this).parent('li.parent_li').find(' > ul > li');
if (children.is(":visible")) {
children.hide('fast');
$(this).attr('title', 'Expand this branch').find(' > i').addClass('glyphicon-plus-sign').removeClass('glyphicon-minus-sign');
} else {
children.show('fast');
$(this).attr('title', 'Collapse this branch').find(' > i').addClass('glyphicon-minus-sign').removeClass('glyphicon-plus-sign');
}
e.stopPropagation();
});
});
| $(function () {
$('.tree li:has(ul)').addClass('parent_li').find(' > span').attr('title', 'Collapse this branch');
$('.tree li.parent_li > span').on('click', function (e) {
var children = $(this).parent('li.parent_li').find(' > ul > li');
if (children.is(":visible")) {
children.hide('fast');
$(this).attr('title', 'Expand this branch').find(' > i').addClass('icon-plus-sign').removeClass('icon-minus-sign');
} else {
children.show('fast');
$(this).attr('title', 'Collapse this branch').find(' > i').addClass('icon-minus-sign').removeClass('icon-plus-sign');
}
e.stopPropagation();
});
});
|
Add Creative Commons Attribution 3.0 license
This license is used for many presentation recordings. It would be great
to have the license supported by the application directly and avoid
constantly looking for the license link. | export const CC_LICENSES = [
{
value: 'Creative Commons Attribution 3.0',
url: 'https://creativecommons.org/licenses/by/3.0/legalcode',
},
{
value: 'Creative Commons Attribution 4.0 International',
url: 'https://creativecommons.org/licenses/by/4.0/legalcode',
},
{
value: 'Creative Commons Attribution-ShareAlike 4.0 International',
url: 'https://creativecommons.org/licenses/by-sa/4.0/legalcode',
},
{
value: 'Creative Commons Attribution-NoDerivatives 4.0 International',
url: 'https://creativecommons.org/licenses/by-nd/4.0/legalcode',
},
{
value: 'Creative Commons Attribution-NonCommercial 4.0 International',
url: 'https://creativecommons.org/licenses/by-nc/4.0/legalcode',
},
{
value: 'Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International',
url: 'https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode',
},
{
value: 'Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International',
url: 'https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode',
},
];
export const NONE = 'None';
export const PUBLIC_DOMAIN = 'Public Domain';
export const OTHER = 'other';
export const COPYRIGHT = 'copyright';
| export const CC_LICENSES = [
{
value: 'Creative Commons Attribution 4.0 International',
url: 'https://creativecommons.org/licenses/by/4.0/legalcode',
},
{
value: 'Creative Commons Attribution-ShareAlike 4.0 International',
url: 'https://creativecommons.org/licenses/by-sa/4.0/legalcode',
},
{
value: 'Creative Commons Attribution-NoDerivatives 4.0 International',
url: 'https://creativecommons.org/licenses/by-nd/4.0/legalcode',
},
{
value: 'Creative Commons Attribution-NonCommercial 4.0 International',
url: 'https://creativecommons.org/licenses/by-nc/4.0/legalcode',
},
{
value: 'Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International',
url: 'https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode',
},
{
value: 'Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International',
url: 'https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode',
},
];
export const NONE = 'None';
export const PUBLIC_DOMAIN = 'Public Domain';
export const OTHER = 'other';
export const COPYRIGHT = 'copyright';
|
Clean up the form structure | import React, { Component } from 'react'
export default class App extends Component {
state = {
length: 6,
wordlistLength: 7776
}
static bits (size) {
return Math.floor(Math.log2(size)) + 1
}
numberSetter (key) {
return (event) => this.setState({ [key]: parseInt(event.target.value, 10) })
}
render () {
const size = this.state.wordlistLength ** this.state.length
return (
<form>
<h1>Password Entropy</h1>
<label>
<h2>Length</h2>
<input value={this.state.length} onChange={this.numberSetter('length')} type="number" min="1" required/>
</label>
<h2>Options</h2>
<label>
<h3>Wordlist Length</h3>
<input value={this.state.wordlistLength} onChange={this.numberSetter('wordlistLength')} type="number" min="1" required/>
</label>
<h2>Possible Passwords</h2>
Roughly {size.toPrecision(4)} ({this.constructor.bits(size)} bits of entropy)
</form>
)
}
}
| import React, { Component } from 'react'
export default class App extends Component {
state = {
listSize: 7776,
passwordSize: 6
}
static bits (size) {
return Math.floor(Math.log2(size)) + 1
}
numberSetter (key) {
return (event) => this.setState({ [key]: parseInt(event.target.value, 10) })
}
render () {
const size = this.state.listSize ** this.state.passwordSize
return (
<div>
<h1>Password Entropy</h1>
<h2>Diceware</h2>
<p>
<input value={this.state.passwordSize} onChange={this.numberSetter('passwordSize')} type="number" min="1" required/>
words from a set of
<input value={this.state.listSize} onChange={this.numberSetter('listSize')} type="number" min="1" required/>
</p>
<p>Roughly {size.toPrecision(4)} passwords ({this.constructor.bits(size)} bits of entropy)</p>
</div>
)
}
}
|
Use socket connection to get own IP. | import sh
from sh import docker
import socket
def get_ip():
"""Return a string of the IP of the hosts eth0 interface."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
s.close()
return ip
def cleanup_inside(name):
"""
Clean the inside of a container by deleting the containers and images within it.
"""
docker("exec", "-t", name, "bash", "-c",
"docker rm -f $(docker ps -qa) ; docker rmi $(docker images -qa)",
_ok_code=[0, 1, 255]) # 255 is; "bash": executable file not found in $PATH
def delete_container(name):
"""
Cleanly delete a container.
"""
# We *must* remove all inner containers and images before removing the outer
# container. Otherwise the inner images will stick around and fill disk.
# https://github.com/jpetazzo/dind#important-warning-about-disk-usage
cleanup_inside(name)
sh.docker.rm("-f", name, _ok_code=[0, 1])
| import sh
from sh import docker
def get_ip():
"""Return a string of the IP of the hosts eth0 interface."""
intf = sh.ifconfig.eth0()
return sh.perl(intf, "-ne", 's/dr:(\S+)/print $1/e')
def cleanup_inside(name):
"""
Clean the inside of a container by deleting the containers and images within it.
"""
docker("exec", "-t", name, "bash", "-c",
"docker rm -f $(docker ps -qa) ; docker rmi $(docker images -qa)",
_ok_code=[0, 1, 255]) # 255 is; "bash": executable file not found in $PATH
def delete_container(name):
"""
Cleanly delete a container.
"""
# We *must* remove all inner containers and images before removing the outer
# container. Otherwise the inner images will stick around and fill disk.
# https://github.com/jpetazzo/dind#important-warning-about-disk-usage
cleanup_inside(name)
sh.docker.rm("-f", name, _ok_code=[0, 1])
|
Use 'enzyme' for 'View' tests | /* eslint-env mocha */
import assert from 'assert'
import React from 'react'
import { shallow } from 'enzyme'
import View from '../'
suite('components/View', () => {
test('prop "children"', () => {
const children = 'children'
const view = shallow(<View>{children}</View>)
assert.equal(view.prop('children'), children)
})
test('prop "pointerEvents"', () => {
const view = shallow(<View pointerEvents='box-only' />)
assert.equal(view.prop('className'), '__style_pebo')
})
test('prop "style"', () => {
const view = shallow(<View />)
assert.equal(view.prop('style').flexShrink, 0)
const flexView = shallow(<View style={{ flex: 1 }} />)
assert.equal(flexView.prop('style').flexShrink, 1)
const flexShrinkView = shallow(<View style={{ flexShrink: 1 }} />)
assert.equal(flexShrinkView.prop('style').flexShrink, 1)
const flexAndShrinkView = shallow(<View style={{ flex: 1, flexShrink: 2 }} />)
assert.equal(flexAndShrinkView.prop('style').flexShrink, 2)
})
})
| /* eslint-env mocha */
import * as utils from '../../../modules/specHelpers'
import assert from 'assert'
import React from 'react'
import View from '../'
suite('components/View', () => {
test('prop "children"', () => {
const children = 'children'
const result = utils.shallowRender(<View>{children}</View>)
assert.equal(result.props.children, children)
})
test('prop "pointerEvents"', () => {
const result = utils.shallowRender(<View pointerEvents='box-only' />)
assert.equal(result.props.className, '__style_pebo')
})
test('prop "style"', () => {
const noFlex = utils.shallowRender(<View />)
assert.equal(noFlex.props.style.flexShrink, 0)
const flex = utils.shallowRender(<View style={{ flex: 1 }} />)
assert.equal(flex.props.style.flexShrink, 1)
const flexShrink = utils.shallowRender(<View style={{ flexShrink: 1 }} />)
assert.equal(flexShrink.props.style.flexShrink, 1)
const flexAndShrink = utils.shallowRender(<View style={{ flex: 1, flexShrink: 2 }} />)
assert.equal(flexAndShrink.props.style.flexShrink, 2)
})
})
|
Change IoC binding value to: vinelal.social.auth | <?php namespace Vinelab\Auth;
use Illuminate\Support\ServiceProvider;
class AuthServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->package('vinelab/auth');
include __DIR__.'/../../routes.php';
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['vinelab.social.auth'] = $this->app->share(function($app){
return new Social($app['config'], $app['cache'], $app['redirect']);
});
$this->app->booting(function(){
$loader = \Illuminate\Foundation\AliasLoader::getInstance();
$loader->alias('SocialAuth', 'Vinelab\Auth\Social');
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array();
}
} | <?php namespace Vinelab\Auth;
use Illuminate\Support\ServiceProvider;
class AuthServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->package('vinelab/auth');
include __DIR__.'/../../routes.php';
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['social_auth'] = $this->app->share(function($app){
return new Social;
});
$this->app->booting(function(){
$loader = \Illuminate\Foundation\AliasLoader::getInstance();
$loader->alias('SocialAuth', 'Vinelab\Auth\Social');
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array();
}
} |
Prepare for next dev cycle | #!/usr/bin/env python
# coding: utf-8
from setuptools import setup, find_packages
setup(
name="bentoo",
description="Benchmarking tools",
version="0.21.dev",
packages=find_packages(),
scripts=["scripts/bentoo-generator.py", "scripts/bentoo-runner.py",
"scripts/bentoo-collector.py", "scripts/bentoo-analyser.py",
"scripts/bentoo-aggregator.py", "scripts/bentoo-metric.py",
"scripts/bentoo-quickstart.py", "scripts/bentoo-calltree.py",
"scripts/bentoo-merge.py", "scripts/bentoo-calltree-analyser.py",
"scripts/bentoo-viewer.py", "scripts/bentoo-svgconvert.py",
"scripts/bentoo-confreader.py"],
package_data={
'': ['*.adoc', '*.rst', '*.md']
},
author="Zhang YANG",
author_email="zyangmath@gmail.com",
license="PSF",
keywords="Benchmark;Performance Analysis",
url="http://github.com/ProgramFan/bentoo")
| #!/usr/bin/env python
# coding: utf-8
from setuptools import setup, find_packages
setup(
name="bentoo",
description="Benchmarking tools",
version="0.20.0",
packages=find_packages(),
scripts=["scripts/bentoo-generator.py", "scripts/bentoo-runner.py",
"scripts/bentoo-collector.py", "scripts/bentoo-analyser.py",
"scripts/bentoo-aggregator.py", "scripts/bentoo-metric.py",
"scripts/bentoo-quickstart.py", "scripts/bentoo-calltree.py",
"scripts/bentoo-merge.py", "scripts/bentoo-calltree-analyser.py",
"scripts/bentoo-viewer.py", "scripts/bentoo-svgconvert.py",
"scripts/bentoo-confreader.py"],
package_data={
'': ['*.adoc', '*.rst', '*.md']
},
author="Zhang YANG",
author_email="zyangmath@gmail.com",
license="PSF",
keywords="Benchmark;Performance Analysis",
url="http://github.com/ProgramFan/bentoo")
|
Use the settings' wiki root, if any. | from flask import Flask, abort
# Create the main app.
app = Flask(__name__)
app.config.from_object('wikked.settings')
app.config.from_envvar('WIKKED_SETTINGS', silent=True)
if app.config['DEBUG']:
from werkzeug import SharedDataMiddleware
import os
app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
'/': os.path.join(os.path.dirname(__file__), 'static')
})
# The main Wiki instance.
from wiki import Wiki
wiki = Wiki(root=app.config.get('WIKI_ROOT'), logger=app.logger)
# Import views and user loader.
import wikked.views
# Login extension.
from flask.ext.login import LoginManager
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.user_loader(wiki.auth.getUser)
login_manager.unauthorized_handler(lambda: abort(401))
# Bcrypt extension.
from flaskext.bcrypt import Bcrypt
app.bcrypt = Bcrypt(app)
| from flask import Flask, abort
# Create the main app.
app = Flask(__name__)
app.config.from_object('wikked.settings')
app.config.from_envvar('WIKKED_SETTINGS', silent=True)
if app.config['DEBUG']:
from werkzeug import SharedDataMiddleware
import os
app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
'/': os.path.join(os.path.dirname(__file__), 'static')
})
# The main Wiki instance.
from wiki import Wiki
wiki = Wiki(logger=app.logger)
# Import views and user loader.
import wikked.views
# Login extension.
from flask.ext.login import LoginManager
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.user_loader(wiki.auth.getUser)
login_manager.unauthorized_handler(lambda: abort(401))
# Bcrypt extension.
from flaskext.bcrypt import Bcrypt
app.bcrypt = Bcrypt(app)
|
Hide form for fractal variables when there are no inputs | String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
!function( $ ) {
$(function () {
"use strict"
var getContents = function(fracType) {
$('#config').load('/' + fracType + ' form', function() {
var form = $('#config form');
var map = initialize(fracType);
var emptyForm = $('input', form).length == 0;
$('#config').toggle(!emptyForm);
if(!emptyForm) {
$('input', form).bind('input', function() {
console.log("Form changed, redrawing");
map.reload();
});
form.submit(function() {
console.log("Form submitted");
map.reload();
return false;
});
}
var resize = function() {
$('#maps').width($(window).width())
.height($(window).height());
}
resize();
$(window).resize(function() {
resize();
google.maps.event.trigger(map, 'resize')
});
});
};
$('ul.nav li a').click(function(e) {
var fracType = $(this).attr('id');
console.log(fracType);
getContents(fracType);
$('#masthead').fadeOut();
$('#config').fadeIn();
return false;
});
})
}( window.jQuery );
| String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
!function( $ ) {
$(function () {
"use strict"
var getContents = function(fracType) {
$('#config').load('/' + fracType + ' form', function() {
var form = $('#config form');
var map = initialize(fracType);
$('input', form).bind('input', function() {
console.log("Form changed, redrawing");
map.reload();
});
var resize = function() {
$('#maps').width($(window).width())
.height($(window).height());
}
resize();
$(window).resize(function() {
resize();
google.maps.event.trigger(map, 'resize')
});
form.submit(function() {
console.log("Form submitted");
map.reload();
return false;
});
});
};
$('ul.nav li a').click(function(e) {
var fracType = $(this).attr('id');
console.log(fracType);
getContents(fracType);
$('#masthead').fadeOut();
$('#config').fadeIn();
return false;
});
})
}( window.jQuery );
|
Add comment on FileProvider init
I swear I added this prior to merging, somehow slipped through. Sorry | import os
import io
import errno
from xdg import BaseDirectory
from .common import ProviderError
class Record(object):
def __init__(self, *path):
data_dir = BaseDirectory.save_data_path('lab', 'v1', *path[:-1])
self.path = os.path.join(data_dir, path[-1])
try:
with io.open(self.path, 'r') as fp:
self.data = fp.read()
except IOError as e:
if e.errno == errno.ENOENT:
self.data = None
else:
raise ProviderError(e)
def push(self, data):
with io.open(self.path, 'w', encoding='utf-8') as fp:
return fp.write(data)
class FileProvider(object):
name = 'files'
def __init__(self, config):
# We don't support and configuration, so intentionally empty
pass
def get(self, *path):
return Record(*path)
| import os
import io
import errno
from xdg import BaseDirectory
from .common import ProviderError
class Record(object):
def __init__(self, *path):
data_dir = BaseDirectory.save_data_path('lab', 'v1', *path[:-1])
self.path = os.path.join(data_dir, path[-1])
try:
with io.open(self.path, 'r') as fp:
self.data = fp.read()
except IOError as e:
if e.errno == errno.ENOENT:
self.data = None
else:
raise ProviderError(e)
def push(self, data):
with io.open(self.path, 'w', encoding='utf-8') as fp:
return fp.write(data)
class FileProvider(object):
name = 'files'
def __init__(self, config):
pass
def get(self, *path):
return Record(*path)
|
Revert "Enable minifying JS code." Breaks some code.
This reverts commit 04637023949910deb0a3f71cbd4784f4018ee680. | var connect = require('connect');
var server = connect.createServer();
server.use(connect.static(__dirname));
server.use('/lib', connect.static(__dirname + '/../lib'));
server.use(require('browserify')({
require: [__dirname + '/../lib/eval.js',
__dirname + '/../lib/lambda.js',
__dirname + '/../lib/macro.js',
__dirname + '/../lib/primitives.js',
__dirname + '/../lib/print.js',
'util',
'underscore',
'pegjs'],
//filter: require('uglify-js')
}));
server.listen(9797, '127.0.0.1');
console.log('Listening on 127.0.0.1:9797...');
| var connect = require('connect');
var server = connect.createServer();
server.use(connect.static(__dirname));
server.use('/lib', connect.static(__dirname + '/../lib'));
server.use(require('browserify')({
require: [__dirname + '/../lib/eval.js',
__dirname + '/../lib/lambda.js',
__dirname + '/../lib/macro.js',
__dirname + '/../lib/primitives.js',
__dirname + '/../lib/print.js',
'util',
'underscore',
'pegjs'],
filter: require('uglify-js')
}));
server.listen(9797, '127.0.0.1');
console.log('Listening on 127.0.0.1:9797...');
|
Fix API URL to /api/* | angular.module('questionServices', ['ngResource']).
factory('Question', function($resource) {
return $resource('api/questions/:id/:action', {id:"@id"}, {
update: { method: 'PUT' },
copy: {method: "POST", params: {action: "copy"}}
});
});
angular.module('formServices', ['ngResource']).
factory('Form', function($resource) {
var Form = $resource('api/forms/:id', {id:"@id"}, {
update: { method: 'PUT' }
});
// set up default values
Form.prototype.id = undefined;
Form.prototype.name = "Untitled Form";
Form.prototype.header = "<h2>Default Header</h2>";
Form.prototype.footer = "<h2>Default Footer</h2>";
Form.prototype.questions = [];
return Form;
});
| angular.module('questionServices', ['ngResource']).
factory('Question', function($resource) {
return $resource('questions/:id/:action', {id:"@id"}, {
update: { method: 'PUT' },
copy: {method: "POST", params: {action: "copy"}}
});
});
angular.module('formServices', ['ngResource']).
factory('Form', function($resource) {
var Form = $resource('forms/:id', {id:"@id"}, {
update: { method: 'PUT' }
});
// set up default values
Form.prototype.id = undefined;
Form.prototype.name = "Untitled Form";
Form.prototype.header = "<h2>Default Header</h2>";
Form.prototype.footer = "<h2>Default Footer</h2>";
Form.prototype.questions = [];
return Form;
});
|
Fix import path to default_commands | # noqa
from dodo_commands.default_commands.standard_commands import DodoCommand
from dodo_commands import call_command
from plumbum import local
from plumbum.cmd import git
class Command(DodoCommand): # noqa
help = ""
decorators = []
def add_arguments_imp(self, parser): # noqa
parser.add_argument('branch')
def handle_imp(self, branch, **kwargs): # noqa
src_dir = self.get_config("/ROOT/src_dir")
with local.cwd(src_dir):
has_local_changes = git("diff")
if has_local_changes:
self.runcmd(
["git", "stash", "save", "create_branch_" + branch], cwd=src_dir)
self.runcmd(["git", "checkout", "dev"], cwd=src_dir)
self.runcmd(["git", "pull"], cwd=src_dir)
self.runcmd(["git", "checkout", "-b", branch], cwd=src_dir)
with local.cwd(src_dir):
call_command("gitsplit", "--move", "HEAD")
if has_local_changes:
self.runcmd(["git", "stash", "pop"], cwd=src_dir)
| # noqa
from dodo_commands.defaults.commands.standard_commands import DodoCommand
from dodo_commands import call_command
from plumbum import local
from plumbum.cmd import git
class Command(DodoCommand): # noqa
help = ""
decorators = []
def add_arguments_imp(self, parser): # noqa
parser.add_argument('branch')
def handle_imp(self, branch, **kwargs): # noqa
src_dir = self.get_config("/ROOT/src_dir")
with local.cwd(src_dir):
has_local_changes = git("diff")
if has_local_changes:
self.runcmd(
["git", "stash", "save", "create_branch_" + branch], cwd=src_dir)
self.runcmd(["git", "checkout", "dev"], cwd=src_dir)
self.runcmd(["git", "pull"], cwd=src_dir)
self.runcmd(["git", "checkout", "-b", branch], cwd=src_dir)
with local.cwd(src_dir):
call_command("gitsplit", "--move", "HEAD")
if has_local_changes:
self.runcmd(["git", "stash", "pop"], cwd=src_dir)
|
Fix for calling getInstance before ApplicationContext is available | package com.rainbof.nyxtools;
import android.content.Context;
import android.util.Log;
import com.rainbof.nyxtools.util.S;
public class NyxTools {
private volatile static NyxTools mInstance;
private NyxToolsPersistence persistence;
public static NyxTools getInstance(Context _context) {
if (mInstance == null) {
synchronized (NyxTools.class) {
mInstance = new NyxTools(_context);
}
}
return mInstance;
}
protected NyxTools(Context _context) {
try {
if (_context.getApplicationContext() != null)
_context = _context.getApplicationContext();
} catch (Exception e) {
Log.e(S.TAG + "getApplicationContext",
"You must call getInstance() after super.onCreate(...)");
throw new IllegalStateException();
}
persistence = new NyxToolsPersistence(_context);
}
public boolean setUsername(String username) {
return persistence.setUsername(username);
}
public String getUsername() {
return persistence.getUsername();
}
public boolean setAuthToken(String authToken) {
return persistence.setAuthToken(authToken);
}
public String getAuthToken() {
return persistence.getAuthToken();
}
public String getUserAgentPrefix() {
return persistence.getUserAgentPrefix();
}
public boolean setUserAgentPrefix(String uaPrefix) {
return persistence.setUserAgentPrefix(uaPrefix);
}
}
| package com.rainbof.nyxtools;
import android.content.Context;
public class NyxTools {
private volatile static NyxTools mInstance;
private NyxToolsPersistence persistence;
public static NyxTools getInstance(Context _context) {
if (mInstance == null) {
synchronized (NyxTools.class) {
mInstance = new NyxTools(_context);
}
}
return mInstance;
}
protected NyxTools(Context _context) {
if (_context.getApplicationContext() != null)
_context = _context.getApplicationContext();
persistence = new NyxToolsPersistence(_context);
}
public boolean setUsername(String username) {
return persistence.setUsername(username);
}
public String getUsername() {
return persistence.getUsername();
}
public boolean setAuthToken(String authToken) {
return persistence.setAuthToken(authToken);
}
public String getAuthToken() {
return persistence.getAuthToken();
}
public String getUserAgentPrefix(){
return persistence.getUserAgentPrefix();
}
public boolean setUserAgentPrefix(String uaPrefix){
return persistence.setUserAgentPrefix(uaPrefix);
}
}
|
Add git-php in composer file | <?php
return [ "cdn" => [ "jquery" => "https://code.jquery.com/jquery-3.3.1.min.js",
"bootstrap" => [ "css" => "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css","js" => "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" ],
"semantic" => [ "css" => "https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.0/semantic.min.css","js" => "https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.0/semantic.min.js" ] ],
"composer" => [ "require" =>
[ "twig/twig" => "~1.0","mindplay/annotations" => "dev-master","phpmv/ubiquity" => "2.0.x-dev" ],
"autoload"=>["psr-4"=>[""=>"app/"]],
"require-dev"=>["czproject/git-php"=>"^3.13"]
]
];
| <?php
return [ "cdn" => [ "jquery" => "https://code.jquery.com/jquery-3.3.1.min.js",
"bootstrap" => [ "css" => "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css","js" => "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" ],
"semantic" => [ "css" => "https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.0/semantic.min.css","js" => "https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.0/semantic.min.js" ] ],
"composer" => [ "require" =>
[ "twig/twig" => "~1.0","mindplay/annotations" => "dev-master","phpmv/ubiquity" => "2.0.x-dev" ],
"autoload"=>["psr-4"=>[""=>"app/"]]
]
];
|
Allow pagination from query
Fluid presenter method | <?php
namespace ItvisionSy\LaravelExtras\Presenter;
use ArrayIterator as Iterator;
use Illuminate\Database\Eloquent\Collection as ECollection;
/**
* Description of PresenterCollection
*
* @author muhannad
*/
class Collection extends ECollection {
protected $presenter = false;
public function presenter($set = null) {
if ($set === null) {
return $this->presenter;
} else {
$this->presenter = !!$set;
return $this;
}
}
public function getIterator() {
if ($this->presenter) {
return new ArrayIterator($this->items);
} else {
return new Iterator($this->items);
}
}
public function paginate(\Illuminate\Database\Eloquent\Builder $query, $size = null) {
$paginator = $query->paginate($size);
$this->paginator($paginator);
return $paginator;
}
public function paginator(\Illuminate\Pagination\Paginator &$paginator) {
$items = [];
foreach ($this as $item) {
$items[] = $item;
}
$paginator->setItems($items);
return $paginator;
}
}
| <?php
namespace ItvisionSy\LaravelExtras\Presenter;
use ArrayIterator as Iterator;
use Illuminate\Database\Eloquent\Collection as ECollection;
/**
* Description of PresenterCollection
*
* @author muhannad
*/
class Collection extends ECollection {
protected $presenter = false;
public function presenter($set = null) {
if ($set === null) {
return $this->presenter;
} else {
$this->presenter = !!$set;
}
}
public function getIterator() {
if ($this->presenter) {
return new ArrayIterator($this->items);
} else {
return new Iterator($this->items);
}
}
public function paginator(\Illuminate\Pagination\Paginator &$paginator) {
$items = [];
foreach ($this as $item) {
$items[] = $item;
}
$paginator->setItems($items);
return $paginator;
}
}
|
Add Django < 1.4 requirements | from distutils.core import setup
from setuptools import find_packages
import os
import sys
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def find_packages_in(where, **kwargs):
return [where] + ['%s.%s' % (where, package) for package in find_packages(where=where, **kwargs)]
setup(
name = 'django-multitenant',
version = '0.2.7',
author = 'Allan Lei',
author_email = 'allanlei@helveticode.com',
description = ('Multi-tenant addons for Django'),
license = 'New BSD',
keywords = 'multitenant multidb multischema django',
url = 'https://github.com/allanlei/django-multitenant',
packages=find_packages_in('tenant'),
long_description=read('README.md'),
install_requires=[
'Django<1.4',
],
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: BSD License',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| from distutils.core import setup
from setuptools import find_packages
import os
import sys
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def find_packages_in(where, **kwargs):
return [where] + ['%s.%s' % (where, package) for package in find_packages(where=where, **kwargs)]
setup(
name = 'django-multitenant',
version = '0.2.7',
author = 'Allan Lei',
author_email = 'allanlei@helveticode.com',
description = ('Multi-tenant addons for Django'),
license = 'New BSD',
keywords = 'multitenant multidb multischema django',
url = 'https://github.com/allanlei/django-multitenant',
packages=find_packages_in('tenant'),
long_description=read('README.md'),
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: BSD License',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Fix for attribute import statistics
The currentRecordNumber must be up-to-date for the UI to reflect the
proper numbers of stored / processed / total. | /*
* Copyright 2016 Space Dynamics Laboratory - Utah State University Research Foundation.
*
* 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 edu.usu.sdl.openstorefront.service.io.reader;
import edu.usu.sdl.openstorefront.common.exception.OpenStorefrontRuntimeException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class CSVReader
extends GenericReader<String[]>
{
private au.com.bytecode.opencsv.CSVReader reader;
public CSVReader(InputStream in)
{
super(in);
reader = new au.com.bytecode.opencsv.CSVReader(new InputStreamReader(in));
}
@Override
public String[] nextRecord()
{
try {
currentRecordNumber++;
return reader.readNext();
} catch (IOException ex) {
throw new OpenStorefrontRuntimeException(ex);
}
}
}
| /*
* Copyright 2016 Space Dynamics Laboratory - Utah State University Research Foundation.
*
* 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 edu.usu.sdl.openstorefront.service.io.reader;
import edu.usu.sdl.openstorefront.common.exception.OpenStorefrontRuntimeException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class CSVReader
extends GenericReader<String[]>
{
private au.com.bytecode.opencsv.CSVReader reader;
public CSVReader(InputStream in)
{
super(in);
reader = new au.com.bytecode.opencsv.CSVReader(new InputStreamReader(in));
}
@Override
public String[] nextRecord()
{
try {
return reader.readNext();
} catch (IOException ex) {
throw new OpenStorefrontRuntimeException(ex);
}
}
}
|
Fix bug in start a thread more than one time | import javax.mail.MessagingException;
import javax.mail.Store;
import java.util.concurrent.TimeoutException;
/**
* Created by yiwen on 6/6/16.
*/
public abstract class TimeoutConnect {
private static class Connect implements Runnable {
private Store store;
private String host, username, password;
public Connect(Store store, String host, String username, String password) {
this.store = store;
this.host = host;
this.username = username;
this.password = password;
}
@Override
public void run() {
try {
store.connect(host, username, password);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
public static void timeoutConnect(Store store, String host, String username, String password, long timeout)
throws TimeoutException {
Thread t = new Thread(new Connect(store, host, username, password), "TimeoutConnection");
long t0 = System.currentTimeMillis();
boolean state = true;
while (true) {
if (state) {
t.start();
state = false;
}
if (!t.isAlive()) {
break;
}
if (System.currentTimeMillis() - t0 > timeout) {
System.out.println("Connect store timeout");
throw new TimeoutException("Connect store timeout");
}
}
}
}
| import javax.mail.MessagingException;
import javax.mail.Store;
import java.util.concurrent.TimeoutException;
/**
* Created by yiwen on 6/6/16.
*/
public abstract class TimeoutConnect {
private static class Connect implements Runnable {
private Store store;
private String host, username, password;
public Connect(Store store, String host, String username, String password) {
this.store = store;
this.host = host;
this.username = username;
this.password = password;
}
@Override
public void run() {
try {
store.connect(host, username, password);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
public static void timeoutConnect(Store store, String host, String username, String password, long timeout)
throws TimeoutException {
Thread t = new Thread(new Connect(store, host, username, password), "TimeoutConnection");
long t0 = System.currentTimeMillis();
while (true) {
t.start();
if (!t.isAlive()) {
break;
}
if (System.currentTimeMillis() - t0 > timeout) {
System.out.println("Connect store timeout");
throw new TimeoutException("Connect store timeout");
}
}
}
}
|
Add tests for the non-existence of error messages | var Mocha = require('mocha'),
_ = require('underscore');
module.exports = function (browser, module, suite, config, tests) {
suite = Mocha.Suite.create(suite, module.slug);
tests = _.extend({
exists: function () {
return browser
.$('#' + module.slug).isDisplayed()
.should.eventually.be.ok;
},
'contains no error message': function () {
return browser
.hasElementByCssSelector('#' + module.slug + ' h2.error')
.should.eventually.not.be.ok;
},
'has a title': function () {
return browser
.$('#' + module.slug + ' h2').text()
.should.eventually.equal(module.title);
}
}, tests);
_.each(tests, function (test, key) {
suite.addTest(new Mocha.Test(key, test));
});
try { // to load a test suite corresponding with the module-type
var moduleTests = require('./modules/' + module['module-type']);
moduleTests(browser, module, suite, config);
} catch (e) {
if (e.code === 'MODULE_NOT_FOUND') {
suite.addTest(new Mocha.Test('no test suite is defined for module-type ' + module['module-type']));
}
}
return suite;
};
| var Mocha = require('mocha'),
_ = require('underscore');
module.exports = function (browser, module, suite, config, tests) {
suite = Mocha.Suite.create(suite, module.slug);
tests = _.extend({
exists: function () {
return browser
.$('#' + module.slug).isDisplayed()
.should.eventually.be.ok;
},
'has a title': function () {
return browser
.$('#' + module.slug + ' h2').text()
.should.eventually.equal(module.title);
}
}, tests);
_.each(tests, function (test, key) {
suite.addTest(new Mocha.Test(key, test));
});
try { // to load a test suite corresponding with the module-type
var moduleTests = require('./modules/' + module['module-type']);
moduleTests(browser, module, suite, config);
} catch (e) {
if (e.code === 'MODULE_NOT_FOUND') {
suite.addTest(new Mocha.Test('no test suite is defined for module-type ' + module['module-type']));
}
}
return suite;
};
|
Make sure headers can be children of blockquotes. | <?php
namespace FluxBB\Markdown\Node;
class Blockquote extends Block implements NodeInterface, NodeAcceptorInterface
{
public function getType()
{
return 'block_quote';
}
public function canContain(Node $other)
{
return $other->getType() == 'paragraph';
}
public function accepts(Node $block)
{
return $block->getType() == 'paragraph';
}
public function proposeTo(NodeAcceptorInterface $block)
{
return $block->acceptBlockquote($this);
}
public function acceptParagraph(Paragraph $paragraph)
{
$this->addChild($paragraph);
return $paragraph;
}
public function acceptHeading(Heading $heading)
{
$this->addChild($heading);
return $this;
}
public function acceptBlockquote(Blockquote $blockquote)
{
$this->merge($blockquote);
return $this;
}
public function acceptBlankLine(BlankLine $blankLine)
{
$this->close();
return $this->parent;
}
public function visit(NodeVisitorInterface $visitor)
{
$visitor->enterBlockquote($this);
parent::visit($visitor);
$visitor->leaveBlockquote($this);
}
}
| <?php
namespace FluxBB\Markdown\Node;
class Blockquote extends Block implements NodeInterface, NodeAcceptorInterface
{
public function getType()
{
return 'block_quote';
}
public function canContain(Node $other)
{
return $other->getType() == 'paragraph';
}
public function accepts(Node $block)
{
return $block->getType() == 'paragraph';
}
public function proposeTo(NodeAcceptorInterface $block)
{
return $block->acceptBlockquote($this);
}
public function acceptParagraph(Paragraph $paragraph)
{
$this->addChild($paragraph);
return $paragraph;
}
public function acceptBlockquote(Blockquote $blockquote)
{
$this->merge($blockquote);
return $this;
}
public function acceptBlankLine(BlankLine $blankLine)
{
$this->close();
return $this->parent;
}
public function visit(NodeVisitorInterface $visitor)
{
$visitor->enterBlockquote($this);
parent::visit($visitor);
$visitor->leaveBlockquote($this);
}
}
|
Check time argument as Position type. | """
File: tempo_event.py
Purpose: Defines a tempo as an Event
"""
from timemodel.event import Event
from timemodel.position import Position
class TempoEvent(Event):
"""
Defines tempo as an Event, given a Tempo and a time position.
"""
def __init__(self, tempo, time):
"""
Constructor.
Args:
tempo:(Tempo) object.
time: Postion.
"""
if not isinstance(time, Position):
raise Exception('time argument to TempoEvent must be Position not \'{0}\'.'.format(type(time)))
Event.__init__(self, tempo, time)
def tempo(self):
return self.object.tempo
def __str__(self):
return '[{0}, Tempo({1})]'.format(self.time, self.object)
| """
File: tempo_event.py
Purpose: Defines a tempo as an Event
"""
from timemodel.event import Event
class TempoEvent(Event):
"""
Defines tempo as an Event, given a Tempo and a time position.
"""
def __init__(self, tempo, time):
"""
Constructor.
Args:
tempo:(Tempo) object.
time: Comparable object.
"""
Event.__init__(self, tempo, time)
def tempo(self):
return self.object.tempo
def __str__(self):
return '[{0}, Tempo({1})]'.format(self.time, self.object)
|
Make PhpSpec passing after fixing PHPStan warnings | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace spec\Sylius\Bundle\OrderBundle\Controller;
use PhpSpec\ObjectBehavior;
use Sylius\Bundle\OrderBundle\Controller\AddToCartCommandInterface;
use Sylius\Component\Order\Model\OrderInterface;
use Sylius\Component\Order\Model\OrderItemInterface;
final class AddToCartCommandSpec extends ObjectBehavior
{
function let(OrderInterface $order, OrderItemInterface $orderItem): void
{
$this->beConstructedWith($order, $orderItem);
}
function it_is_add_cart_item_command(): void
{
$this->shouldImplement(AddToCartCommandInterface::class);
}
function it_has_order(OrderInterface $order): void
{
$this->getCart()->shouldReturn($order);
}
function it_has_order_item(OrderItemInterface $orderItem): void
{
$this->getCartItem()->shouldReturn($orderItem);
}
}
| <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace spec\Sylius\Bundle\OrderBundle\Controller;
use PhpSpec\ObjectBehavior;
use Sylius\Bundle\OrderBundle\Controller\AddToCartCommandInterface;
use Sylius\Component\Order\Model\OrderInterface;
use Sylius\Component\Order\Model\OrderItemInterface;
final class AddToCartCommandSpec extends ObjectBehavior
{
function let(OrderInterface $order, OrderItemInterface $orderItem): void
{
$this->beConstructedThrough('createWithCartAndCartItem', [$order, $orderItem]);
}
function it_is_add_cart_item_command(): void
{
$this->shouldImplement(AddToCartCommandInterface::class);
}
function it_has_order(OrderInterface $order): void
{
$this->getCart()->shouldReturn($order);
}
function it_has_order_item(OrderItemInterface $orderItem): void
{
$this->getCartItem()->shouldReturn($orderItem);
}
}
|
Update Expected Library test responses for numbering books | package com.twu.biblioteca;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Created by watsonarw on 16/04/15.
*/
public class LibraryTest {
@Test
public void testSingleBookLibrary() {
Library library = new Library();
library.addBook("The Hobbit", "J.R.R. Tolkien", 1937);
assertEquals(" 1 | The Hobbit - J.R.R. Tolkien, 1937\n",library.getBookList());
}
@Test
public void testMultiBookLibrary() {
Library library = new Library();
library.addBook("The Hobbit", "J.R.R. Tolkien", 1937);
library.addBook("Catcher in the Rye", "J.D. Salinger", 1951);
assertEquals(" 1 | The Hobbit - J.R.R. Tolkien, 1937\n 2 | Catcher in the Rye - J.D. Salinger, 1951\n",library.getBookList());
}
}
| package com.twu.biblioteca;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Created by watsonarw on 16/04/15.
*/
public class LibraryTest {
@Test
public void testSingleBookLibrary() {
Library library = new Library();
library.addBook("The Hobbit", "J.R.R. Tolkien", 1937);
assertEquals("The Hobbit - J.R.R. Tolkien, 1937\n",library.getBookList());
}
@Test
public void testMultiBookLibrary() {
Library library = new Library();
library.addBook("The Hobbit", "J.R.R. Tolkien", 1937);
library.addBook("Catcher in the Rye", "J.D. Salinger", 1951);
assertEquals("The Hobbit - J.R.R. Tolkien, 1937\nCatcher in the Rye - J.D. Salinger, 1951\n",library.getBookList());
}
}
|
Change around so config is loaded when changed | // relay_force_routing
// documentation via: haraka -h plugins/relay_force_routing
exports.hook_get_mx = function (next, hmail, domain) {
var domain_ini = this.config.get('relay_dest_domains.ini', 'ini');
var force_route = lookup_routing(domain_ini['domains'], domain);
if (force_route != "NOTFOUND" ){
this.logdebug('using ' + force_route + ' for: ' + domain);
next(OK, force_route);
} else {
this.logdebug('using normal MX lookup for: ' + domain);
next(CONT);
}
}
/**
* @return {string}
*/
function lookup_routing (domains_ini, domain) {
if (domain in domains_ini) {
var config = JSON.parse(domains_ini[domain]);
return config['nexthop'];
}
return "NOTFOUND";
}
| // relay_force_routing
// documentation via: haraka -h plugins/relay_force_routing
exports.register = function() {
this.register_hook('get_mx', 'force_routing');
this.domain_ini = this.config.get('relay_dest_domains.ini', 'ini');
};
exports.force_routing = function (next, hmail, domain) {
var force_route = lookup_routing(this, this.domain_ini['domains'], domain);
if (force_route != "NOTFOUND" ){
this.logdebug(this, 'using ' + force_route + ' for ' + domain);
next(OK, force_route);
} else {
this.logdebug(this, 'using normal MX lookup' + ' for ' + domain);
next(CONT);
}
};
/**
* @return {string}
*/
function lookup_routing (plugin, domains_ini, domain) {
if (domain in domains_ini) {
var config = JSON.parse(domains_ini[domain]);
plugin.logdebug(plugin, 'found config for' + domain + ': ' + domains_ini['nexthop']);
return config['nexthop'];
}
return "NOTFOUND";
}
|
Add route to limit posts | Router.configure({
layoutTemplate: 'layout',
loadingTemplate: 'loading',
notFoundTemplate: 'notFound',
waitOn: function() {
return Meteor.subscribe('notifications');
}
});
Router.route('/', { name: 'postsList'});
Router.route('/posts/:_id', {
name: 'postPage',
waitOn: function() {
return Meteor.subscribe('comments', this.params._id);
},
data: function() {
return Posts.findOne(this.params._id);
}
});
Router.route('posts/:_id/edit', {
name: 'postEdit',
data: function() {
return Posts.findOne(this.params._id);
}
});
Router.route('/submit', { name: 'postSubmit' });
Router.route('/:postsLimit?', {
name: 'postsList',
waitOn: function() {
var limit = parseInt(this.params.postsLimit) || 5;
return Meteor.subscribe('posts', { sort: { submitted: -1 }, limit: limit });
}
});
var requireLogin = function() {
if (!Meteor.user()) {
if (Meteor.loggingIn()) {
this.render(this.loadingTemplate);
} else {
this.render('accessDenied');
}
} else {
this.next();
}
}
Router.onBeforeAction('dataNotFound', { only: 'postPage' });
Router.onBeforeAction(requireLogin, { only: 'postSubmit' });
| Router.configure({
layoutTemplate: 'layout',
loadingTemplate: 'loading',
notFoundTemplate: 'notFound',
waitOn: function() {
return [Meteor.subscribe('posts'), Meteor.subscribe('notifications')];
}
});
Router.route('/', { name: 'postsList'});
Router.route('/posts/:_id', {
name: 'postPage',
waitOn: function() {
return Meteor.subscribe('comments', this.params._id);
},
data: function() {
return Posts.findOne(this.params._id);
}
});
Router.route('posts/:_id/edit', {
name: 'postEdit',
data: function() {
return Posts.findOne(this.params._id);
}
});
Router.route('/submit', { name: 'postSubmit' });
var requireLogin = function() {
if (!Meteor.user()) {
if (Meteor.loggingIn()) {
this.render(this.loadingTemplate);
} else {
this.render('accessDenied');
}
} else {
this.next();
}
}
Router.onBeforeAction('dataNotFound', { only: 'postPage' });
Router.onBeforeAction(requireLogin, { only: 'postSubmit' });
|
Improve line wrapping in the documentation | //tag::include[]
package org.hibernate.validator.referenceguide.chapter06.constraintvalidatorpayload;
//end::include[]
import javax.validation.ConstraintValidatorContext;
import javax.validation.ConstraintValidator;
import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext;
//tag::include[]
public class ZipCodeValidator implements ConstraintValidator<ZipCode, String> {
public String countryCode;
@Override
public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
if ( object == null ) {
return true;
}
boolean isValid = false;
String countryCode = constraintContext
.unwrap( HibernateConstraintValidatorContext.class )
.getConstraintValidatorPayload( String.class );
if ( "US".equals( countryCode ) ) {
// checks specific to the United States
}
else if ( "FR".equals( countryCode ) ) {
// checks specific to France
}
else {
// ...
}
return isValid;
}
}
//end::include[]
| //tag::include[]
package org.hibernate.validator.referenceguide.chapter06.constraintvalidatorpayload;
//end::include[]
import javax.validation.ConstraintValidatorContext;
import javax.validation.ConstraintValidator;
import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext;
//tag::include[]
public class ZipCodeValidator implements ConstraintValidator<ZipCode, String> {
public String countryCode;
@Override
public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
if ( object == null ) {
return true;
}
boolean isValid = false;
String countryCode = constraintContext.unwrap( HibernateConstraintValidatorContext.class )
.getConstraintValidatorPayload( String.class );
if ( "US".equals( countryCode ) ) {
// checks specific to the United States
}
else if ( "FR".equals( countryCode ) ) {
// checks specific to France
}
else {
// ...
}
return isValid;
}
}
//end::include[]
|
Add support for an index mode | 'use strict';
// MODULES //
var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
var getIndex = require( './get_index.js' );
// FUNCTIONS //
/**
* Returns an array element.
*
* @private
* @param {integer} i - index for first dimension
* @param {integer} j - index for second dimension
* @throws {TypeError} index for first dimension must be an integer value
* @throws {TypeError} index for second dimension must be an integer value
* @returns {*} array element
*/
function get( i, j ) {
/* eslint-disable no-invalid-this */
var idx;
if ( !isInteger( i ) ) {
throw new TypeError( 'invalid input argument. Index for first dimension must be an integer value. Value: `'+i+'`.' );
}
if ( !isInteger( j ) ) {
throw new TypeError( 'invalid input argument. Index for second dimension must be an integer value. Value: `'+j+'`.' );
}
i = getIndex( i, this._shape[ 0 ], this._mode );
j = getIndex( j, this._shape[ 1 ], this._mode );
idx = this._offset + ( this._strides[0]*i ) + ( this._strides[1]*j );
return this._buffer[ idx ];
} // end FUNCTION get()
// EXPORTS //
module.exports = get;
| 'use strict';
// MODULES //
var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
// FUNCTIONS //
/**
* Returns an array element.
*
* @private
* @param {integer} i - index for first dimension
* @param {integer} j - index for second dimension
* @throws {TypeError} index for first dimension must be an integer value
* @throws {TypeError} index for second dimension must be an integer value
* @returns {*} array element
*/
function get( i, j ) {
/* eslint-disable no-invalid-this */
var idx;
if ( !isInteger( i ) ) {
throw new TypeError( 'invalid input argument. Index for first dimension must be an integer value. Value: `'+i+'`.' );
}
if ( !isInteger( j ) ) {
throw new TypeError( 'invalid input argument. Index for second dimension must be an integer value. Value: `'+j+'`.' );
}
// TODO: support index modes
idx = this._offset + ( this._strides[0]*i ) + ( this._strides[1]*j );
return this._buffer[ idx ];
} // end FUNCTION get()
// EXPORTS //
module.exports = get;
|
Update foreign language spam detector | <?php
namespace Lio\Content;
class ForeignLanguageSpamDetector implements SpamDetector
{
/** @inheritdoc */
public function detectsSpam($value)
{
return (bool) preg_match(
"/[일안명빠에외하전나밤사이팅토노카ぬ벳인포방어코리아맨강남야구장강배팅배트ミ법스포츠석사배지석사소테크카주소る】ズअ서현오피अ분당오피अ]+/iu",
$value
);
}
}
| <?php
namespace Lio\Content;
class ForeignLanguageSpamDetector implements SpamDetector
{
/** @inheritdoc */
public function detectsSpam($value)
{
return (bool) preg_match(
"/[일안명빠에외하전나밤사이팅토노카ぬ벳인포방어코리아맨강남야구장강배팅배트ミ법스포츠석사배지석사소테크카주소る】ズ]+/iu",
$value
);
}
}
|
Use clientHeight and pass style params to wrapper so it has the same style/class as original one and height is detected correctly | import React from 'react';
import {shouldComponentUpdate} from 'react-addons-pure-render-mixin';
const HeightReporter = React.createClass({
propTypes: {
children: React.PropTypes.node.isRequired,
onHeightReady: React.PropTypes.func.isRequired
},
componentDidMount() {
this.height = this.refs.wrapper.clientHeight;
if (this.height > 0) {
return this.props.onHeightReady(this.height);
}
},
shouldComponentUpdate,
componentDidUpdate() {
if (this.refs.wrapper.clientHeight > 0 && this.refs.wrapper.clientHeight !== this.height) {
this.height = this.refs.wrapper.clientHeight;
return this.props.onHeightReady(this.height);
}
},
render() {
const {onHeightReady, children, ...props} = this.props;
return (
<div style={{height: 0, overflow: 'hidden'}}>
<div ref="wrapper" {...props}>
{children}
</div>
</div>
);
}
});
export default HeightReporter;
| import React from 'react';
import {shouldComponentUpdate} from 'react-addons-pure-render-mixin';
const HeightReporter = React.createClass({
propTypes: {
children: React.PropTypes.node.isRequired,
onHeightReady: React.PropTypes.func.isRequired
},
componentDidMount() {
this.height = this.refs.wrapper.offsetHeight;
if (this.height > 0) {
return this.props.onHeightReady(this.height);
}
},
shouldComponentUpdate,
componentDidUpdate() {
if (this.refs.wrapper.offsetHeight > 0 && this.refs.wrapper.offsetHeight !== this.height) {
this.height = this.refs.wrapper.offsetHeight;
return this.props.onHeightReady(this.height);
}
},
render() {
return (
<div style={{height: 0, overflow: 'hidden'}}>
<div ref="wrapper">
{this.props.children}
</div>
</div>
);
}
});
export default HeightReporter;
|
Fix for .indexOf on Number | /* ===============================================================================
************ Infinite Scroll ************
=============================================================================== */
function handleInfiniteScroll() {
/*jshint validthis:true */
var inf = this;
var scrollTop = inf.scrollTop;
var scrollHeight = inf.scrollHeight;
var height = inf.offsetHeight;
var distance = inf.getAttribute('data-distance');
if (!distance) distance = 50;
if (typeof distance === 'string' && distance.indexOf('%') >= 0) {
distance = parseInt(distance, 10) / 100 * height;
}
if (distance > height) distance = height;
if (scrollTop + height >= scrollHeight - distance) {
$(inf).trigger('infinite');
}
}
app.attachInfiniteScroll = function (infiniteContent) {
$(infiniteContent).on('scroll', handleInfiniteScroll);
};
app.detachInfiniteScroll = function (infiniteContent) {
$(infiniteContent).off('scroll', handleInfiniteScroll);
};
app.initInfiniteScroll = function (pageContainer) {
pageContainer = $(pageContainer);
var infiniteContent = pageContainer.find('.infinite-scroll');
app.attachInfiniteScroll(infiniteContent);
function detachEvents() {
app.detachInfiniteScroll(infiniteContent);
pageContainer.off('pageBeforeRemove', detachEvents);
}
pageContainer.on('pageBeforeRemove', detachEvents);
}; | /* ===============================================================================
************ Infinite Scroll ************
=============================================================================== */
function handleInfiniteScroll() {
/*jshint validthis:true */
var inf = this;
var scrollTop = inf.scrollTop;
var scrollHeight = inf.scrollHeight;
var height = inf.offsetHeight;
var distance = inf.getAttribute('data-distance');
if (!distance) distance = 50;
if (distance.indexOf('%') >= 0) {
distance = parseInt(distance, 10) / 100 * height;
}
if (distance > height) distance = height;
if (scrollTop + height >= scrollHeight - distance) {
$(inf).trigger('infinite');
}
}
app.attachInfiniteScroll = function (infiniteContent) {
$(infiniteContent).on('scroll', handleInfiniteScroll);
};
app.detachInfiniteScroll = function (infiniteContent) {
$(infiniteContent).off('scroll', handleInfiniteScroll);
};
app.initInfiniteScroll = function (pageContainer) {
pageContainer = $(pageContainer);
var infiniteContent = pageContainer.find('.infinite-scroll');
app.attachInfiniteScroll(infiniteContent);
function detachEvents() {
app.detachInfiniteScroll(infiniteContent);
pageContainer.off('pageBeforeRemove', detachEvents);
}
pageContainer.on('pageBeforeRemove', detachEvents);
}; |
Use relative paths for previews to support sites in sub dirs
The use of an absolute path caused the dataobject previewer iframe to
point to an incorrect path when a site was not located directly in the
document root. A 404 page would display in all preview iframes instead
of the preview that had been rendered. | <?php
/**
* Class DataObjectPreviewer
*/
class DataObjectPreviewer
{
/**
* @param DataObjectPreviewInterface $record
* @return string
*/
public function preview(DataObjectPreviewInterface $record)
{
$content = $record->getPreviewHtml();
$contentMd5 = md5($content);
$htmlFilepath = sprintf(
'%s/%s.html',
DATAOBJECTPREVIEW_CACHE_PATH,
$contentMd5
);
if (!file_exists(DATAOBJECTPREVIEW_CACHE_PATH)) {
mkdir(DATAOBJECTPREVIEW_CACHE_PATH);
}
if (!file_exists($htmlFilepath)) {
file_put_contents($htmlFilepath, $content);
}
return sprintf(
'<div class="dataobjectpreview" data-src="%s"></div>',
str_replace(BASE_PATH . '/', '', $htmlFilepath)
);
}
}
| <?php
/**
* Class DataObjectPreviewer
*/
class DataObjectPreviewer
{
/**
* @param DataObjectPreviewInterface $record
* @return string
*/
public function preview(DataObjectPreviewInterface $record)
{
$content = $record->getPreviewHtml();
$contentMd5 = md5($content);
$htmlFilepath = sprintf(
'%s/%s.html',
DATAOBJECTPREVIEW_CACHE_PATH,
$contentMd5
);
if (!file_exists(DATAOBJECTPREVIEW_CACHE_PATH)) {
mkdir(DATAOBJECTPREVIEW_CACHE_PATH);
}
if (!file_exists($htmlFilepath)) {
file_put_contents($htmlFilepath, $content);
}
return sprintf(
'<div class="dataobjectpreview" data-src="%s"></div>',
str_replace(BASE_PATH, '', $htmlFilepath)
);
}
}
|
Fix for PSR2 spacing around foreach keyword | <?php
namespace League\Event;
class BufferedEmitter extends Emitter
{
/**
* @var EventInterface[]
*/
protected $bufferedEvents = [];
/**
* @inheritdoc
*/
public function emit($event)
{
$this->bufferedEvents[] = $event;
return $event;
}
/**
* @inheritdoc
*/
public function emitBatch(array $events)
{
foreach ($events as $event) {
$this->bufferedEvents[] = $event;
}
return $events;
}
/**
* Emit the buffered events.
*
* @return array
*/
public function emitBufferedEvents()
{
$result = [];
foreach ($this->bufferedEvents as $event) {
$result[] = parent::emit($event);
}
return $result;
}
}
| <?php
namespace League\Event;
class BufferedEmitter extends Emitter
{
/**
* @var EventInterface[]
*/
protected $bufferedEvents = [];
/**
* @inheritdoc
*/
public function emit($event)
{
$this->bufferedEvents[] = $event;
return $event;
}
/**
* @inheritdoc
*/
public function emitBatch(array $events)
{
foreach($events as $event) {
$this->bufferedEvents[] = $event;
}
return $events;
}
/**
* Emit the buffered events.
*
* @return array
*/
public function emitBufferedEvents()
{
$result = [];
foreach($this->bufferedEvents as $event) {
$result[] = parent::emit($event);
}
return $result;
}
}
|
Add explicit `void` return type to UserLoginCancelLostPasswordListener::__invoke() | <?php
namespace wcf\system\event\listener;
use wcf\data\user\UserAction;
use wcf\system\user\authentication\event\UserLoggedIn;
/**
* Cancels lost password requests if the user successfully logs in.
*
* @author Tim Duesterhus
* @copyright 2001-2021 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\Event\Listener
* @since 5.5
*/
final class UserLoginCancelLostPasswordListener
{
public function __invoke(UserLoggedIn $event): void
{
$user = $event->getUser();
if (!$user->lostPasswordKey) {
return;
}
(new UserAction([$user], 'cancelLostPasswordRequest'))->executeAction();
}
}
| <?php
namespace wcf\system\event\listener;
use wcf\data\user\UserAction;
use wcf\system\user\authentication\event\UserLoggedIn;
/**
* Cancels lost password requests if the user successfully logs in.
*
* @author Tim Duesterhus
* @copyright 2001-2021 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\Event\Listener
* @since 5.5
*/
final class UserLoginCancelLostPasswordListener
{
public function __invoke(UserLoggedIn $event)
{
$user = $event->getUser();
if (!$user->lostPasswordKey) {
return;
}
(new UserAction([$user], 'cancelLostPasswordRequest'))->executeAction();
}
}
|
Set focus back to textarea after button was pressed | import React from 'react'
import PropTypes from 'prop-types'
/* Component with a state */
export default class AddChatMessage extends React.Component {
constructor(props) {
super(props)
this.state = {message: ''}
}
onChangeMessage = (e) => {
this.setState({message: e.target.value})
}
onSendCick = () => {
this.props.onClick({message: this.state.message})
this.setState({message:''})
this.textInput.focus()
}
handleKeyPress = (e) => {
if (e.key === 'Enter'){
e.preventDefault()
this.onSendCick()
return false
}
}
render() {
return (
<div>
<textarea ref={(e) => { this.textInput = e }} onChange={this.onChangeMessage} onKeyPress={this.handleKeyPress} value={this.state.message}/>
<button onClick={this.onSendCick}>Send</button>
</div>
)
}
}
AddChatMessage.propTypes = {
onClick: PropTypes.func
} | import React from 'react'
import PropTypes from 'prop-types'
/* Component with a state */
export default class AddChatMessage extends React.Component {
constructor(props) {
super(props)
this.state = {message: ''}
}
onChangeMessage = (e) => {
this.setState({message: e.target.value})
}
onSendCick = () => {
this.props.onClick({message: this.state.message})
this.setState({message:''})
}
handleKeyPress = (e) => {
if (e.key === 'Enter'){
e.preventDefault()
this.onSendCick()
return false
}
}
render() {
return (
<div>
<textarea onChange={this.onChangeMessage} onKeyPress={this.handleKeyPress} value={this.state.message}/>
<button onClick={this.onSendCick}>Send</button>
</div>
)
}
}
AddChatMessage.propTypes = {
onClick: PropTypes.func
} |
Update schema manager test to run. Need to blow away test db before each run | var config = require('../config');
var mongoose = require('mongoose');
var schemaManager;
var should = require('should');
describe('SchemaManager', function() {
before(function(done) {
mongoose.connect(config.db.url);
var db = mongoose.connection;
db.once('open', function() {
schemaManager = require('../util/schema-manager')(mongoose);
done();
});
});
describe('add-invalid-schema', function() {
it("should error adding an empty string ", function(done) {
var name = "";
var schema = "";
schemaManager.addSchema({"name" : name, "definition" : schema}, function(err, entity) {
should.exist(err);
done();
});
});
});
describe('add-valid-schema', function() {
it("should add a valid json schema object", function(done) {
var name = "network_element";
var schema = {
ne_type: "String",
cid: "String",
ip: "String",
ip6: "String",
bgpip: "String",
bgpip6: "String",
}
schemaManager.addSchema({"name" : name, "definition" : schema}, function(err, entity) {
should.not.exist(err);
done();
// figure out how to check the entity
});
});
});
}); | var config = require('../config');
var mongoose = require('mongoose');
var schemaManager;
describe('SchemaManager', function() {
before(function() {
mongoose.connect(config.db.url);
var db = mongoose.connection;
db.once('open', function() {
schemaManager = require('../util/schema-manager')(mongoose);
});
});
describe('add-invalid-schema', function() {
var name = "";
var schema = "";
schemaManager.addSchema({"name" : name, "definition" : schema}, function(err, entity) {
should.exist(err);
});
});
describe('add-valid-schema', function() {
var name = "network_element";
var schema = "{ \
ne_type: String, \
cid: String, \
ip: String, \
ip6: String, \
bgpip: String, \
bgpip6: String, \
}";
schemaManager.addSchema({"name" : name, "definition" : schema}, function(err, entity) {
should.not.exist(err);
// figure out how to check the entity
});
});
}); |
Update to new BBVA html | /* configure jshint globals */
/* globals numeral */
(function ($) {
'use strict';
// Set langauge for Numeral library.
numeral.language('es');
// Move main table to the beginning of the page.
var $main = $('body>div:eq(-1)');
$main.children('table:eq(-1)').detach().prependTo($main);
// Add current balance to Credit Cards.
$('p:contains("Tarjetas de Crédito")').closest('table').find('tr:gt(1):lt(-2)').each(function () {
var $tr = $(this);
var $total = $tr.find('td:eq(2) .pesetas');
var $disponible = $tr.find('td:last .pesetas');
numeral.language('es');
var saldo = numeral($total.html()).subtract(numeral($disponible.html()));
$disponible.append('<span style="display:inline-block; width:80px; color:DarkRed;">' + saldo.format('0,0.00') + '</span>');
});
})(jQuery);
| /* configure jshint globals */
/* globals numeral */
(function ($) {
'use strict';
// Set langauge for Numeral library.
numeral.language('es');
var $center = $('center');
var first_table = $('center').prev().detach();
$center.after(first_table);
var dinero_ya = $('.containerDineroYa').detach();
$center.append(dinero_ya);
$center.find('>div:eq(0)>br').remove();
$center.find('table table:eq(5) tr:gt(1):lt(-2)').each(function () {
var $tr = $(this);
var $total = $tr.find('td:eq(2) .pesetas');
var $disponible = $tr.find('td:last .pesetas');
numeral.language('es');
var saldo = numeral($total.html()).subtract(numeral($disponible.html()));
$disponible.append(' (' + saldo.format('0,0.00') + ')');
});
})(jQuery);
|
Allow Assessment assignee to edit own comments
That is, edit own comments immediately without refreshing the page.
Before the fix this wasn't possible because local permissions info
has not been updated on comment creation. | /*!
Copyright (C) 2016 Google Inc.
Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
*/
(function (can, $, GGRC) {
'use strict';
can.Control('GGRC.Controllers.Comments', {
}, {
_create_relationship: function (source, destination) {
if (!destination) {
return $.Deferred().resolve();
}
return new CMS.Models.Relationship({
source: source.stub(),
destination: destination,
context: source.context
}).save();
},
'{CMS.Models.Comment} created': function (model, ev, instance) {
var parentDfd;
var permissionRefresh;
var source;
if (!(instance instanceof CMS.Models.Comment)) {
return;
}
source = instance._source_mapping || GGRC.page_instance();
parentDfd = this._create_relationship(source, instance);
permissionRefresh = Permission.refresh();
instance.delay_resolving_save_until(
$.when(parentDfd, permissionRefresh));
}
});
$(function () {
$(document.body).ggrc_controllers_comments();
});
})(this.can, this.can.$, this.GGRC);
| /*!
Copyright (C) 2016 Google Inc.
Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
*/
(function (can, $, GGRC) {
'use strict';
can.Control('GGRC.Controllers.Comments', {
}, {
_create_relationship: function (source, destination) {
if (!destination) {
return $.Deferred().resolve();
}
return new CMS.Models.Relationship({
source: source.stub(),
destination: destination,
context: source.context
}).save();
},
'{CMS.Models.Comment} created': function (model, ev, instance) {
var parentDfd;
var source;
if (!(instance instanceof CMS.Models.Comment)) {
return;
}
source = instance._source_mapping || GGRC.page_instance();
parentDfd = this._create_relationship(source, instance);
instance.delay_resolving_save_until($.when(parentDfd));
}
});
$(function () {
$(document.body).ggrc_controllers_comments();
});
})(this.can, this.can.$, this.GGRC);
|
Revert "add support for addon icon (requires FontAwesome)"
This reverts commit 5db7b0a5550757c653de869516c308ff10452b74. | import Em from 'ember';
import FormGroupComponent from './group';
import ControlMixin from 'ember-idx-forms/mixins/control';
/*
Form Input
Syntax:
{{em-input property="property name"}}
*/
export default FormGroupComponent.extend({
controlView: Em.TextField.extend(ControlMixin, {
attributeBindings: ['placeholder', 'required', 'autofocus', 'disabled'],
placeholder: Em.computed.alias('parentView.placeholder'),
required: Em.computed.alias('parentView.required'),
autofocus: Em.computed.alias('parentView.autofocus'),
disabled: Em.computed.alias('parentView.disabled'),
type: Em.computed.alias('parentView.type'),
model: Em.computed.alias('parentView.model'),
propertyName: Em.computed.alias('parentView.propertyName')
}),
property: void 0,
label: void 0,
placeholder: void 0,
required: void 0,
autofocus: void 0,
disabled: void 0,
controlWrapper: Em.computed('form.form_layout', function() {
if (this.get('form.form_layout') === 'horizontal') {
return 'col-sm-10';
}
return null;
})
}); | import Em from 'ember';
import FormGroupComponent from './group';
import ControlMixin from 'ember-idx-forms/mixins/control';
/*
Form Input
Syntax:
{{em-input property="property name"}}
*/
export default FormGroupComponent.extend({
controlView: Em.TextField.extend(ControlMixin, {
attributeBindings: ['placeholder', 'required', 'autofocus', 'disabled'],
placeholder: Em.computed.alias('parentView.placeholder'),
required: Em.computed.alias('parentView.required'),
autofocus: Em.computed.alias('parentView.autofocus'),
disabled: Em.computed.alias('parentView.disabled'),
type: Em.computed.alias('parentView.type'),
model: Em.computed.alias('parentView.model'),
propertyName: Em.computed.alias('parentView.propertyName')
}),
addonIcon: false,
property: void 0,
label: void 0,
placeholder: void 0,
required: void 0,
autofocus: void 0,
disabled: void 0,
controlWrapper: Em.computed('form.form_layout', function() {
if (this.get('form.form_layout') === 'horizontal') {
return 'col-sm-10';
}
return null;
})
});
|
Upgrade dependency python-slugify to ==1.2.2 | import os
from setuptools import setup
from withtool import __version__
def read(fname):
path = os.path.join(os.path.dirname(__file__), fname)
with open(path, encoding='utf-8') as f:
return f.read()
setup(
name='with',
version=__version__,
description='A shell context manager',
long_description=read('README.rst'),
author='Renan Ivo',
author_email='renanivom@gmail.com',
url='https://github.com/renanivo/with',
keywords='context manager shell command line repl',
scripts=['bin/with'],
install_requires=[
'appdirs==1.4.3',
'docopt==0.6.2',
'prompt-toolkit==1.0',
'python-slugify==1.2.2',
],
packages=['withtool'],
classifiers=[
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
| import os
from setuptools import setup
from withtool import __version__
def read(fname):
path = os.path.join(os.path.dirname(__file__), fname)
with open(path, encoding='utf-8') as f:
return f.read()
setup(
name='with',
version=__version__,
description='A shell context manager',
long_description=read('README.rst'),
author='Renan Ivo',
author_email='renanivom@gmail.com',
url='https://github.com/renanivo/with',
keywords='context manager shell command line repl',
scripts=['bin/with'],
install_requires=[
'appdirs==1.4.3',
'docopt==0.6.2',
'prompt-toolkit==1.0',
'python-slugify==1.2.1',
],
packages=['withtool'],
classifiers=[
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
|
Add package org.gbif.ws.server.advice to scan | package org.gbif.registry;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.solr.SolrHealthContributorAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@SpringBootApplication(
scanBasePackages = {
"org.gbif.ws.server.interceptor",
"org.gbif.ws.server.aspect",
"org.gbif.ws.server.filter",
"org.gbif.ws.server.advice",
"org.gbif.ws.security",
"org.gbif.registry"},
exclude = {
SolrAutoConfiguration.class,
SolrHealthContributorAutoConfiguration.class
})
@MapperScan("org.gbif.registry.persistence.mapper")
@EnableConfigurationProperties
public class RegistryWsApplication {
public static void main(String[] args) {
SpringApplication.run(RegistryWsApplication.class, args);
}
}
| package org.gbif.registry;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.solr.SolrHealthContributorAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@SpringBootApplication(
scanBasePackages = {
"org.gbif.ws.server.interceptor",
"org.gbif.ws.server.aspect",
"org.gbif.ws.server.filter",
"org.gbif.ws.security",
"org.gbif.registry"},
exclude = {
SolrAutoConfiguration.class,
SolrHealthContributorAutoConfiguration.class
})
@MapperScan("org.gbif.registry.persistence.mapper")
@EnableConfigurationProperties
public class RegistryWsApplication {
public static void main(String[] args) {
SpringApplication.run(RegistryWsApplication.class, args);
}
}
|
Add shared fixtures for Mod and Game | """Global test configuration"""
import os
from pathlib import Path
import betamax
import pytest
from mccurse import addon, curse
# Ensure cassete dir
CASSETE_DIR = 'tests/cassetes/'
if not os.path.exists(CASSETE_DIR):
os.makedirs(CASSETE_DIR)
record_mode = 'none' if os.environ.get('TRAVIS_BUILD') else 'once'
with betamax.Betamax.configure() as config:
config.cassette_library_dir = CASSETE_DIR
config.default_cassette_options.update({
'record_mode': record_mode,
'preserve_exact_body_bytes': True,
})
# Shared fixtures
@pytest.fixture
def file_database(tmpdir) -> curse.Database:
"""Database potentially located in temp dir."""
return curse.Database('test', Path(str(tmpdir)))
@pytest.fixture
def tinkers_construct() -> addon.Mod:
"""Tinkers Construct project data"""
data = {
'name': 'Tinkers Construct',
'id': 74072,
'summary': 'Modify all the things, then do it again!',
}
return addon.Mod(**data)
@pytest.fixture
def minecraft() -> curse.Game:
"""Minecraft version for testing."""
data = {
'name': 'Minecraft',
'id': 432,
'version': '1.10.2',
}
return curse.Game(**data)
| """Global test configuration"""
import os
from pathlib import Path
import betamax
import pytest
from mccurse import curse
# Ensure cassete dir
CASSETE_DIR = 'tests/cassetes/'
if not os.path.exists(CASSETE_DIR):
os.makedirs(CASSETE_DIR)
record_mode = 'none' if os.environ.get('TRAVIS_BUILD') else 'once'
with betamax.Betamax.configure() as config:
config.cassette_library_dir = CASSETE_DIR
config.default_cassette_options.update({
'record_mode': record_mode,
'preserve_exact_body_bytes': True,
})
# Shared fixtures
@pytest.fixture
def file_database(tmpdir) -> curse.Database:
"""Database potentially located in temp dir."""
return curse.Database('test', Path(str(tmpdir)))
|
Load wsgi apps after reading the configuration. | # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import os
import sys
import traceback
from gunicorn import util
from gunicorn.app.base import Application
class WSGIApplication(Application):
def init(self, parser, opts, args):
if len(args) != 1:
parser.error("No application module specified.")
self.cfg.set("default_proc_name", args[0])
self.app_uri = args[0]
sys.path.insert(0, os.getcwd())
def load(self):
try:
return util.import_app(self.app_uri)
except:
print "Failed to import application: %s" % self.app_uri
traceback.print_exc()
sys.exit(1)
| # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import os
import sys
import traceback
from gunicorn import util
from gunicorn.app.base import Application
class WSGIApplication(Application):
def init(self, parser, opts, args):
if len(args) != 1:
parser.error("No application module specified.")
self.cfg.set("default_proc_name", args[0])
self.app_uri = args[0]
sys.path.insert(0, os.getcwd())
try:
self.load()
except:
print "Failed to import application: %s" % self.app_uri
traceback.print_exc()
sys.exit(1)
def load(self):
return util.import_app(self.app_uri) |
Add S3 command for performing backup data | from datetime import datetime
from fabric.api import (
cd,
env,
put,
run,
sudo,
task
)
PRODUCTION_IP = '54.154.235.243'
PROJECT_DIRECTORY = '/home/ubuntu/ztm/'
BACKUP_DIRECTORY = '/home/ubuntu/backup/'
COMPOSE_FILE = 'compose-production.yml'
@task
def production():
env.run = sudo
env.hosts = [
'ubuntu@' + PRODUCTION_IP + ':22',
]
def create_project_directory():
run('mkdir -p ' + PROJECT_DIRECTORY)
def update_compose_file():
put('./' + COMPOSE_FILE, PROJECT_DIRECTORY)
@task
def do_backup():
backup_time = datetime.now().strftime('%Y-%m-%d_%H%M')
with cd(BACKUP_DIRECTORY):
command = 'tar -cjvf ztm-' + backup_time + \
'.tar.bz2 ' + PROJECT_DIRECTORY
env.run(command)
command = 's3cmd sync ' + BACKUP_DIRECTORY + ' ' \
's3://zendesk-tickets-machine'
run(command)
@task
def deploy():
create_project_directory()
update_compose_file()
with cd(PROJECT_DIRECTORY):
env.run('docker-compose -f ' + COMPOSE_FILE + ' pull')
env.run('docker-compose -f ' + COMPOSE_FILE + ' up -d')
| from fabric.api import (
cd,
env,
put,
run,
sudo,
task
)
PRODUCTION_IP = '54.154.235.243'
PROJECT_DIRECTORY = '/home/ubuntu/ztm/'
COMPOSE_FILE = 'compose-production.yml'
@task
def production():
env.run = sudo
env.hosts = [
'ubuntu@' + PRODUCTION_IP + ':22',
]
def create_project_directory():
run('mkdir -p ' + PROJECT_DIRECTORY)
def update_compose_file():
put('./' + COMPOSE_FILE, PROJECT_DIRECTORY)
@task
def deploy():
create_project_directory()
update_compose_file()
with cd(PROJECT_DIRECTORY):
env.run('docker-compose -f ' + COMPOSE_FILE + ' pull')
env.run('docker-compose -f ' + COMPOSE_FILE + ' up -d')
|
Add early returns for Item API handler | <?php
header('Content-type:application/json');
// Object
require_once('./object/item.php');
// Service
// Database
require_once('./json/item.php');
// Initialize response.
$status = 500;
$body = [];
$header = '';
// Method router.
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET':
get();
break;
default:
$status = 405;
$header .= 'Allow: GET';
return;
}
// Get router.
function get () {
switch ( count($_GET) ) {
case 0:
getList();
break;
case 1:
getItem();
break;
default:
$status = 400;
return;
}
}
// Get item.
function getItem () {
// Retrieve item.
$item = ItemJson::get($_GET['id']);
// if not found.
if (gettype($item) != 'array') {
$status = 404;
return;
}
$status = 200;
$body = $item;
return;
}
// Get item list.
function getList () {
// Retrieve item list.
$list = ItemJson::list();
// If not found.
if (gettype($item) != 'array') {
$status = 503;
return;
}
$status = 200;
$body = $list;
return;
}
HTTP::respond($status, $body, $header);
?>
| <?php
header('Content-type:application/json');
// Object
require_once('./object/item.php');
// Service
// Database
require_once('./json/item.php');
// Initialize response.
$status = 500;
$body = [];
$header = '';
// Method router.
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET':
get();
break;
default:
$status = 405;
$header .= 'Allow: GET';
}
// Get router.
function get () {
switch ( count($_GET) ) {
case 0:
getList();
break;
case 1:
getItem();
break;
default:
$status = 400;
}
}
// Get item.
function getItem () {
// Retrieve item.
$item = ItemJson::get($_GET['id']);
// if not found.
if (gettype($item) != 'array') {
$status = 404;
return;
}
$status = 200;
$body = $item;
return;
}
// Get item list.
function getList () {
// Retrieve item list.
$list = ItemJson::list();
// If not found.
if (gettype($item) != 'array') {
$status = 503;
return;
}
$status = 200;
$body = $list;
return;
}
HTTP::respond($status, $body, $header);
?>
|
Write name of last page in txt file | import os
def make_chapter_files():
os.chdir('../static/images')
for _, dirs, files in os.walk(os.getcwd()):
dirs = [d for d in dirs if not d[0] == '.']
files = [f for f in files if not f[0] == '.']
for directory in dirs:
file_path = get_filepath(directory)
make_file(file_path)
def write_chapter_files():
root, chapters, files = next(os.walk(os.getcwd()))
path_list = [os.path.join(root, chapter) for chapter in chapters]
chapter_list = [name for name in files if not name[0] == '.']
# match path to txt file
zipped = zip(path_list, chapter_list)
for path, filename in zipped:
_, _, files = next(os.walk(path))
if (len(files) > 0):
write_last_page(files[-1], filename)
def get_filepath(directory):
filepath = '{}.txt'.format(directory)
return filepath
def make_file(filepath):
f = open(filepath, 'a')
f.close()
def write_last_page(page_w_ext, filename):
f = open(filename, 'w')
page, _ = page_w_ext.split('.')
f.write(page)
f.close()
if __name__ == '__main__':
make_chapter_files()
write_chapter_files()
| import os
def make_chapter_files():
os.chdir('../static/images')
for _, dirs, files in os.walk(os.getcwd()):
dirs = [d for d in dirs if not d[0] == '.']
files = [f for f in files if not f[0] == '.']
for directory in dirs:
file_path = get_filepath(directory)
make_file(file_path)
def write_chapter_files():
os.chdir('../static/images')
root, chapters, files = next(os.walk(os.getcwd()))
path_list = [os.path.join(root, chapter) for chapter in chapters]
chapter_list = [name for name in files if not name[0] == '.']
print path_list
print chapter_list
def get_filepath(directory):
filepath = '{}.txt'.format(directory)
return filepath
def make_file(filepath):
f = open(filepath, 'a')
f.close()
if __name__ == '__main__':
# make_chapter_files()
write_chapter_files()
|
Allow for case where user has no profile. | Meteor.startup(function() {
Tracker.autorun(function() {
if (Meteor.userId() && Meteor.user()) {
Rollbar.configure({
payload: {
person: {
id: Meteor.userId(),
username: Meteor.user().profile && Meteor.user().profile.name
}
}
});
} else {
Rollbar.configure({
payload: {
person: null
}
});
}
});
});
throwError = function() {
Meteor.apply('throwError', arguments, function(err, result) {
if (err) {
console.log("Could not log event to rollbar");
console.log(err);
}
});
};
handleError = function(error) {
Meteor.apply('handleError', arguments, function(err, result) {
console.log("Could not log error to rollbar");
console.log(err);
});
}; | Meteor.startup(function() {
Tracker.autorun(function() {
if (Meteor.userId() && Meteor.user()) {
Rollbar.configure({
payload: {
person: {
id: Meteor.userId(),
username: Meteor.user().profile.name
}
}
});
} else {
Rollbar.configure({
payload: {
person: null
}
});
}
});
});
throwError = function() {
Meteor.apply('throwError', arguments, function(err, result) {
if (err) {
console.log("Could not log event to rollbar");
console.log(err);
}
});
};
handleError = function(error) {
Meteor.apply('handleError', arguments, function(err, result) {
console.log("Could not log error to rollbar");
console.log(err);
});
}; |
Fix lint line length warnings (blocking manage checks) | # -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
# pylint: disable=invalid-name
"""
csv2ofx.mappings.stripe
~~~~~~~~~~~~~~~~~~~~~~~~
Provides a mapping for transactions obtained via Stripe card processing
Note that Stripe provides a Default set of columns or you can download
All columns. (as well as custom). The Default set does not include card
information, so provides no appropriate value for the PAYEE field for
an anonymous transaction (missing a customer).
It's suggested the All Columns format be used if not all transactions
identify a customer. This mapping sets PAYEE to Customer Name if it
exists, otherwise Card Name (if provided)
"""
from __future__ import (
absolute_import, division, print_function, unicode_literals)
from operator import itemgetter
mapping = {
'has_header': True,
'account': 'Stripe',
'id': itemgetter('id'),
'date': itemgetter('created'),
'amount': itemgetter('amount'),
'currency': itemgetter('currency'),
'payee': lambda tr: tr.get('customer_description')
if len(tr.get('customer_description')) > 0
else tr.get('card_name', ""),
'desc': itemgetter("description")
}
| # -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
# pylint: disable=invalid-name
"""
csv2ofx.mappings.stripe
~~~~~~~~~~~~~~~~~~~~~~~~
Provides a mapping for transactions obtained via Stripe card processing
Note that Stripe provides a Default set of columns or you can download All columns. (as well as custom).
The Default set does not include card information, so provides no appropriate value for the
PAYEE field for an anonymous transaction (missing a customer).
It's suggested the All Columns format be used if not all transactions identify a customer.
This mapping sets PAYEE to Customer Name if it exists, otherwise Card Name (if provided)
"""
from __future__ import (
absolute_import, division, print_function, unicode_literals)
from operator import itemgetter
mapping = {
'has_header': True,
'account': 'Stripe',
'id': itemgetter('id'),
'date': itemgetter('created'),
'amount': itemgetter('amount'),
'currency': itemgetter('currency'),
'payee': lambda tr: tr.get('customer_description') if len(tr.get('customer_description')) > 0 else tr.get('card_name', ""),
'desc': itemgetter("description")
}
|
Make RedisTemplate final and validate not null construction | package com.marcosbarbero.zuul.filters.pre.ratelimit.config.redis;
import com.marcosbarbero.zuul.filters.pre.ratelimit.config.Policy;
import com.marcosbarbero.zuul.filters.pre.ratelimit.config.Rate;
import com.marcosbarbero.zuul.filters.pre.ratelimit.config.RateLimiter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Assert;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* @author Marcos Barbero
*/
public class RedisRateLimiter implements RateLimiter {
private final RedisTemplate template;
public RedisRateLimiter(final RedisTemplate template) {
Assert.notNull(template, "RedisTemplate cannot be null");
this.template = template;
}
@Override
@SuppressWarnings("unchecked")
public Rate consume(final Policy policy, final String key) {
final Long limit = policy.getLimit();
final Long refreshInterval = policy.getRefreshInterval();
final Long current = this.template.boundValueOps(key).increment(1L);
Long expire = this.template.getExpire(key);
if (expire == null || expire == -1) {
this.template.expire(key, refreshInterval, SECONDS);
expire = refreshInterval;
}
return new Rate(limit, Math.max(-1, limit - current), SECONDS.toMillis(expire));
}
}
| package com.marcosbarbero.zuul.filters.pre.ratelimit.config.redis;
import com.marcosbarbero.zuul.filters.pre.ratelimit.config.Policy;
import com.marcosbarbero.zuul.filters.pre.ratelimit.config.Rate;
import com.marcosbarbero.zuul.filters.pre.ratelimit.config.RateLimiter;
import org.springframework.data.redis.core.RedisTemplate;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* @author Marcos Barbero
*/
public class RedisRateLimiter implements RateLimiter {
private RedisTemplate template;
public RedisRateLimiter(RedisTemplate template) {
this.template = template;
}
@Override
@SuppressWarnings("unchecked")
public Rate consume(final Policy policy, final String key) {
final Long limit = policy.getLimit();
final Long refreshInterval = policy.getRefreshInterval();
final Long current = this.template.boundValueOps(key).increment(1L);
Long expire = this.template.getExpire(key);
if (expire == null || expire == -1) {
this.template.expire(key, refreshInterval, SECONDS);
expire = refreshInterval;
}
return new Rate(limit, Math.max(-1, limit - current), SECONDS.toMillis(expire));
}
}
|
Add necessary member variables for iRunCommand | <?php
namespace Lauft\Behat\BashExtension\Context;
/**
* BashContext context for Behat BDD tool.
* Provides bash base step definitions.
*/
class BashContext extends RawBashContext
{
/** @var string */
protected $rootDirectory;
/** @var string */
protected $workingDir;
/** @var Process */
protected $process;
public function __construct($rootDirectory = DIRECTORY_SEPARATOR)
{
$this->rootDirectory = $rootDirectory;
$this->process = new Process(null);
}
/**
/**
* @When /^I run "([^"]*)"(?: with "([^"]*)")?$/
*
* @param string $command
* @param string $arguments
*/
public function iRunCommand($command, $arguments = '')
{
$arguments = strtr($arguments, array('\'' => '"'));
$this->process->setWorkingDirectory($this->workingDir);
$this->process->setCommandLine($command.' '.$arguments);
$this->process->start();
$this->process->wait();
}
} | <?php
namespace Lauft\Behat\BashExtension\Context;
/**
* BashContext context for Behat BDD tool.
* Provides bash base step definitions.
*/
class BashContext extends RawBashContext
{
/**
* @When /^I run "([^"]*)"(?: with "([^"]*)")?$/
*
* @param string $command
* @param string $arguments
*/
public function iRunCommand($command, $arguments = '')
{
$arguments = strtr($arguments, array('\'' => '"'));
$this->process->setWorkingDirectory($this->workingDir);
$this->process->setCommandLine($command.' '.$arguments);
$this->process->start();
$this->process->wait();
}
} |
layout: Align option icon in Lightbox screen
Icon was not properly aligned due to overlay of unreadCount.
As there is no need of unreadCount here, Instead of using NavButton,
use Icon component directly.
Fixes #3003. | /* @flow */
import React, { PureComponent } from 'react';
import { Text, StyleSheet, View } from 'react-native';
import type { Style } from '../types';
import Icon from '../common/Icons';
const styles = StyleSheet.create({
wrapper: {
height: 44,
flexDirection: 'row',
justifyContent: 'space-between',
paddingLeft: 16,
paddingRight: 8,
flex: 1,
},
text: {
color: 'white',
fontSize: 14,
alignSelf: 'center',
},
icon: {
fontSize: 28,
alignSelf: 'center',
},
});
type Props = {
style?: Style,
displayMessage: string,
onOptionsPress: () => void,
};
export default class LightboxFooter extends PureComponent<Props> {
props: Props;
render() {
const { displayMessage, onOptionsPress, style } = this.props;
return (
<View style={[styles.wrapper, style]}>
<Text style={styles.text}>{displayMessage}</Text>
<Icon style={styles.icon} color="white" name="more-vertical" onPress={onOptionsPress} />
</View>
);
}
}
| /* @flow */
import React, { PureComponent } from 'react';
import { Text, StyleSheet, View } from 'react-native';
import type { Style } from '../types';
import NavButton from '../nav/NavButton';
const styles = StyleSheet.create({
wrapper: {
height: 44,
flexDirection: 'row',
justifyContent: 'space-between',
paddingLeft: 16,
paddingRight: 8,
flex: 1,
},
text: {
color: 'white',
fontSize: 14,
alignSelf: 'center',
},
icon: {
fontSize: 28,
},
});
type Props = {
style?: Style,
displayMessage: string,
onOptionsPress: () => void,
};
export default class LightboxFooter extends PureComponent<Props> {
props: Props;
render() {
const { displayMessage, onOptionsPress, style } = this.props;
return (
<View style={[styles.wrapper, style]}>
<Text style={styles.text}>{displayMessage}</Text>
<NavButton
name="more-vertical"
color="white"
style={styles.icon}
onPress={onOptionsPress}
/>
</View>
);
}
}
|
Remove had a bug due to bad reference. | 'use strict';
const util = require('util');
const CommandUtil = require('../src/command_util').CommandUtil;
const l10nFile = __dirname + '/../l10n/commands/remove.yml';
const l10n = require('../src/l10n')(l10nFile);
const _ = require('../src/helpers');
exports.command = (rooms, items, players, npcs, Commands) => {
return (args, player, isDead) => {
const target = _.firstWord(args);
if (target === 'all') { return Commands.player_commands.drop('all', player); }
const thing = CommandUtil.findItemInEquipment(items, target, player, true);
if (thing.isEquipped()) {
return remove(thing);
} else {
return player.warn(`${thing.getShortDesc()} is not equipped.`);
}
function remove(item) {
if (!item && !isDead) {
return player.sayL10n(l10n, 'ITEM_NOT_FOUND');
}
util.log(player.getName() + ' removing ' + item.getShortDesc('en'));
const location = player.unequip(item, items, players);
if (!location) { return player.say(`You are unable to unequip ${item.getShortDesc()}.`); }
if (isDead) { return; }
const room = rooms.getAt(player.getLocation());
item.emit('remove', location, room, player, players);
}
};
};
| 'use strict';
const util = require('util');
const CommandUtil = require('../src/command_util').CommandUtil;
const l10nFile = __dirname + '/../l10n/commands/remove.yml';
const l10n = require('../src/l10n')(l10nFile);
const _ = require('../src/helpers');
exports.command = (rooms, items, players, npcs, Commands) => {
return (args, player, isDead) => {
const target = _.firstWord(args);
if (target === 'all') { return Commands.player_commands.drop('all', player); }
const thing = CommandUtil.findItemInEquipment(items, target, player, true);
if (thing.isEquipped()) {
return remove(thing);
} else {
return player.warn(`${thing.getShortDesc()} is not equipped.`);
}
function remove(item) {
if (!item && !isDead) {
return player.sayL10n(l10n, 'ITEM_NOT_FOUND');
}
util.log(player.getName() + ' removing ' + item.getShortDesc('en'));
const success = player.unequip(item, items, players);
if (!success) { return player.say(`You are unable to unequip ${item.getShortDesc()}.`); }
if (isDead) { return; }
const room = rooms.getAt(player.getLocation());
item.emit('remove', location, room, player, players);
}
};
};
|
Fix TestSyntheticCapping for Python 3.
In Python 3, whitespace inconsistences are errors. This synthetic
provider had mixed tabs and spaces, as well as inconsistent
indentation widths. This led to the file not being imported,
and naturally the test failing. No functional change here, just
whitespace.
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@258751 91177308-0d34-0410-b5e6-96231b3b80d8 | import lldb
class fooSynthProvider:
def __init__(self, valobj, dict):
self.valobj = valobj;
self.int_type = valobj.GetType().GetBasicType(lldb.eBasicTypeInt)
def num_children(self):
return 3;
def get_child_at_index(self, index):
if index == 0:
child = self.valobj.GetChildMemberWithName('a');
if index == 1:
child = self.valobj.CreateChildAtOffset ('fake_a', 1, self.int_type);
if index == 2:
child = self.valobj.GetChildMemberWithName('r');
return child;
def get_child_index(self, name):
if name == 'a':
return 0;
if name == 'fake_a':
return 1;
return 2;
| import lldb
class fooSynthProvider:
def __init__(self, valobj, dict):
self.valobj = valobj;
self.int_type = valobj.GetType().GetBasicType(lldb.eBasicTypeInt)
def num_children(self):
return 3;
def get_child_at_index(self, index):
if index == 0:
child = self.valobj.GetChildMemberWithName('a');
if index == 1:
child = self.valobj.CreateChildAtOffset ('fake_a', 1, self.int_type);
if index == 2:
child = self.valobj.GetChildMemberWithName('r');
return child;
def get_child_index(self, name):
if name == 'a':
return 0;
if name == 'fake_a':
return 1;
return 2;
|
Fix sendmail include path and disable verbose logging | <?php
/**
* A wrapper function for PHPMailer to easily send emails
*/
function sendMail($toAddr, $subject, $body) {
set_include_path(dirname(dirname(__FILE__)));
require_once('config/config.php');
require_once('lib/class.phpmailer.php');
require_once('lib/class.smtp.php');
$mail = new PHPMailer;
// $mail->SMTPDebug = 3; // Verbose debugging output
$mail->isSMTP();
$mail->Host = Config::SMTP_HOST;
$mail->SMTPAuth = true;
$mail->Username = Config::SMTP_USERNAME;
$mail->Password = Config::SMTP_PASSWORD;
$mail->SMTPSecure = Config::SMTP_SECURE;
$mail->Port = Config::SMTP_PORT;
$mail->From = Config::MAIL_FROM_ADDR;
$mail->FromName = Config::MAIL_FROM_NAME;
$mail->addAddress($toAddr);
$mail->Subject = $subject;
$mail->Body = $body;
if(!$mail->send()) {
return $mail->ErrorInfo;
} else {
return true;
}
}
| <?php
/**
* A wrapper function for PHPMailer to easily send emails
*/
function sendMail($toAddr, $subject, $body) {
require('../config/config.php');
require('../lib/class.phpmailer.php');
require('../lib/class.smtp.php');
$mail = new PHPMailer;
if (Config::DEBUG) {
$mail->SMTPDebug = 3; // Verbose debugging output
}
$mail->isSMTP();
$mail->Host = Config::SMTP_HOST;
$mail->SMTPAuth = true;
$mail->Username = Config::SMTP_USERNAME;
$mail->Password = Config::SMTP_PASSWORD;
$mail->SMTPSecure = Config::SMTP_SECURE;
$mail->Port = Config::SMTP_PORT;
$mail->From = Config::MAIL_FROM_ADDR;
$mail->FromName = Config::MAIL_FROM_NAME;
$mail->addAddress($toAddr);
$mail->Subject = $subject;
$mail->Body = $body;
if(!$mail->send()) {
return $mail->ErrorInfo;
} else {
return true;
}
}
|
Fix test for page renderadapter meta trimming | <?php
class CM_RenderAdapter_PageTest extends CMTest_TestCase {
public function testFetchDescriptionKeywordsTitleTrimming() {
$render = new CM_Frontend_Render();
$page = $this->getMockBuilder('CM_Page_Abstract')->getMockForAbstractClass();
/** @var CM_Page_Abstract $page */
$renderAdapter = $this->getMockBuilder('CM_RenderAdapter_Page')
->setMethods(array('_fetchTemplate'))
->setConstructorArgs(array($render, $page))
->getMock();
$renderAdapter->expects($this->any())->method('_fetchTemplate')->will($this->returnCallback(function ($templateName) {
return "\n \t test-" . $templateName . "\n";
}));
/** @var CM_RenderAdapter_Page $renderAdapter */
$this->assertSame('test-meta-description', $renderAdapter->fetchDescription());
$this->assertSame('test-meta-keywords', $renderAdapter->fetchKeywords());
$this->assertSame('test-title', $renderAdapter->fetchTitle());
}
}
| <?php
class CM_RenderAdapter_PageTest extends CMTest_TestCase {
public function testFetchDescriptionKeywordsTitle() {
$render = new CM_Frontend_Render();
$page = $this->getMockBuilder('CM_Page_Abstract')->getMockForAbstractClass();
/** @var CM_Page_Abstract $page */
$renderAdapter = $this->getMockBuilder('CM_RenderAdapter_Page')
->setMethods(array('_fetchMetaTemplate'))
->setConstructorArgs(array($render, $page))
->getMock();
$renderAdapter->expects($this->any())->method('_fetchMetaTemplate')->will($this->returnCallback(function ($tplName) {
return 'test-' . $tplName . '.tpl';
}));
/** @var CM_RenderAdapter_Page $renderAdapter */
$this->assertSame('test-meta-description.tpl', $renderAdapter->fetchDescription());
$this->assertSame('test-meta-keywords.tpl', $renderAdapter->fetchKeywords());
$this->assertSame('test-title.tpl', $renderAdapter->fetchTitle());
}
}
|
Split out the css rebuilding into its own fab method. | set(
fab_hosts = ['startthedark.com'],
fab_user = 'startthedark',
)
def unlink_nginx():
'Un-link nginx rules for startthedark.'
sudo('rm -f /etc/nginx/sites-enabled/startthedark.com')
sudo('/etc/init.d/nginx reload')
def link_nginx():
'Link nginx rules for startthedark'
sudo('ln -s /etc/nginx/sites-available/startthedark.com /etc/nginx/sites-enabled/startthedark.com')
sudo('/etc/init.d/nginx reload')
def rebuild_prod_css():
local('bash make_prod_css.sh')
local('git commit -a -m "Rebuilt Prod CSS For Commit"')
local('git push origin master')
def deploy():
'Deploy startthedark.'
run('cd /var/www/startthedark.com/startthedark; git pull;')
run('cd /var/www/startthedark.com/startthedark; /usr/bin/python manage.py syncdb')
sudo('/etc/init.d/apache2 reload')
| set(
fab_hosts = ['startthedark.com'],
fab_user = 'startthedark',
)
def unlink_nginx():
'Un-link nginx rules for startthedark.'
sudo('rm -f /etc/nginx/sites-enabled/startthedark.com')
sudo('/etc/init.d/nginx reload')
def link_nginx():
'Link nginx rules for startthedark'
sudo('ln -s /etc/nginx/sites-available/startthedark.com /etc/nginx/sites-enabled/startthedark.com')
sudo('/etc/init.d/nginx reload')
def deploy():
'Deploy startthedark.'
local('bash make_prod_css.sh')
set(fab_fail = 'ignore')
local('git commit -a -m "Rebuilt Prod CSS For Commit"')
local('git push origin master')
set(fab_fail = 'abort')
run('cd /var/www/startthedark.com/startthedark; git pull;')
run('cd /var/www/startthedark.com/startthedark; /usr/bin/python manage.py syncdb')
sudo('/etc/init.d/apache2 reload')
|
Localization: Fix sk translation of rangelength method
Closes #1001 | /*
* Translated default messages for the jQuery validation plugin.
* Locale: SK (Slovak; slovenčina, slovenský jazyk)
*/
$.extend($.validator.messages, {
required: "Povinné zadať.",
maxlength: $.validator.format("Maximálne {0} znakov."),
minlength: $.validator.format("Minimálne {0} znakov."),
rangelength: $.validator.format("Minimálne {0} a Maximálne {1} znakov."),
email: "E-mailová adresa musí byť platná.",
url: "URL musí byť platný.",
date: "Musí byť dátum.",
number: "Musí byť číslo.",
digits: "Môže obsahovať iba číslice.",
equalTo: "Dva hodnoty sa musia rovnať.",
range: $.validator.format("Musí byť medzi {0} a {1}."),
max: $.validator.format("Nemôže byť viac ako{0}."),
min: $.validator.format("Nemôže byť menej ako{0}."),
creditcard: "Číslo platobnej karty musí byť platné."
});
| /*
* Translated default messages for the jQuery validation plugin.
* Locale: SK (Slovak; slovenčina, slovenský jazyk)
*/
$.extend($.validator.messages, {
required: "Povinné zadať.",
maxlength: $.validator.format("Maximálne {0} znakov."),
minlength: $.validator.format("Minimálne {0} znakov."),
rangelength: $.validator.format("Minimálne {0} a Maximálne {0} znakov."),
email: "E-mailová adresa musí byť platná.",
url: "URL musí byť platný.",
date: "Musí byť dátum.",
number: "Musí byť číslo.",
digits: "Môže obsahovať iba číslice.",
equalTo: "Dva hodnoty sa musia rovnať.",
range: $.validator.format("Musí byť medzi {0} a {1}."),
max: $.validator.format("Nemôže byť viac ako{0}."),
min: $.validator.format("Nemôže byť menej ako{0}."),
creditcard: "Číslo platobnej karty musí byť platné."
});
|
Make it easier to load the initial page | #!/usr/bin/env python
# Sets up a basic site that can allow two browsers to connect to each
# other via WebRTC DataChannels, sending connection events via WebSockets.
from flask import Flask, send_from_directory
from flask_sockets import Sockets
import json
app = Flask(__name__)
sockets = Sockets(app)
channels = {}
@sockets.route('/channel/<name>')
def channel_socket(ws, name):
if name in channels:
channels[name].append(ws)
else:
channels[name] = [ws]
while not ws.closed:
message = ws.receive()
print "Got msg:", message
if message is None:
continue
for other_ws in channels[name]:
if ws is not other_ws:
other_ws.send(message)
channels[name].remove(ws)
for other_ws in channels[name]:
other_ws.send(json.dumps({"type": "client_disconnected", "msg": {}}))
@app.route('/static/<path:path>')
def send_static(path):
return app.send_from_directory('static', path)
@app.route('/')
def serve_site():
return app.send_static_file("index.html")
if __name__ == "__main__":
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
server = pywsgi.WSGIServer(('', 5000), app, handler_class=WebSocketHandler)
server.serve_forever()
| #!/usr/bin/env python
# Sets up a basic site that can allow two browsers to connect to each
# other via WebRTC DataChannels, sending connection events via WebSockets.
from flask import Flask, send_from_directory
from flask_sockets import Sockets
import json
app = Flask(__name__)
sockets = Sockets(app)
channels = {}
@sockets.route('/channel/<name>')
def channel_socket(ws, name):
if name in channels:
channels[name].append(ws)
else:
channels[name] = [ws]
while not ws.closed:
message = ws.receive()
print "Got msg:", message
if message is None:
continue
for other_ws in channels[name]:
if ws is not other_ws:
other_ws.send(message)
channels[name].remove(ws)
for other_ws in channels[name]:
other_ws.send(json.dumps({"type": "client_disconnected", "msg": {}}))
@app.route('/static/<path:path>')
def send_static(path):
return app.send_from_directory('static', path)
@app.route('/index.html')
def serve_site():
return app.send_static_file("index.html")
if __name__ == "__main__":
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
server = pywsgi.WSGIServer(('', 5000), app, handler_class=WebSocketHandler)
server.serve_forever()
|
Add debugging if run directly | from datetime import datetime
import io
import os
import legofy
from PIL import Image
from flask import Flask, render_template, request, redirect, send_file
BRICK_PATH = os.path.join(os.path.dirname(legofy.__file__), "assets", "bricks", "1x1.png")
BRICK_IMAGE = Image.open(BRICK_PATH)
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload():
uploaded = request.files['file']
if not uploaded:
return redirect('/')
try:
image = Image.open(uploaded)
except IOError:
return redirect('/')
new_size = legofy.get_new_size(image, BRICK_IMAGE)
image.thumbnail(new_size, Image.ANTIALIAS)
lego_image = legofy.make_lego_image(image, BRICK_IMAGE)
new_image = io.BytesIO()
lego_image.save(new_image, format='PNG')
new_image.seek(0)
response = send_file(new_image, mimetype='image/png')
response.headers['Last-Modified'] = datetime.now()
response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '-1'
return response
if __name__ == '__main__':
app.run(debug=True)
| from datetime import datetime
import io
import os
import legofy
from PIL import Image
from flask import Flask, render_template, request, redirect, send_file
BRICK_PATH = os.path.join(os.path.dirname(legofy.__file__), "assets", "bricks", "1x1.png")
BRICK_IMAGE = Image.open(BRICK_PATH)
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload():
uploaded = request.files['file']
if not uploaded:
return redirect('/')
try:
image = Image.open(uploaded)
except IOError:
return redirect('/')
new_size = legofy.get_new_size(image, BRICK_IMAGE)
image.thumbnail(new_size, Image.ANTIALIAS)
lego_image = legofy.make_lego_image(image, BRICK_IMAGE)
new_image = io.BytesIO()
lego_image.save(new_image, format='PNG')
new_image.seek(0)
response = send_file(new_image, mimetype='image/png')
response.headers['Last-Modified'] = datetime.now()
response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '-1'
return response
|
Change types to type as only one type | 'use strict';
var helpers = require('../helpers');
module.exports = {
'name': 'no-qualifying-elements',
'defaults': {
'allow-element-with-attribute': false,
'allow-element-with-class': false,
'allow-element-with-id': false
},
'detect': function (ast, parser) {
var result = [];
ast.traverseByType('simpleSelector', function (selectors) {
selectors.content.forEach(function (item, i) {
if (item.is('class') || item.is('attribute') || item.is('id')) {
var previous = selectors.content[i - 1] || false;
if (previous && previous.is('ident')) {
if (!parser.options['allow-element-with-' + item.type]) {
result = helpers.addUnique(result, {
'ruleId': parser.rule.name,
'line': item.start.line,
'column': item.start.column,
'message': 'Qualifying element not allowed for ' + item.type,
'severity': parser.severity
});
}
}
}
});
});
return result;
}
};
| 'use strict';
var helpers = require('../helpers');
module.exports = {
'name': 'no-qualifying-elements',
'defaults': {
'allow-element-with-attribute': false,
'allow-element-with-class': false,
'allow-element-with-id': false
},
'detect': function (ast, parser) {
var result = [];
ast.traverseByTypes(['simpleSelector'], function (selectors) {
selectors.content.forEach(function (item, i) {
if (item.is('class') || item.is('attribute') || item.is('id')) {
var previous = selectors.content[i - 1] || false;
if (previous && previous.is('ident')) {
if (!parser.options['allow-element-with-' + item.type]) {
result = helpers.addUnique(result, {
'ruleId': parser.rule.name,
'line': item.start.line,
'column': item.start.column,
'message': 'Qualifying element not allowed for ' + item.type,
'severity': parser.severity
});
}
}
}
});
});
return result;
}
};
|
Fix file type for post submissions | from custom.uth.utils import create_case, match_case, attach_images_to_case
from custom.uth.models import SonositeUpload, VscanUpload
from celery.task import task
import io
@task
def async_create_case(upload_id):
upload_doc = SonositeUpload.get(upload_id)
files = {}
for f in upload_doc._attachments.keys():
files[f] = io.BytesIO(upload_doc.fetch_attachment(f))
create_case(upload_doc.related_case_id, files)
# TODO delete doc if processing is successful
@task
def async_find_and_attach(upload_id):
upload_doc = VscanUpload.get(upload_id)
case = match_case(
upload_doc.scanner_serial,
upload_doc.scan_id,
upload_doc.date
)
attach_images_to_case(case, [])
# TODO delete doc if successful
| from custom.uth.utils import create_case, match_case, attach_images_to_case
from custom.uth.models import SonositeUpload, VscanUpload
from celery.task import task
@task
def async_create_case(upload_id):
upload_doc = SonositeUpload.get(upload_id)
files = {}
for f in upload_doc._attachments.keys():
files[f] = upload_doc.fetch_attachment(f)
create_case(upload_doc.related_case_id, files)
# TODO delete doc if processing is successful
@task
def async_find_and_attach(upload_id):
upload_doc = VscanUpload.get(upload_id)
case = match_case(
upload_doc.scanner_serial,
upload_doc.scan_id,
upload_doc.date
)
attach_images_to_case(case, [])
# TODO delete doc if successful
|
Add primary key while creating tables | 'use strict';
require('dotenv').config();
const Pg = require('pg');
const MEASUREMENTS_TABLE = process.env.MEASUREMENTS_TABLE;
const STATION_IDS_TABLE = process.env.STATION_IDS_TABLE;
const pg = new Pg.Client({
connectionString: process.env.DATABASE_URL,
ssl: true
});
pg.connect();
const measurementsTable = pg.query(`CREATE TABLE ${MEASUREMENTS_TABLE} (timestamp TIMESTAMP NOT NULL PRIMARY KEY, station_id VARCHAR(12) NOT NULL, is_occupied BOOL NOT NULL, distance INT NOT NULL)`)
.then(result => console.log(`${MEASUREMENTS_TABLE} created`))
.catch(error => console.log(error));
const stationIdsTable = pg.query(`CREATE TABLE ${STATION_IDS_TABLE}(station_id VARCHAR(12) NOT NULL)`)
.then(result => console.log(`${STATION_IDS_TABLE} created`))
.catch(error => console.log(error));
Promise.all([measurementsTable, stationIdsTable]).then(values => pg.end()); | 'use strict';
require('dotenv').config();
const Pg = require('pg');
const MEASUREMENTS_TABLE = process.env.MEASUREMENTS_TABLE;
const STATION_IDS_TABLE = process.env.STATION_IDS_TABLE;
const pg = new Pg.Client({
connectionString: process.env.DATABASE_URL,
ssl: true
});
pg.connect();
const measurementsTable = pg.query(`CREATE TABLE ${MEASUREMENTS_TABLE}(timestamp TIMESTAMP NOT NULL, station_id VARCHAR(12) NOT NULL, is_occupied BOOL NOT NULL, distance INT NOT NULL)`)
.then(result => console.log(`${MEASUREMENTS_TABLE} created`))
.catch(error => console.log(error));
const stationIdsTable = pg.query(`CREATE TABLE ${STATION_IDS_TABLE}(station_id VARCHAR(12) NOT NULL)`)
.then(result => console.log(`${STATION_IDS_TABLE} created`))
.catch(error => console.log(error));
Promise.all([measurementsTable, stationIdsTable]).then(values => pg.end()); |
Add 10 days only in the leap day case too. | from datetime import date, timedelta
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
def convert_to(self, calendar):
return calendar.from_date(self.date)
def __eq__(self, other):
return self.calendar == other.calendar and self.date == other.date
def __str__(self):
return "%s (%s)" % (self.date, self.calendar.__name__)
class Calendar(object):
def from_date(self, date):
return DateWithCalendar(self.__class__, date)
class ProlepticGregorianCalendar(Calendar):
def date(self, year, month, day):
d = date(year, month, day)
return self.from_date(d)
class JulianCalendar(Calendar):
@staticmethod
def is_julian_leap_year(y):
return (y % 4) == 0
def date(self, year, month, day):
if day == 29 and month == 2 and self.is_julian_leap_year(year):
d = date(year, month, 28)
else:
d = date(year, month, day)
d = d + timedelta(days=10)
return self.from_date(d)
| from datetime import date, timedelta
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
def convert_to(self, calendar):
return calendar.from_date(self.date)
def __eq__(self, other):
return self.calendar == other.calendar and self.date == other.date
def __str__(self):
return "%s (%s)" % (self.date, self.calendar.__name__)
class Calendar(object):
def from_date(self, date):
return DateWithCalendar(self.__class__, date)
class ProlepticGregorianCalendar(Calendar):
def date(self, year, month, day):
d = date(year, month, day)
return self.from_date(d)
class JulianCalendar(Calendar):
@staticmethod
def is_julian_leap_year(y):
return (y % 4) == 0
def date(self, year, month, day):
if day == 29 and month == 2 and self.is_julian_leap_year(year):
d = date(year, month, 28)
d = d + timedelta(days=11)
else:
d = date(year, month, day)
d = d + timedelta(days=10)
return self.from_date(d)
|
Fix extension example to work with nextChain() | /*
* Copyright (c) 2011 David Saff
* Copyright (c) 2011 Christian Gruber
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.junit.contrib.truth.extensiontest;
import org.junit.contrib.truth.FailureStrategy;
import org.junit.contrib.truth.subjects.Subject;
/**
* A simple example Subject to demonstrate extension.
*
* @author Christian Gruber (christianedwardgruber@gmail.com)
*/
public class MySubject extends Subject<MySubject, MyType> {
public MySubject(FailureStrategy failureStrategy, MyType subject) {
super(failureStrategy, subject);
}
public And<MySubject> matches(MyType object) {
if (getSubject().value != object.value) {
fail("matches", getSubject(), object);
}
return nextChain();
}
}
| /*
* Copyright (c) 2011 David Saff
* Copyright (c) 2011 Christian Gruber
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.junit.contrib.truth.extensiontest;
import org.junit.contrib.truth.FailureStrategy;
import org.junit.contrib.truth.subjects.Subject;
import org.junit.contrib.truth.subjects.And;
/**
* A simple example Subject to demonstrate extension.
*
* @author Christian Gruber (christianedwardgruber@gmail.com)
*/
public class MySubject extends Subject<MySubject, MyType> {
public MySubject(FailureStrategy failureStrategy, MyType subject) {
super(failureStrategy, subject);
}
public And<MySubject> matches(MyType object) {
if (getSubject().value != object.value) {
fail("matches", getSubject(), object);
}
return new And<MySubject>(this);
}
}
|
Update canvas (test dependency only). | Package.describe({
name: "froatsnook:bardcode",
version: "1.1.0",
summary: "Draw 1-D barcodes to Canvases (client and server)",
git: "https://github.com/froatsnook/bardcode"
});
Package.onUse(function(api) {
api.versionsFrom("1.0.3.1");
api.addFiles("lib/01-bardcode.js");
api.addFiles("lib/canvas.js");
api.addFiles("lib/Codabar.js");
api.addFiles("lib/Code128.js");
api.addFiles("lib/Code39.js");
api.addFiles("lib/drawBarcode.js");
api.addFiles("lib/EAN.js");
api.addFiles("lib/FIM.js");
api.addFiles("lib/ITF.js");
api.addFiles("lib/svg.js");
api.addFiles("lib/validations.js");
api.export("drawBarcode");
api.export("bardcode");
});
Package.onTest(function(api) {
Npm.depends({
"canvas": "1.2.1"
});
api.use("tinytest");
api.use("froatsnook:bardcode");
api.addFiles("test/tests.js");
});
| Package.describe({
name: "froatsnook:bardcode",
version: "1.1.0",
summary: "Draw 1-D barcodes to Canvases (client and server)",
git: "https://github.com/froatsnook/bardcode"
});
Package.onUse(function(api) {
api.versionsFrom("1.0.3.1");
api.addFiles("lib/01-bardcode.js");
api.addFiles("lib/canvas.js");
api.addFiles("lib/Codabar.js");
api.addFiles("lib/Code128.js");
api.addFiles("lib/Code39.js");
api.addFiles("lib/drawBarcode.js");
api.addFiles("lib/EAN.js");
api.addFiles("lib/FIM.js");
api.addFiles("lib/ITF.js");
api.addFiles("lib/svg.js");
api.addFiles("lib/validations.js");
api.export("drawBarcode");
api.export("bardcode");
});
Package.onTest(function(api) {
Npm.depends({
"canvas": "1.1.6"
});
api.use("tinytest");
api.use("froatsnook:bardcode");
api.addFiles("test/tests.js");
});
|
Fix a couple of redirect URLs | from django.conf.urls import url
from parliament.core.utils import redir_view
from parliament.hansards.redirect_views import hansard_redirect
urlpatterns = [
url(r'^hansards/$', redir_view('debates')),
url(r'^hansards/year/(?P<year>\d{4})/$', redir_view('debates_by_year')),
url(r'^hansards/(?P<hansard_id>\d+)/$', hansard_redirect),
url(r'^hansards/(?P<hansard_date>[0-9-]+)/$', hansard_redirect),
url(r'^hansards/(?P<hansard_id>\d+)/(?P<sequence>\d+)/$', hansard_redirect),
url(r'^hansards/(?P<hansard_date>[0-9-]+)/(?P<sequence>\d+)/$', hansard_redirect),
url(r'^hansards/(?P<hansard_id>\d+)/(?P<sequence>\d+)/(?P<only>only|permalink)/$', hansard_redirect),
url(r'^hansards/(?P<hansard_date>[0-9-]+)/(?P<sequence>\d+)/(?P<only>only|permalink)/$', hansard_redirect),
]
| from django.conf.urls import url
from parliament.core.utils import redir_view
from parliament.hansards.redirect_views import hansard_redirect
urlpatterns = [
url(r'^hansards/$', redir_view('parliament.hansards.views.index')),
url(r'^hansards/year/(?P<year>\d{4})/$', redir_view('parliament.hansards.views.by_year')),
url(r'^hansards/(?P<hansard_id>\d+)/$', hansard_redirect),
url(r'^hansards/(?P<hansard_date>[0-9-]+)/$', hansard_redirect),
url(r'^hansards/(?P<hansard_id>\d+)/(?P<sequence>\d+)/$', hansard_redirect),
url(r'^hansards/(?P<hansard_date>[0-9-]+)/(?P<sequence>\d+)/$', hansard_redirect),
url(r'^hansards/(?P<hansard_id>\d+)/(?P<sequence>\d+)/(?P<only>only|permalink)/$', hansard_redirect),
url(r'^hansards/(?P<hansard_date>[0-9-]+)/(?P<sequence>\d+)/(?P<only>only|permalink)/$', hansard_redirect),
]
|
Handle missing version in payload. | import json
from urllib.parse import urljoin
import sys
def get_payload():
return json.load(sys.stdin)
def get_index_url(payload):
source = payload['source']
uri = source['uri']
index = source['index']
if not uri.endswith('/'):
uri += '/'
if not index.endswith('/'):
index += '/'
return urljoin(uri, index)
def get_package_url(payload):
package = payload['source']['package']
return get_index_url(payload) + package
def get_auth(payload):
source = payload['source']
return source['username'], source['password']
def get_version(payload):
try:
version = payload['version']['version']
except TypeError:
version = None
return version
| import json
from urllib.parse import urljoin
import sys
def get_payload():
return json.load(sys.stdin)
def get_index_url(payload):
source = payload['source']
uri = source['uri']
index = source['index']
if not uri.endswith('/'):
uri += '/'
if not index.endswith('/'):
index += '/'
return urljoin(uri, index)
def get_package_url(payload):
package = payload['source']['package']
return get_index_url(payload) + package
def get_auth(payload):
source = payload['source']
return source['username'], source['password']
def get_version(payload):
if 'version' in payload:
version = payload['version']['version']
else:
version = None
return version
|
Change order of home page elements | /* configure jshint globals */
/* globals numeral */
(function ($) {
'use strict';
// Set langauge for Numeral library.
numeral.language('es');
var $center = $('center');
var first_table = $('center').prev().detach();
$center.after(first_table);
var dinero_ya = $('.containerDineroYa').detach();
$center.append(dinero_ya);
$center.find('>div:eq(0)>br').remove();
$center.find('table table:eq(5) tr:gt(1):lt(-2)').each(function () {
var $tr = $(this);
var $total = $tr.find('td:eq(2) .pesetas');
var $disponible = $tr.find('td:last .pesetas');
numeral.language('es');
var saldo = numeral($total.html()).subtract(numeral($disponible.html()));
$disponible.append(' (' + saldo.format('0,0.00') + ')');
});
})(jQuery);
| /* configure jshint globals */
/* globals numeral */
(function ($) {
'use strict';
// Set langauge for Numeral library.
numeral.language('es');
var $toggle = $('<div id=containerDineroYa-toggle>DineroYa</div>');
$toggle.click(function () {
$('.containerDineroYa').toggle();
});
$('.containerDineroYa').before($toggle);
$('.containerDineroYa').hide();
$('center table table:eq(5) tr:gt(1):lt(-2)').each(function () {
var $tr = $(this);
var $total = $tr.find('td:eq(2) .pesetas');
var $disponible = $tr.find('td:last .pesetas');
numeral.language('es');
var saldo = numeral($total.html()).subtract(numeral($disponible.html()));
$disponible.append(' (' + saldo.format('0,0.00') + ')');
});
})(jQuery);
|
Use UberProxy URL for 'tryserver.chromiumos'
BUG=352897
TEST=None
Review URL: https://codereview.chromium.org/554383002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@291886 0039d316-1c4b-4281-b951-d872f2087c98 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumOSTryServer(Master.ChromiumOSBase):
project_name = 'ChromiumOS Try Server'
master_port = 8049
slave_port = 8149
master_port_alt = 8249
try_job_port = 8349
buildbot_url = 'https://uberchromegw.corp.google.com/p/tryserver.chromiumos/'
repo_url_ext = 'https://chromium.googlesource.com/chromiumos/tryjobs.git'
repo_url_int = 'https://chrome-internal.googlesource.com/chromeos/tryjobs.git'
from_address = 'cros.tryserver@chromium.org'
# The reply-to address to set for emails sent from the server.
reply_to = 'chromeos-build@google.com'
# Select tree status urls and codereview location.
base_app_url = 'https://chromiumos-status.appspot.com'
tree_status_url = base_app_url + '/status'
| # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumOSTryServer(Master.ChromiumOSBase):
project_name = 'ChromiumOS Try Server'
master_port = 8049
slave_port = 8149
master_port_alt = 8249
try_job_port = 8349
buildbot_url = 'http://chromegw/p/tryserver.chromiumos/'
repo_url_ext = 'https://chromium.googlesource.com/chromiumos/tryjobs.git'
repo_url_int = 'https://chrome-internal.googlesource.com/chromeos/tryjobs.git'
from_address = 'cros.tryserver@chromium.org'
# The reply-to address to set for emails sent from the server.
reply_to = 'chromeos-build@google.com'
# Select tree status urls and codereview location.
base_app_url = 'https://chromiumos-status.appspot.com'
tree_status_url = base_app_url + '/status'
|
Add missing params to league position | package no.stelar7.api.l4j8.basic.constants.types;
import java.util.Optional;
import java.util.stream.Stream;
public enum LeaguePositionType implements CodedEnum
{
/**
* MASTER+ rank gets this for some reason?
*/
APEX,
/**
* Top lane
*/
TOP,
/**
* Jungle
*/
JUNGLE,
/**
* Mid lane
*/
MIDDLE,
/**
* Bottom lane
*/
BOTTOM,
/**
* Support
*/
UTILITY,
/**
* Not a positional queue
*/
NONE;
/**
* Returns an LeaguePositionType from the provided value
*
* @param type the type to check
* @return LeaguePositionType
*/
public Optional<LeaguePositionType> getFromCode(final String type)
{
return Stream.of(LeaguePositionType.values()).filter(t -> t.name().equalsIgnoreCase(type)).findFirst();
}
/**
* The value used to map strings to objects
*
* @return String
*/
public String getCode()
{
return this.name();
}
}
| package no.stelar7.api.l4j8.basic.constants.types;
import java.util.Optional;
import java.util.stream.Stream;
public enum LeaguePositionType implements CodedEnum
{
/**
* Top lane
*/
TOP,
/**
* Jungle
*/
JUNGLE,
/**
* Mid lane
*/
MIDDLE,
/**
* Bottom lane
*/
BOTTOM,
/**
* Support
*/
UTILITY;
/**
* Returns an LeaguePositionType from the provided value
*
* @param type the type to check
* @return LeaguePositionType
*/
public Optional<LeaguePositionType> getFromCode(final String type)
{
return Stream.of(LeaguePositionType.values()).filter(t -> t.name().equalsIgnoreCase(type)).findFirst();
}
/**
* The value used to map strings to objects
*
* @return String
*/
public String getCode()
{
return this.name();
}
}
|
Revert "update default test server port to 8081"
This reverts commit 4e784e0252201b7890a8a6749dda8b8fa68e33d9. Which
broke the tests because their port numbers weren't updated too. And
there was no real need to make this change in the first place. | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.aethersanctum.lilrest.server;
import org.skife.config.Config;
import org.skife.config.Default;
import org.skife.config.TimeSpan;
/**
*/
public interface JaxRsServerConfig {
@Config("basic.server.listen-port")
@Default("8080")
int port();
@Config("basic.server.max-threads")
@Default("500")
int maxThreads();
@Config("basic.server.idle-timeout")
@Default("30000ms")
TimeSpan idleTimeout();
}
| /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.aethersanctum.lilrest.server;
import org.skife.config.Config;
import org.skife.config.Default;
import org.skife.config.TimeSpan;
/**
*/
public interface JaxRsServerConfig {
@Config("basic.server.listen-port")
@Default("8081")
int port();
@Config("basic.server.max-threads")
@Default("500")
int maxThreads();
@Config("basic.server.idle-timeout")
@Default("30000ms")
TimeSpan idleTimeout();
}
|
Fix the shape of gap_w | import tensorflow as tf
slim = tf.contrib.slim
def le_net(images, num_classes=10, scope='LeNet'):
with tf.variable_scope(scope, 'LeNet', [images, num_classes]):
net = slim.conv2d(images, 32, [5, 5], scope='conv1')
net = slim.max_pool2d(net, [2, 2], 2, scope='pool1')
net = slim.conv2d(net, 64, [5, 5], scope='conv2')
net = slim.max_pool2d(net, [2, 2], 2, scope='pool2')
gap = tf.reduce_mean(net, (1, 2))
with tf.variable_scope('GAP'):
gap_w = tf.get_variable('W', shape=[64, num_classes], initializer=tf.random_normal_initializer(0., 0.01))
logits = tf.matmul(gap, gap_w)
return logits, net
def le_net_arg_scope(weight_decay=0.0):
with slim.arg_scope(
[slim.conv2d, slim.fully_connected],
weights_regularizer=slim.l2_regularizer(weight_decay),
weights_initializer=tf.truncated_normal_initializer(stddev=0.1),
activation_fn=tf.nn.relu) as sc:
return sc
| import tensorflow as tf
slim = tf.contrib.slim
def le_net(images, num_classes=10, scope='LeNet'):
with tf.variable_scope(scope, 'LeNet', [images, num_classes]):
net = slim.conv2d(images, 32, [5, 5], scope='conv1')
net = slim.max_pool2d(net, [2, 2], 2, scope='pool1')
net = slim.conv2d(net, 64, [5, 5], scope='conv2')
net = slim.max_pool2d(net, [2, 2], 2, scope='pool2')
gap = tf.reduce_mean(net, (1, 2))
with tf.variable_scope('GAP'):
gap_w = tf.get_variable('W', shape=[64, 10], initializer=tf.random_normal_initializer(0., 0.01))
logits = tf.matmul(gap, gap_w)
return logits, net
def le_net_arg_scope(weight_decay=0.0):
with slim.arg_scope(
[slim.conv2d, slim.fully_connected],
weights_regularizer=slim.l2_regularizer(weight_decay),
weights_initializer=tf.truncated_normal_initializer(stddev=0.1),
activation_fn=tf.nn.relu) as sc:
return sc
|
Add finishLine state to Game object | function Game(){
this.$track = $('#racetrack');
this.finishLine = this.$track.width() - 54;
}
function Player(id){
this.player = $('.player')[id - 1];
this.position = 10;
}
Player.prototype.move = function(){
this.position += 10;
};
Player.prototype.updatePosition = function(){
$player = $(this.player);
$player.css('margin-left', this.position);
};
$(document).ready(function() {
var game = new Game();
var player1 = new Player(1);
var player2 = new Player(2);
$(document).on('keyup', function(keyPress){
if(keyPress.keyCode === 80) {
player1.move();
player1.updatePosition();
} else if (keyPress.keyCode === 81) {
player2.move();
player2.updatePosition();
}
});
}); | function Game(){
this.$track = $('#racetrack');
}
function Player(id){
this.player = $('.player')[id - 1];
this.position = 10;
}
Player.prototype.move = function(){
this.position += 10;
};
Player.prototype.updatePosition = function(){
$player = $(this.player);
$player.css('margin-left', this.position);
};
$(document).ready(function() {
var game = new Game();
var player1 = new Player(1);
var player2 = new Player(2);
$(document).on('keyup', function(keyPress){
if(keyPress.keyCode === 80) {
player1.move();
player1.updatePosition();
} else if (keyPress.keyCode === 81) {
player2.move();
player2.updatePosition();
}
});
}); |
Add /norestart flag to updater. | <rss xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
<channel>
<title>{{ $app_name }} Update</title>
<description>New version available.</description>
<language>en</language>
<item>
<title>Version {{ $version_name }}</title>
<description>
<![CDATA[
<ul>
@foreach ($changes AS $change)
<li>{{ $change }}</li>
@endforeach
</ul>
]]>
</description>
<pubDate>{{ $date }}</pubDate>
<enclosure url="{{ url('/') }}/releases/{{ $file_name }}-{{ $version_number }}-{{ $platform }}.msi" length="0" sparkle:os="windows" sparkle:installerArguments="/quiet /norestart" sparkle:version="{{ $version_number }}" type="application/octet-stream"/>
</item>
</channel>
</rss> | <rss xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
<channel>
<title>{{ $app_name }} Update</title>
<description>New version available.</description>
<language>en</language>
<item>
<title>Version {{ $version_name }}</title>
<description>
<![CDATA[
<ul>
@foreach ($changes AS $change)
<li>{{ $change }}</li>
@endforeach
</ul>
]]>
</description>
<pubDate>{{ $date }}</pubDate>
<enclosure url="{{ url('/') }}/releases/{{ $file_name }}-{{ $version_number }}-{{ $platform }}.msi" length="0" sparkle:os="windows" sparkle:installerArguments="/quiet" sparkle:version="{{ $version_number }}" type="application/octet-stream"/>
</item>
</channel>
</rss> |
Use console.error to log mocha errors. | var exec = require('child_process').exec,
gulp = require('gulp'),
size = require('gulp-size'),
concat = require('gulp-concat')
gulp.task('build_tests', function() {
return gulp.src('./test/**/!(tests)**.js')
.pipe(concat('tests.js'))
.pipe(size())
.pipe(gulp.dest('./test'))
});
gulp.task('test', ['build_tests'], function() {
var path = './node_modules/mocha-phantomjs/bin/mocha-phantomjs',
options = '-s loadImages=false -s webSecurityEnabled=false',
command = '/test/index.html';
exec(path + ' ' + options + ' ' + command, function (error, stdout, stderr) {
if (stdout) {
console.log(stdout);
} else if (stderr) {
console.error(stderr);
} else if (error) {
console.error(error);
}
});
});
| var exec = require('child_process').exec,
gulp = require('gulp'),
size = require('gulp-size'),
concat = require('gulp-concat')
gulp.task('build_tests', function() {
return gulp.src('./test/**/!(tests)**.js')
.pipe(concat('tests.js'))
.pipe(size())
.pipe(gulp.dest('./test'))
});
gulp.task('test', ['build_tests'], function() {
var path = './node_modules/mocha-phantomjs/bin/mocha-phantomjs',
options = '-s loadImages=false -s webSecurityEnabled=false',
command = '/test/index.html';
exec(path + ' ' + options + ' ' + command, function (error, stdout, stderr) {
if (stdout) {
console.log(stdout);
} else if (stderr) {
console.log(stderr);
} else if (error) {
console.log(error);
}
});
});
|
Fix params not being generated for other files | import subprocess
import os
#from tailorscad.config import ScadConfig
BASE_DIR = '/usr/bin/'
DEFAULT = BASE_DIR + 'openscad'
def build_with_openscad(state):
args = build_args_from_state(state)
out_call = ''
for arg in args:
out_call += ' ' + arg
print 'args:', out_call
try:
subprocess.check_call(args)
return True
except subprocess.CalledProcessError as (e):
print str(e)
return False
def build_args_from_state(state):
#executable = ScadConfig.open_scad if ScadConfig.open_scad else DEFAULT
executable = 'openscad'
replace = []
if state.params:
print 'state params:', state.params
# TODO: Handle string exceptions
replace = ['-D ' + '='.join((key, str(value)))
for key, value in state.params.iteritems()]
print 'state replace:', replace
# TODO: Handle different output types
output = os.path.join(state.output_directory, state.name + ".stl")
args = [executable, '-o', output]
if len(replace) >= 1:
args.extend(replace)
args.append(state.main_path)
return args
| import subprocess
import os
#from tailorscad.config import ScadConfig
BASE_DIR = '/usr/bin/'
DEFAULT = BASE_DIR + 'openscad'
def build_with_openscad(state):
args = build_args_from_state(state)
out_call = ''
for arg in args:
out_call += ' ' + arg
print 'args:', out_call
try:
subprocess.check_call(args)
return True
except subprocess.CalledProcessError as (e):
print str(e)
return False
def build_args_from_state(state):
#executable = ScadConfig.open_scad if ScadConfig.open_scad else DEFAULT
executable = 'openscad'
replace = ['-D']
if state.params:
print 'state params:', state.params
replace = [':'.join((key, str(value)))
for key, value in state.params.iteritems()]
output = os.path.join(state.output_directory, state.name + ".stl")
args = [executable, '-o', output]
if len(replace) > 1:
args.extend(replace)
args.append(state.main_path)
return args
|
Fix the patch package to be compatible with Yarn. | const fs = require('fs');
const path = require('path');
function patch(packageJson, depName, hostPackageName) {
if (packageJson[depName] && packageJson[depName][hostPackageName]) {
packageJson[depName][hostPackageName] = 'file:../../'; // eslint-disable-line no-param-reassign
}
}
const workingFolder = process.cwd();
const hostPackagePath = path.resolve(workingFolder, '../../package.json');
const hostPackageJson = JSON.parse(fs.readFileSync(hostPackagePath));
const hostPackageName = hostPackageJson.name;
const dependentPackagePath = path.resolve(workingFolder, './package.json');
const dependentPackageJson = JSON.parse(fs.readFileSync(dependentPackagePath));
patch(dependentPackageJson, 'dependencies', hostPackageName);
patch(dependentPackageJson, 'devDependencies', hostPackageName);
patch(dependentPackageJson, 'peerDependencies', hostPackageName);
const patchedPackageContent = JSON.stringify(dependentPackageJson, null, 2);
fs.writeFileSync(dependentPackagePath, `${patchedPackageContent}\n`, 'utf-8');
| const fs = require('fs');
const path = require('path');
function patch(packageJson, depName, hostPackageName) {
if (packageJson[depName] && packageJson[depName][hostPackageName]) {
packageJson[depName][hostPackageName] = '../../'; // eslint-disable-line no-param-reassign
}
}
const workingFolder = process.cwd();
const hostPackagePath = path.resolve(workingFolder, '../../package.json');
const hostPackageJson = JSON.parse(fs.readFileSync(hostPackagePath));
const hostPackageName = hostPackageJson.name;
const dependentPackagePath = path.resolve(workingFolder, './package.json');
const dependentPackageJson = JSON.parse(fs.readFileSync(dependentPackagePath));
patch(dependentPackageJson, 'dependencies', hostPackageName);
patch(dependentPackageJson, 'devDependencies', hostPackageName);
patch(dependentPackageJson, 'peerDependencies', hostPackageName);
const patchedPackageContent = JSON.stringify(dependentPackageJson, null, 2);
fs.writeFileSync(dependentPackagePath, `${patchedPackageContent}\n`, 'utf-8');
|
Use PHP5.3 compat array syntax | <?php
/**
* Created by JetBrains PhpStorm.
* User: Doug
* Date: 28/07/13
* Time: 12:58
* To change this template use File | Settings | File Templates.
*/
namespace DVDoug\BoxPacker;
class ItemListTest extends \PHPUnit_Framework_TestCase {
function testCompare() {
$box1 = new TestItem('Small', 20, 20, 2, 100);
$box2 = new TestItem('Large', 200, 200, 20, 1000);
$box3 = new TestItem('Medium', 100, 100, 10, 500);
$list = new ItemList;
$list->insert($box1);
$list->insert($box2);
$list->insert($box3);
$sorted = array();
while (!$list->isEmpty()) {
$sorted[] = $list->extract();
}
self::assertEquals(array($box2,$box3,$box1), $sorted);
}
}
| <?php
/**
* Created by JetBrains PhpStorm.
* User: Doug
* Date: 28/07/13
* Time: 12:58
* To change this template use File | Settings | File Templates.
*/
namespace DVDoug\BoxPacker;
class ItemListTest extends \PHPUnit_Framework_TestCase {
function testCompare() {
$box1 = new TestItem('Small', 20, 20, 2, 100);
$box2 = new TestItem('Large', 200, 200, 20, 1000);
$box3 = new TestItem('Medium', 100, 100, 10, 500);
$list = new ItemList;
$list->insert($box1);
$list->insert($box2);
$list->insert($box3);
$sorted = [];
while (!$list->isEmpty()) {
$sorted[] = $list->extract();
}
self::assertEquals(array($box2,$box3,$box1), $sorted);
}
}
|
Update links for child theme
To make child theme work better. | <?php
/*********************
Enqueue the proper CSS
if you use Sass.
*********************/
function reverie_enqueue_style()
{
// foundation stylesheet
wp_register_style( 'reverie-foundation-stylesheet', get_template_directory_uri() . '/css/app.css', array(), '' );
// Register the main style
wp_register_style( 'reverie-stylesheet', get_template_directory_uri() . '/css/style.css', array(), '', 'all' );
wp_enqueue_style( 'reverie-foundation-stylesheet' );
wp_enqueue_style( 'reverie-stylesheet' );
// Register child theme style if using child theme
if ( is_child_theme() ) {
wp_register_style( 'reverie-child-stylesheet', get_stylesheet_directory_uri() . '/css/style.css', array(), '', 'all' );
wp_enqueue_style( 'reverie-child-stylesheet' );
}
}
add_action( 'wp_enqueue_scripts', 'reverie_enqueue_style' );
?>
| <?php
/*********************
Enqueue the proper CSS
if you use Sass.
*********************/
function reverie_enqueue_style()
{
// foundation stylesheet
wp_register_style( 'reverie-foundation-stylesheet', get_template_directory_uri() . '/css/app.css', array(), '' );
// Register the main style
wp_register_style( 'reverie-stylesheet', get_template_directory_uri() . '/css/style.css', array(), '', 'all' );
wp_enqueue_style( 'reverie-foundation-stylesheet' );
wp_enqueue_style( 'reverie-stylesheet' );
// Register child theme style if using child theme
if ( is_child_theme() ) {
wp_register_style( 'reverie-child-stylesheet', get_stylesheet_directory_uri() . '/style.css', array(), '', 'all' );
wp_enqueue_style( 'reverie-child-stylesheet' );
}
}
add_action( 'wp_enqueue_scripts', 'reverie_enqueue_style' );
?>
|
Add back in previous constructor to make revapi happy, but no one should really be creating these anyway | package com.elmakers.mine.bukkit.api.event;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.spell.Spell;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
/**
* A custom event that the Magic plugin will fire any time a
* Mage casts a Spell.
*/
public class CastEvent extends Event {
private final CastContext context;
private static final HandlerList handlers = new HandlerList();
public CastEvent(Mage mage, Spell spell, SpellResult result) {
throw new IllegalArgumentException("Please create a CastEvent with CastContext now .. but also why are you creating a CastEvent?");
}
public CastEvent(CastContext context) {
this.context = context;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
public Mage getMage() {
return context.getMage();
}
public Spell getSpell() {
return context.getSpell();
}
public CastContext getContext() {
return context;
}
public SpellResult getSpellResult() {
return context.getResult();
}
}
| package com.elmakers.mine.bukkit.api.event;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.spell.Spell;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
/**
* A custom event that the Magic plugin will fire any time a
* Mage casts a Spell.
*/
public class CastEvent extends Event {
private final CastContext context;
private static final HandlerList handlers = new HandlerList();
public CastEvent(CastContext context) {
this.context = context;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
public Mage getMage() {
return context.getMage();
}
public Spell getSpell() {
return context.getSpell();
}
public CastContext getContext() {
return context;
}
public SpellResult getSpellResult() {
return context.getResult();
}
}
|
Check for a user from previously in the pipeline before checking for duplicate user. | from django.contrib.auth import get_user_model
from django.utils.translation import ugettext
from social_auth.exceptions import AuthAlreadyAssociated
from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email
def associate_by_email(*args, **kwargs):
"""Check if a user with this email already exists. If they do, don't create an account."""
backend = kwargs['backend']
if backend.name in ['google-oauth2', 'github'] or kwargs.get('user'):
# We provide and exception here for users upgrading.
return super_associate_by_email(*args, **kwargs)
email = kwargs['details'].get('email')
if email:
User = get_user_model()
if User.objects.filter(email=email).exists():
msg = ugettext('This email is already in use. First login with your other account and '
'under the top right menu click add account.')
raise AuthAlreadyAssociated(backend, msg % {
'provider': backend.name
})
| from django.contrib.auth import get_user_model
from django.utils.translation import ugettext
from social_auth.exceptions import AuthAlreadyAssociated
from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email
def associate_by_email(*args, **kwargs):
"""Check if a user with this email already exists. If they do, don't create an account."""
backend = kwargs['backend']
if backend.name in ['google-oauth2', 'github']:
# We provide and exception here for users upgrading.
return super_associate_by_email(*args, **kwargs)
email = kwargs['details'].get('email')
if email:
User = get_user_model()
if User.objects.filter(email=email).exists():
msg = ugettext('This email is already in use. First login with your other account and '
'under the top right menu click add account.')
raise AuthAlreadyAssociated(backend, msg % {
'provider': backend.name
})
|
Update VueGWT panel to support Factory | package com.axellience.vuegwt.client.gwtpanel;
import com.axellience.vuegwt.client.VueGWT;
import com.axellience.vuegwt.client.component.VueComponent;
import com.axellience.vuegwt.client.vue.VueFactory;
import com.axellience.vuegwt.client.vue.VueJsConstructor;
import com.google.gwt.user.client.ui.SimplePanel;
/**
* Wrap a {@link VueComponent} instance in a GWT Panel
* @author Adrien Baron
*/
public class VueGwtPanel<T extends VueComponent> extends SimplePanel
{
private T vueComponentInstance;
public VueGwtPanel(VueFactory<T> vueFactory)
{
this(vueFactory.getJsConstructor());
}
public VueGwtPanel(VueJsConstructor<T> vueJsConstructor)
{
super();
vueComponentInstance = vueJsConstructor.instantiate();
}
public VueGwtPanel(Class<T> vueClass)
{
this(VueGWT.getFactory(vueClass));
}
@Override
protected void onAttach()
{
super.onAttach();
vueComponentInstance.$mount(getElement());
}
public T vue()
{
return this.vueComponentInstance;
}
}
| package com.axellience.vuegwt.client.gwtpanel;
import com.axellience.vuegwt.client.VueGWT;
import com.axellience.vuegwt.client.component.VueComponent;
import com.axellience.vuegwt.client.vue.VueJsConstructor;
import com.google.gwt.user.client.ui.SimplePanel;
/**
* Wrap a {@link VueComponent} instance in a GWT Panel
* @author Adrien Baron
*/
public class VueGwtPanel<T extends VueComponent> extends SimplePanel
{
private T vueComponentInstance;
public VueGwtPanel(VueJsConstructor<T> vueJsConstructor)
{
super();
vueComponentInstance = vueJsConstructor.instantiate();
}
public VueGwtPanel(Class<T> vueClass)
{
super();
vueComponentInstance = VueGWT.createInstance(vueClass);
}
@Override
protected void onAttach()
{
super.onAttach();
vueComponentInstance.$mount(getElement());
}
public T vue()
{
return this.vueComponentInstance;
}
}
|
Add value to the exception for debugging. | package pg.hadoop.pig;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.Tuple;
import java.io.IOException;
/**
* Returns the hashcode of the given String or Number.
*/
public class HashCode extends EvalFunc<Integer> {
@Override
public Integer exec(final Tuple input) throws IOException {
if (input.size() != 1) {
throw new IllegalArgumentException("HashCode function requires a String or Number parameter.");
}
final Object obj = input.get(0);
if (!(obj instanceof String) && !(obj instanceof Number)) {
throw new IllegalArgumentException("HashCode only supports Strings and Numbers. Value=" + String.valueOf(obj));
}
return obj.hashCode();
}
}
| package pg.hadoop.pig;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.Tuple;
import java.io.IOException;
/**
* Returns the hashcode of the given String or Number.
*/
public class HashCode extends EvalFunc<Integer> {
@Override
public Integer exec(final Tuple input) throws IOException {
if (input.size() != 1) {
throw new IllegalArgumentException("HashCode function requires a String or Number parameter.");
}
final Object obj = input.get(0);
if (!(obj instanceof String) && !(obj instanceof Number)) {
throw new IllegalArgumentException("HashCode only supports Strings and Numbers");
}
return obj.hashCode();
}
}
|
Fix traceback being emitted when updating a proxy-mode rus (RCE-2260) | #!/usr/bin/python
#
# Copyright (c) SAS Institute Inc.
#
import sys
import os
import pwd
from conary.server import schema
from conary.lib import cfgtypes, tracelog
from conary import dbstore
from .config import UpsrvConfig
class SimpleFileLog(tracelog.FileLog):
def printLog(self, level, msg):
self.fd.write("%s\n" % msg)
try:
cfg = UpsrvConfig.load()
except cfgtypes.CfgEnvironmentError:
print "Error reading config file"
sys.exit(1)
if not cfg.repositoryDB:
print "In proxy mode, no migration required"
sys.exit(0)
tracelog.FileLog = SimpleFileLog
tracelog.initLog(filename='stderr', level=2)
db = dbstore.connect(cfg.repositoryDB[1], cfg.repositoryDB[0])
schema.loadSchema(db, doMigrate=True)
if cfg.repositoryDB[0] == 'sqlite':
os.chown(cfg.repositoryDB[1], pwd.getpwnam('apache')[2],
pwd.getpwnam('apache')[3])
| #!/usr/bin/python
#
# Copyright (c) SAS Institute Inc.
#
import sys
import os
import pwd
from conary.server import schema
from conary.lib import cfgtypes, tracelog
from conary import dbstore
from .config import UpsrvConfig
class SimpleFileLog(tracelog.FileLog):
def printLog(self, level, msg):
self.fd.write("%s\n" % msg)
try:
cfg = UpsrvConfig.load()
except cfgtypes.CfgEnvironmentError:
print "Error reading config file"
sys.exit(1)
tracelog.FileLog = SimpleFileLog
tracelog.initLog(filename='stderr', level=2)
db = dbstore.connect(cfg.repositoryDB[1], cfg.repositoryDB[0])
schema.loadSchema(db, doMigrate=True)
if cfg.repositoryDB[0] == 'sqlite':
os.chown(cfg.repositoryDB[1], pwd.getpwnam('apache')[2],
pwd.getpwnam('apache')[3])
|
Use updated catchment tools import | import os
import numpy as np
from catchment_tools import get_grid_cells
def create_grids(catchments, in_directory, out_directory, grid_file):
"""
Create grid files for the supplied catchments.
:param catchments: List of catchment IDs.
:type catchments: Array(string)
:param in_directory: Path to catchment boundary (geojson) directory.
:type in_directory: string
:param out_directory: Output directory for catchment grid csv files.
:type out_directory: string
:param grid_file: Path to input grid file for coordinates to match boundaries against.
:type grid_file: string
"""
for catchment in catchments:
boundary = os.path.join(in_directory, catchment + '.json')
cells = np.asarray(get_grid_cells(boundary, grid_file, 0.3))
np.savetxt(os.path.join(out_directory, catchment + '.csv'), cells, fmt="%.2f", delimiter=',')
| import os
import numpy as np
from catchment_cutter import get_grid_cells
def create_grids(catchments, in_directory, out_directory, grid_file):
"""
Create grid files for the supplied catchments.
:param catchments: List of catchment IDs.
:type catchments: Array(string)
:param in_directory: Path to catchment boundary (geojson) directory.
:type in_directory: string
:param out_directory: Output directory for catchment grid csv files.
:type out_directory: string
:param grid_file: Path to input grid file for coordinates to match boundaries against.
:type grid_file: string
"""
for catchment in catchments:
boundary = os.path.join(in_directory, catchment + '.json')
cells = np.asarray(get_grid_cells(boundary, grid_file))
np.savetxt(os.path.join(out_directory, catchment + '.csv'), cells, fmt="%.2f", delimiter=',')
|
Change default CSS classes for rendered activities | <?php
namespace Honeybee\Ui\Renderer\Html\Honeybee\Ui\Activity;
use Honeybee\Ui\Renderer\ActivityRenderer;
class HtmlActivityRenderer extends ActivityRenderer
{
protected function getTemplateParameters()
{
$activity = $this->getPayload('subject');
$default_css = [
'activity',
'activity-' . strtolower($activity->getName())
];
$params = [];
$params['css'] = $this->getOption('css', $default_css);
$params['form_id'] = $this->getOption('form_id', $activity->getSettings()->get('form_id', 'formid'));
$params['form_parameters'] = $this->getOption('form_parameters', $activity->getUrl()->getParameters());
$params['form_method'] = $this->getOption('form_method', ($activity->getVerb() === 'read') ? 'GET' : 'POST');
$params['form_css'] = $this->getOption('form_css');
$params['emphasized'] = (bool)$this->getOption('emphasized', false);
return array_replace_recursive(parent::getTemplateParameters(), $params);
}
}
| <?php
namespace Honeybee\Ui\Renderer\Html\Honeybee\Ui\Activity;
use Honeybee\Ui\Renderer\ActivityRenderer;
class HtmlActivityRenderer extends ActivityRenderer
{
protected function getTemplateParameters()
{
$activity = $this->getPayload('subject');
$default_css = [
'button',
'button-' . strtolower($activity->getName())
];
if ($this->getOption('plain_activity')) {
$default_css = [
'activity',
'activity-' . strtolower($activity->getName())
];
}
$params = [];
$params['css'] = $this->getOption('css', $default_css);
$params['form_id'] = $this->getOption('form_id', $activity->getSettings()->get('form_id', 'formid'));
$params['form_parameters'] = $this->getOption('form_parameters', $activity->getUrl()->getParameters());
$params['form_method'] = $this->getOption('form_method', ($activity->getVerb() === 'read') ? 'GET' : 'POST');
$params['form_css'] = $this->getOption('form_css');
return array_replace_recursive(parent::getTemplateParameters(), $params);
}
}
|
8: Create documentation of DataSource Settings
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8 | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"
# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dblist = []
for db in dbs:
dbname = db.split('(')
n = 0
for i in dbname:
if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
dblist.append(str(db).replace('"',''))
n += 1
dblist.sort()
for db in dblist:
#t1 = ibmcnx.functions.getDSId( db )
print db
# AdminConfig.show( t1 )
# print '\n\n'
# AdminConfig.showall( t1 )
# AdminConfig.showAttribute(t1,'statementCacheSize' )
# AdminConfig.showAttribute(t1,'[statementCacheSize]' ) | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"
# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dblist = []
for db in dbs:
db = db.split('(')
n = 0
for i in db:
if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
dblist.append(str(i).replace('"',''))
n += 1
dblist.sort()
for db in dblist:
t1 = ibmcnx.functions.getDSId( db )
print t1
# AdminConfig.show( t1 )
# print '\n\n'
# AdminConfig.showall( t1 )
# AdminConfig.showAttribute(t1,'statementCacheSize' )
# AdminConfig.showAttribute(t1,'[statementCacheSize]' ) |
Update dsub version to 0.3.9
PiperOrigin-RevId: 319808345 | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.9'
| # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.9.dev0'
|
Fix autoloader to work with helper classes on linux | <?php
namespace PhpXmlRpc;
/**
* In the unlikely event that you are not using Composer to manage class autoloading, here's an autoloader for this lib.
* For usage, see any file in the demo/client directory
*/
class Autoloader
{
/**
* Registers PhpXmlRpc\Autoloader as an SPL autoloader.
*
* @param bool $prepend Whether to prepend the autoloader or not.
*/
public static function register($prepend = false)
{
spl_autoload_register(array(__CLASS__, 'autoload'), true, $prepend);
}
/**
* Handles autoloading of classes.
*
* @param string $class A class name.
*/
public static function autoload($class)
{
if (0 !== strpos($class, 'PhpXmlRpc\\')) {
return;
}
if (is_file($file = __DIR__ . str_replace(array('PhpXmlRpc\\', '\\'), '/', $class).'.php')) {
require $file;
}
}
} | <?php
namespace PhpXmlRpc;
/**
* In the unlikely event that you are not using Composer to manage class autoloading, here's an autoloader for this lib.
* For usage, see any file in the demo/client directory
*/
class Autoloader
{
/**
* Registers PhpXmlRpc\Autoloader as an SPL autoloader.
*
* @param bool $prepend Whether to prepend the autoloader or not.
*/
public static function register($prepend = false)
{
spl_autoload_register(array(__CLASS__, 'autoload'), true, $prepend);
}
/**
* Handles autoloading of classes.
*
* @param string $class A class name.
*/
public static function autoload($class)
{
if (0 !== strpos($class, 'PhpXmlRpc\\')) {
return;
}
if (is_file($file = __DIR__ . str_replace('PhpXmlRpc\\', '/', $class).'.php')) {
require $file;
}
}
} |
Use single quotes in test for everything except descriptions | (function() {
'use strict';
describe("<%= pluginFullName %>", function() {
var slides, deck,
createDeck = function() {
slides = [];
var parent = document.createElement('article');
for (var i = 0; i < 10; i++) {
slides.push(document.createElement('section'));
parent.appendChild(slides[i]);
}
deck = bespoke.from(parent, {
myplugin: true
});
};
beforeEach(createDeck);
describe("when a slide is activated", function() {
beforeEach(function() {
deck.slide(0);
});
it("should not a useless 'foobar' class to the slide", function() {
expect(slides[0].classList.contains('foobar')).toBe(false);
});
});
});
}());
| (function() {
"use strict";
describe("<%= pluginFullName %>", function() {
var slides, deck,
createDeck = function() {
slides = [];
var parent = document.createElement('article');
for (var i = 0; i < 10; i++) {
slides.push(document.createElement('section'));
parent.appendChild(slides[i]);
}
deck = bespoke.from(parent, {
myplugin: true
});
};
beforeEach(createDeck);
describe("when a slide is activated", function() {
beforeEach(function() {
deck.slide(0);
});
it("should not a useless 'foobar' class to the slide", function() {
expect(slides[0].classList.contains('foobar')).toBe(false);
});
});
});
}());
|
Use included to fetch supervisees | import Controller from '@ember/controller'
import { task } from 'ember-concurrency'
import QueryParams from 'ember-parachute'
import moment from 'moment'
const UsersEditResponsibilitiesQueryParams = new QueryParams({})
export default Controller.extend(UsersEditResponsibilitiesQueryParams.Mixin, {
setup() {
this.get('projects').perform()
this.get('supervisees').perform()
},
projects: task(function*() {
return yield this.store.query('project', {
reviewer: this.get('model.id'),
include: 'customer',
ordering: 'customer__name,name'
})
}),
supervisees: task(function*() {
let supervisor = this.get('model.id')
let balances = yield this.store.query('worktime-balance', {
supervisor,
date: moment().format('YYYY-MM-DD'),
include: 'user'
})
return balances.mapBy('user')
})
})
| import Controller from '@ember/controller'
import { task } from 'ember-concurrency'
import QueryParams from 'ember-parachute'
import moment from 'moment'
const UsersEditResponsibilitiesQueryParams = new QueryParams({})
export default Controller.extend(UsersEditResponsibilitiesQueryParams.Mixin, {
setup() {
this.get('projects').perform()
this.get('supervisees').perform()
},
projects: task(function*() {
return yield this.store.query('project', {
reviewer: this.get('model.id'),
include: 'customer',
ordering: 'customer__name,name'
})
}),
supervisees: task(function*() {
let supervisor = this.get('model.id')
yield this.store.query('worktime-balance', {
supervisor,
date: moment().format('YYYY-MM-DD')
})
return yield this.store.query('user', { supervisor, ordering: 'username' })
})
})
|
Add container__block for padding on default pages. | <?php
/**
* Generates site-wide page chrome.
* @see https://drupal.org/node/1728148
**/
?>
<!--[if lt IE 8 ]><div class="messages error">You're using an unsupported browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to make sure everything works nicely!</div><![endif]-->
<?php if (!empty($tabs['#primary'])): ?><nav class="admin-tabs"><?php print render($tabs); ?></nav><?php endif; ?>
<?php print $messages; ?>
<div class="wrapper">
<?php print $variables['navigation']; ?>
<?php print $variables['header']; ?>
<main role="main" class="container -padded">
<div class="wrapper">
<div class="container__block">
<?php print render($page['content']); ?>
</div>
</div>
</main>
<?php print $variables['footer']; ?>
</div>
| <?php
/**
* Generates site-wide page chrome.
* @see https://drupal.org/node/1728148
**/
?>
<!--[if lt IE 8 ]><div class="messages error">You're using an unsupported browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to make sure everything works nicely!</div><![endif]-->
<?php if (!empty($tabs['#primary'])): ?><nav class="admin-tabs"><?php print render($tabs); ?></nav><?php endif; ?>
<?php print $messages; ?>
<div class="wrapper">
<?php print $variables['navigation']; ?>
<?php print $variables['header']; ?>
<main role="main" class="container">
<div class="wrapper">
<?php print render($page['content']); ?>
</div>
</main>
<?php print $variables['footer']; ?>
</div>
|
GREEN: Correct file path is now returned. | package de.itemis.mosig.racecar.textconv;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class TextFileReader {
private final Path filePath;
public TextFileReader(Path filePath) {
this.filePath = filePath;
}
public String contents() {
String result = null;
try {
result = new String(Files.readAllBytes(filePath), StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException("Error while reading file '" + filePath + "'.", e);
}
return result;
}
public Path getFilePath() {
return filePath;
}
}
| package de.itemis.mosig.racecar.textconv;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class TextFileReader {
private final Path filePath;
public TextFileReader(Path filePath) {
this.filePath = filePath;
}
public String contents() {
String result = null;
try {
result = new String(Files.readAllBytes(filePath), StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException("Error while reading file '" + filePath + "'.", e);
}
return result;
}
public Path getFilePath() {
return null;
}
}
|
Update the API version used | <?php
declare(strict_types = 1);
namespace Speicher210\KontaktIO;
use function GuzzleHttp\default_user_agent;
class Client extends \GuzzleHttp\Client
{
public const API_VERSION_STABLE = '9';
public const API_VERSION_LATEST = '10';
/**
* @param string $apiKey
* @param string $version
*/
public function __construct($apiKey, $version = self::API_VERSION_STABLE)
{
parent::__construct(
[
'base_uri' => 'https://api.kontakt.io',
'headers' => [
'Accept' => 'application/vnd.com.kontakt+json;version=' . $version,
'Api-Key' => $apiKey,
'User-Agent' => 'Speicher210/KontaktIO ' . default_user_agent()
]
]
);
}
}
| <?php
namespace Speicher210\KontaktIO;
use function GuzzleHttp\default_user_agent;
class Client extends \GuzzleHttp\Client
{
const API_VERSION_STABLE = '7';
const API_VERSION_LATEST = '8';
/**
* Constructor.
*
* @param string $apiKey
* @param string $version
*/
public function __construct($apiKey, $version = self::API_VERSION_STABLE)
{
parent::__construct(
[
'base_uri' => 'https://api.kontakt.io',
'headers' => [
'Accept' => 'application/vnd.com.kontakt+json;version=' . $version,
'Api-Key' => $apiKey,
'User-Agent' => 'Speicher210/KontaktIO ' . default_user_agent(),
],
]
);
}
}
|
Update PreferenceActivity to keep the state through configuration changes | package com.negusoft.holoaccent.example;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import com.negusoft.holoaccent.activity.AccentActivity;
public class PreferencesActivity extends AccentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new GeneralPreferenceFragment())
.commit();
}
}
public static class GeneralPreferenceFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
}
}
}
| package com.negusoft.holoaccent.example;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import com.negusoft.holoaccent.activity.AccentActivity;
public class PreferencesActivity extends AccentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new GeneralPreferenceFragment())
.commit();
}
public static class GeneralPreferenceFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.