text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Add argument to adjust figure size
And minor styling tweaks.
|
import matplotlib.pyplot as plt
import numpy as np
def horizontal_bar(sorted_streaks, sort):
"""
Render a horizontal bar chart of streaks.
Values have already been sorted by sort.
"""
# Only extract those users & streaks for streaks that are non-zero:
users, streaks = zip(*[(user, streak.get(sort)) for user, streak
in sorted_streaks if streak.get(sort) > 0][::-1])
title = 'Top Contributors by {} Streak'.format(sort.title())
figure = plt.figure(num=None, figsize=(6, 15))
y_pos = np.arange(len(users)) # y-location of bars
print('y_pos', y_pos)
plt.barh(y_pos, streaks, facecolor='#5555EE', edgecolor='grey', align='center')
plt.yticks(y_pos, users)
plt.xlim([0, max(streaks) + 10]) # x-limits a bit wider at right
plt.subplots_adjust(left=0.25) # Wider left margin
plt.title(title)
for format in ('png', 'svg'):
figure.savefig('temp/top_{}.{}'.format(sort, format), format=format)
|
import matplotlib.pyplot as plt
import numpy as np
def horizontal_bar(sorted_streaks, sort):
"""
Render a horizontal bar chart of streaks.
Values have already been sorted by sort.
"""
# Only extract those users & streaks for streaks that are non-zero:
users, streaks = zip(*[(user, streak.get(sort)) for user, streak
in sorted_streaks if streak.get(sort) > 0][::-1])
title = 'Top Contributors by {} Streak'.format(sort.title())
figure = plt.figure()
y_pos = np.arange(len(users)) # y-location of bars
print('y_pos', y_pos)
plt.barh(y_pos, streaks, facecolor='#ff9999', edgecolor='grey', align='center')
plt.yticks(y_pos, users)
plt.xlim([0, max(streaks) + 0.5]) # x-limits a bit wider at right
plt.subplots_adjust(left=0.2) # Wider left margin
plt.title(title)
for format in ('png', 'svg'):
figure.savefig('temp/top_{}.{}'.format(sort, format), format=format)
|
Fix private route flashing login
|
/* eslint-disable */
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { Route, Redirect, withRouter } from 'react-router-dom'
const PrivateRouteComponent = props => {
const { component: Component, loggedIn, customRedirectPath, currentlySending, ...rest } = props
return (
<Route
{...rest}
render={values =>
loggedIn || currentlySending
? <Component {...values} />
: <Redirect
to={{
pathname: customRedirectPath ? customRedirectPath : '/2/login',
state: { from: values.location }
}}
/>}
/>
)
}
PrivateRouteComponent.propTypes = {
component: PropTypes.func.isRequired,
loggedIn: PropTypes.bool.isRequired
}
const mapStateToProps = state => ({
loggedIn: state.app.loggedIn,
currentlySending: state.app.currentlySending
})
const PrivateRoute = withRouter(connect(mapStateToProps)(PrivateRouteComponent))
export default PrivateRoute
|
/* eslint-disable */
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { Route, Redirect, withRouter } from 'react-router-dom'
const PrivateRouteComponent = props => {
const { component: Component, loggedIn, customRedirectPath, ...rest } = props
return (
<Route
{...rest}
render={values =>
loggedIn
? <Component {...values} />
: <Redirect
to={{
pathname: customRedirectPath ? customRedirectPath : '/2/login',
state: { from: values.location }
}}
/>}
/>
)
}
PrivateRouteComponent.propTypes = {
component: PropTypes.func.isRequired,
loggedIn: PropTypes.bool.isRequired
}
const mapStateToProps = state => ({
loggedIn: state.app.loggedIn
})
const PrivateRoute = withRouter(connect(mapStateToProps)(PrivateRouteComponent))
export default PrivateRoute
|
Fix missing parent constructor call
Signed-off-by: Christoph Wurst <7abde52c298496fa169fb750f91f213a282142af@winzerhof-wurst.at>
|
<?php
declare(strict_types=1);
/**
* @author Christoph Wurst <wurst.christoph@gmail.com>
* @author Lukas Reschke <lukas@owncloud.com>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* Mail
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Mail\Http;
use OCP\AppFramework\Http\Response;
class HtmlResponse extends Response {
/** @var string */
private $content;
public function __construct(string $content) {
parent::__construct();
$this->content = $content;
}
/**
* Simply sets the headers and returns the file contents
*
* @return string the file contents
*/
public function render(): string {
return $this->content;
}
}
|
<?php
declare(strict_types=1);
/**
* @author Christoph Wurst <wurst.christoph@gmail.com>
* @author Lukas Reschke <lukas@owncloud.com>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* Mail
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Mail\Http;
use OCP\AppFramework\Http\Response;
class HtmlResponse extends Response {
/** @var string */
private $content;
public function __construct(string $content) {
$this->content = $content;
}
/**
* Simply sets the headers and returns the file contents
*
* @return string the file contents
*/
public function render(): string {
return $this->content;
}
}
|
Add placeholder settings to unit tests
|
import unittest
from app import create_app, db
class AppTestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
# Temporary. Will be removed once default settings has been set up.
self.app.config['posts_per_page'] = '10'
self.app.config['blog_name'] = 'flask-blogger'
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_ctx.pop()
class DummyPostData(dict):
def getlist(self, key):
v = self[key]
if not isinstance(v, (list, tuple)):
v = [v]
return v
|
import unittest
from app import create_app, configure_settings, db
class AppTestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
configure_settings(self.app)
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_ctx.pop()
class DummyPostData(dict):
def getlist(self, key):
v = self[key]
if not isinstance(v, (list, tuple)):
v = [v]
return v
|
Simplify random, so it can be port as easily as possible.
|
package org.chabu;
public class Random {
private long seed;
private static final long multiplier = 0x5_DEEC_E66DL;
private static final long addend = 0x0BL;
private static final long mask = (1L << 48) - 1;
public Random(long seed) {
this.seed = (seed ^ multiplier) & mask;
}
public void nextBytes(byte[] bytes, int offset, int length ) {
for (int i = 0; i < length; ) {
bytes[offset+i++] = (byte)nextInt();
}
}
public int nextInt() {
this.seed = (this.seed * multiplier + addend) & mask;
return (int)(this.seed >>> 16);
}
}
|
package org.chabu;
public
class Random {
private long seed;
private static final long multiplier = 0x5_DEEC_E66DL;
private static final long addend = 0x0BL;
private static final long mask = (1L << 48) - 1;
public Random(long seed) {
this.seed = initialScramble(seed);
}
private static long initialScramble(long seed) {
return (seed ^ multiplier) & mask;
}
protected int next(int bits) {
this.seed = (this.seed * multiplier + addend) & mask;
return (int)(this.seed >>> (48 - bits));
}
public void nextBytes(byte[] bytes, int offset, int length ) {
for (int i = 0; i < length; ) {
bytes[offset+i++] = (byte)nextInt();
}
}
public int nextInt() {
return next(32);
}
}
|
Store begin and end times as dates
|
package edu.pdx.cs410J.chances;
import edu.pdx.cs410J.AbstractAppointment;
import java.util.Date;
public class Appointment extends AbstractAppointment {
private Date beginTime;
private Date endTime;
private String description;
public Appointment() {}
public Appointment(String description) {
this.description = description;
}
/**
* Set the time this appointment begins.
*/
public void setBeginTime(Date beginTime) {
this.beginTime = beginTime;
}
/**
* Set the time this appointment ends.
*/
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
/**
* Get the time this appointment begins.
*
* @return String representation of appointment begin time
*/
@Override
public String getBeginTimeString() {
return beginTime.toString();
}
/**
* Get the time this appointment ends.
*
* @return String representation of appointment end time
*/
@Override
public String getEndTimeString() {
return endTime.toString();
}
/**
* Get the description of this appointment.
*
* @return Description of this appointment
*/
@Override
public String getDescription() {
return description;
}
}
|
package edu.pdx.cs410J.chances;
import edu.pdx.cs410J.AbstractAppointment;
import java.util.Date;
public class Appointment extends AbstractAppointment {
private String beginTime;
private String endTime;
private String description;
public Appointment() {}
public Appointment(String description) {
this.description = description;
}
/**
* Set the time this appointment begins.
*/
public void setBeginTime(Date beginTime) {
this.beginTime = beginTime.toString();
}
/**
* Set the time this appointment ends.
*/
public void setEndTime(Date endTime) {
this.endTime = endTime.toString();
}
/**
* Get the time this appointment begins.
*
* @return String representation of appointment begin time
*/
@Override
public String getBeginTimeString() {
return beginTime;
}
/**
* Get the time this appointment ends.
*
* @return String representation of appointment end time
*/
@Override
public String getEndTimeString() {
return endTime;
}
/**
* Get the description of this appointment.
*
* @return Description of this appointment
*/
@Override
public String getDescription() {
return description;
}
}
|
Add a check for history and replaceState.
|
window.extractToken = (hash) => {
const match = hash.match(/access_token=(\w+)/);
let token = !!match && match[1];
if (!token) {
token = localStorage.getItem('ello_access_token');
}
return token;
}
window.checkAuth = () => {
const token = extractToken(document.location.hash);
if (window.history && window.history.replaceState) {
window.history.replaceState(window.history.state, document.title, window.location.pathname)
} else {
document.location.hash = '' // this is a fallback for IE < 10
}
if (token) {
localStorage.setItem('ello_access_token', token)
} else {
// TODO: protocol, hostname, <port>, scope, client_id are all ENVs?
const url = 'https://' + ENV.AUTH_DOMAIN + '/api/oauth/authorize.html' +
'?response_type=token' +
'&scope=web_app' +
'&client_id=' + ENV.AUTH_CLIENT_ID +
'&redirect_uri=' + ENV.AUTH_REDIRECT_URI;
window.location.href = url;
}
}
window.resetAuth = () => {
const token = localStorage.getItem('ello_access_token');
if (token) {
localStorage.removeItem('ello_access_token');
window.checkAuth()
}
}
window.checkAuth()
|
window.extractToken = (hash) => {
const match = hash.match(/access_token=(\w+)/);
let token = !!match && match[1];
if (!token) {
token = localStorage.getItem('ello_access_token');
}
return token;
}
window.checkAuth = () => {
const token = extractToken(document.location.hash);
window.history.replaceState(window.history.state, document.title, window.location.pathname)
document.location.hash = '' // this is a fallback for IE < 10
if (token) {
localStorage.setItem('ello_access_token', token)
} else {
// TODO: protocol, hostname, <port>, scope, client_id are all ENVs?
const url = 'https://' + ENV.AUTH_DOMAIN + '/api/oauth/authorize.html' +
'?response_type=token' +
'&scope=web_app' +
'&client_id=' + ENV.AUTH_CLIENT_ID +
'&redirect_uri=' + ENV.AUTH_REDIRECT_URI;
window.location.href = url;
}
}
window.resetAuth = () => {
const token = localStorage.getItem('ello_access_token');
if (token) {
localStorage.removeItem('ello_access_token');
window.checkAuth()
}
}
window.checkAuth()
|
Support is actually py >= 35
|
import sys
from setuptools import setup
# Be verbose about Python < 3.5 being deprecated.
if sys.version_info < (3, 5):
print('\n' * 3 + '*' * 64)
print('lastcast requires Python 3.5+, and might be broken if run with\n'
'this version of Python.')
print('*' * 64 + '\n' * 3)
setup(
name='lastcast',
version='1.0.1',
description='Scrobble music to last.fm from Chromecast.',
author='Erik Price',
url='https://github.com/erik/lastcast',
packages=['lastcast'],
entry_points={
'console_scripts': [
'lastcast = lastcast:main',
],
},
license='MIT',
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Operating System :: OS Independent",
],
install_requires=[
'PyChromecast==2.0.0',
'click==6.7',
'pylast==1.7.0',
'toml==0.9.4',
]
)
|
import sys
from setuptools import setup
# Be verbose about Python < 3.4 being deprecated.
if sys.version_info < (3, 4):
print('\n' * 3 + '*' * 64)
print('lastcast requires Python 3.4+, and might be broken if run with\n'
'this version of Python.')
print('*' * 64 + '\n' * 3)
setup(
name='lastcast',
version='1.0.0',
description='Scrobble music to last.fm from Chromecast.',
author='Erik Price',
url='https://github.com/erik/lastcast',
packages=['lastcast'],
entry_points={
'console_scripts': [
'lastcast = lastcast:main',
],
},
license='MIT',
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Operating System :: OS Independent",
],
install_requires=[
'PyChromecast==2.0.0',
'click==6.7',
'pylast==1.7.0',
'toml==0.9.4',
]
)
|
Make tests work without using "this" to get the global object.
|
// Pulverize ES6 library features provided by the environment for testing
delete Object.is;
delete Object.assign;
delete Object.setPrototypeOf;
// V8 throws an error when attempting to delete these properties
try { delete Number.EPSILON } catch (x) {}
try { delete Number.MAX_SAFE_INTEGER } catch (x) {}
try { delete Number.MIN_SAFE_INTEGER } catch (x) {}
delete Math.sign;
delete Number.isInteger;
delete Number.isFinite;
delete Number.isNaN;
delete Number.isSafeInteger;
delete String.raw;
delete String.fromCodePoint;
delete String.prototype.repeat;
delete String.prototype.startsWith;
delete String.prototype.endsWith;
delete String.prototype.contains;
delete String.prototype.codePointAt;
delete String.prototype[Symbol.iterator];
delete Array.from;
delete Array.of;
delete Array.prototype.copyWithin;
delete Array.prototype.fill;
delete Array.prototype.find;
delete Array.prototype.findIndex;
delete Array.prototype.values;
delete Array.prototype.entries;
delete Array.prototype.keys;
delete Array.prototype[Symbol.iterator];
delete _es6now.global.Map;
delete _es6now.global.Promise;
|
// Pulverize ES6 library features provided by the environment for testing
delete Object.is;
delete Object.assign;
delete Object.setPrototypeOf;
// V8 throws an error when attempting to delete these properties
try { delete Number.EPSILON } catch (x) {}
try { delete Number.MAX_SAFE_INTEGER } catch (x) {}
try { delete Number.MIN_SAFE_INTEGER } catch (x) {}
delete Math.sign;
delete Number.isInteger;
delete Number.isFinite;
delete Number.isNaN;
delete Number.isSafeInteger;
delete String.raw;
delete String.fromCodePoint;
delete String.prototype.repeat;
delete String.prototype.startsWith;
delete String.prototype.endsWith;
delete String.prototype.contains;
delete String.prototype.codePointAt;
delete String.prototype[Symbol.iterator];
delete Array.from;
delete Array.of;
delete Array.prototype.copyWithin;
delete Array.prototype.fill;
delete Array.prototype.find;
delete Array.prototype.findIndex;
delete Array.prototype.values;
delete Array.prototype.entries;
delete Array.prototype.keys;
delete Array.prototype[Symbol.iterator];
delete this.Map;
delete this.Promise;
|
Change to Controller from Delegate shell
|
"""NM-Controller accounts are used to provide secure access to the XMLRPC API. They are normal Unix accounts with a shell that tunnels XMLRPC requests to the API server."""
import accounts
import logger
import tools
class Controller(accounts.Account):
SHELL = '/usr/bin/forward_api_calls' # tunneling shell
TYPE = 'controller'
@staticmethod
def create(name, vref = None):
add_shell(Controller.SHELL)
logger.log_call('/usr/sbin/useradd', '-p', '*', '-s', Controller.SHELL, name)
@staticmethod
def destroy(name): logger.log_call('/usr/sbin/userdel', '-r', name)
def add_shell(shell):
"""Add <shell> to /etc/shells if it's not already there."""
etc_shells = open('/etc/shells')
valid_shells = etc_shells.read().split()
etc_shells.close()
if shell not in valid_shells:
etc_shells = open('/etc/shells', 'a')
print >>etc_shells, shell
etc_shells.close()
|
"""NM-Controller accounts are used to provide secure access to the XMLRPC API. They are normal Unix accounts with a shell that tunnels XMLRPC requests to the API server."""
import accounts
import logger
import tools
class Controller(accounts.Account):
SHELL = '/usr/bin/forward_api_calls' # tunneling shell
TYPE = 'controller'
@staticmethod
def create(name, vref = None):
add_shell(Delegate.SHELL)
logger.log_call('/usr/sbin/useradd', '-p', '*', '-s', Delegate.SHELL, name)
@staticmethod
def destroy(name): logger.log_call('/usr/sbin/userdel', '-r', name)
def add_shell(shell):
"""Add <shell> to /etc/shells if it's not already there."""
etc_shells = open('/etc/shells')
valid_shells = etc_shells.read().split()
etc_shells.close()
if shell not in valid_shells:
etc_shells = open('/etc/shells', 'a')
print >>etc_shells, shell
etc_shells.close()
|
tests: Raise AssertionError to mark tests as failed instead of errored
|
import os
import sys
import glob
from babel.messages.pofile import read_po
import nose
def get_language_code(filename):
filename = os.path.split(filename)[0]
filename = os.path.split(filename)[0]
filename = os.path.split(filename)[1]
return filename
def test_pofiles():
for filename in glob.glob(os.path.join('skylines', 'translations', '*', 'LC_MESSAGES', 'messages.po')):
test_pofiles.func_doc = ('Python string format placeholders must match '
'(lang: {})'.format(get_language_code(filename)))
yield check_pofile, filename
def check_pofile(filename):
with open(filename) as fileobj:
catalog = read_po(fileobj)
for error in catalog.check():
print 'Error in message: ' + str(error[0])
raise AssertionError(error[1][0])
if __name__ == "__main__":
sys.argv.append(__name__)
nose.run()
|
import os
import sys
import glob
from babel.messages.pofile import read_po
import nose
def get_language_code(filename):
filename = os.path.split(filename)[0]
filename = os.path.split(filename)[0]
filename = os.path.split(filename)[1]
return filename
def test_pofiles():
for filename in glob.glob(os.path.join('skylines', 'translations', '*', 'LC_MESSAGES', 'messages.po')):
test_pofiles.func_doc = ('Python string format placeholders must match '
'(lang: {})'.format(get_language_code(filename)))
yield check_pofile, filename
def check_pofile(filename):
with open(filename) as fileobj:
catalog = read_po(fileobj)
for error in catalog.check():
print 'Error in message: ' + str(error[0])
raise error[1][0]
if __name__ == "__main__":
sys.argv.append(__name__)
nose.run()
|
Make sure the temp directory exists (otherwise error is thrown in WebpackManifest)
|
var gulp = require('gulp')
var gulpSequence = require('gulp-sequence')
var getEnabledTasks = require('../lib/getEnabledTasks')
var os = require('os')
var fs = require('fs')
var path = require('path')
var productionTask = function(cb) {
global.production = true
// Build to a temporary directory, then move compiled files as a last step
PATH_CONFIG.finalDest = PATH_CONFIG.dest
PATH_CONFIG.dest = PATH_CONFIG.temp
? path.join(process.env.PWD, PATH_CONFIG.temp)
: path.join(os.tmpdir(), 'gulp-starter');
fs.mkdirSync(PATH_CONFIG.dest);
var tasks = getEnabledTasks('production')
var rev = TASK_CONFIG.production.rev ? 'rev': false
var static = TASK_CONFIG.static ? 'static' : false
gulpSequence('clean', tasks.assetTasks, tasks.codeTasks, rev, 'size-report', static, 'replaceFiles', cb)
}
gulp.task('build', productionTask)
module.exports = productionTask
|
var gulp = require('gulp')
var gulpSequence = require('gulp-sequence')
var getEnabledTasks = require('../lib/getEnabledTasks')
var os = require('os')
var path = require('path')
var productionTask = function(cb) {
global.production = true
// Build to a temporary directory, then move compiled files as a last step
PATH_CONFIG.finalDest = PATH_CONFIG.dest
PATH_CONFIG.dest = PATH_CONFIG.temp
? path.join(process.env.PWD, PATH_CONFIG.temp)
: path.join(os.tmpdir(), 'gulp-starter');
var tasks = getEnabledTasks('production')
var rev = TASK_CONFIG.production.rev ? 'rev': false
var static = TASK_CONFIG.static ? 'static' : false
gulpSequence('clean', tasks.assetTasks, tasks.codeTasks, rev, 'size-report', static, 'replaceFiles', cb)
}
gulp.task('build', productionTask)
module.exports = productionTask
|
Use uppercase for fair sort enum
|
import { GraphQLEnumType } from 'graphql';
export default {
type: new GraphQLEnumType({
name: 'FairSorts',
values: {
CREATED_AT_ASC: {
value: 'created_at',
},
CREATED_AT_DESC: {
value: '-created_at',
},
START_AT_ASC: {
value: 'start_at',
},
START_AT_DESC: {
value: '-start_at',
},
NAME_ASC: {
value: 'name',
},
NAME_DESC: {
value: '-name',
},
},
}),
};
|
import { GraphQLEnumType } from 'graphql';
export default {
type: new GraphQLEnumType({
name: 'FairSorts',
values: {
created_at_asc: {
value: 'created_at',
},
created_at_desc: {
value: '-created_at',
},
start_at_asc: {
value: 'start_at',
},
start_at_desc: {
value: '-start_at',
},
name_asc: {
value: 'name',
},
name_desc: {
value: '-name',
},
},
}),
};
|
Add test for 'Register' button
|
import React from 'react';
import ReactDOM from 'react-dom';
import {
renderIntoDocument,
scryRenderedDOMComponentsWithTag
} from 'react-addons-test-utils';
import configureStore from '../redux/configureStore'
import RegistrationForm from './RegistrationForm'
describe('RegistrationForm', () => {
it('renders inputs for user registration', () => {
const store = configureStore()
const component = renderIntoDocument(
<RegistrationForm store={store} />
);
const renderedDOM = ReactDOM.findDOMNode(component)
const inputs = renderedDOM.querySelectorAll('input')
expect(inputs.length).toEqual(2)
expect(inputs[0]).toBeDefined()
expect(inputs[0].name).toEqual('userName')
expect(inputs[1]).toBeDefined()
expect(inputs[1].name).toEqual('email')
const buttons = scryRenderedDOMComponentsWithTag(component, 'button');
expect(buttons.length).toEqual(1);
expect(buttons[0].textContent).toEqual('Register');
})
})
|
import React from 'react';
import ReactDOM from 'react-dom';
import {
renderIntoDocument,
scryRenderedDOMComponentsWithTag
} from 'react-addons-test-utils';
import configureStore from '../redux/configureStore'
import RegistrationForm from './RegistrationForm'
describe('RegistrationForm', () => {
it('renders inputs for user registration', () => {
const store = configureStore()
const component = renderIntoDocument(
<RegistrationForm store={store} />
);
const renderedDOM = ReactDOM.findDOMNode(component)
const inputs = renderedDOM.querySelectorAll('input')
expect(inputs.length).toEqual(3)
expect(inputs[0]).toBeDefined()
expect(inputs[0].name).toEqual('userName')
expect(inputs[1]).toBeDefined()
expect(inputs[1].name).toEqual('email')
expect(inputs[2]).toBeDefined()
expect(inputs[2].name).toEqual('phone')
})
})
|
Implement Icon.update() for ComponentWidget fix
|
/**
* brightwheel
*
* Copyright © 2016 Allen Smith <loranallensmith@github.com>. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
/** @jsx etch.dom */
import etch from 'etch';
import classNames from 'classnames';
import BrightwheelComponent from './brightwheel-component';
class Icon extends BrightwheelComponent {
constructor(properties, children) {
// Construct a basic BrightwheelComponent from the parameters given
super(properties, children)
// Set a default icon if unspecified
if(this.properties.icon === undefined) {
this.properties.icon = 'help-circled';
}
// Reinitialize component
etch.initialize(this);
}
render() {
let classes = classNames(
'icon',
`icon-${this.properties.icon}`,
this.properties.classNames
);
return (<span {...this.properties.attributes} className={classes}></span>);
}
update(properties, children) {
this.properties = properties;
this.children = children;
return etch.update(this);
}
}
export default Icon;
|
/**
* brightwheel
*
* Copyright © 2016 Allen Smith <loranallensmith@github.com>. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
/** @jsx etch.dom */
import etch from 'etch';
import classNames from 'classnames';
import BrightwheelComponent from './brightwheel-component';
class Icon extends BrightwheelComponent {
constructor(properties, children) {
// Construct a basic BrightwheelComponent from the parameters given
super(properties, children)
// Set a default icon if unspecified
if(this.properties.icon === undefined) {
this.properties.icon = 'help-circled';
}
// Reinitialize component
etch.initialize(this);
}
render() {
let classes = classNames(
'icon',
`icon-${this.properties.icon}`,
this.properties.classNames
);
return (<span {...this.properties.attributes} className={classes}></span>);
}
}
export default Icon;
|
[core] GraphQL: Remove in-line mock data when testing graphql list CLI command
|
module.exports = async function listApisAction(args, context) {
const {apiClient, output, chalk} = context
const client = apiClient({
requireUser: true,
requireProject: true
})
let endpoints
try {
endpoints = await client.request({
url: `/apis/graphql`,
method: 'GET'
})
} catch (err) {
if (err.statusCode === 404) {
endpoints = []
} else {
throw err
}
}
if (endpoints && endpoints.length > 0) {
output.print('Here are the GraphQL endpoints deployed for this project:')
endpoints.forEach((endpoint, index) => {
output.print(`${index + 1}. ${chalk.bold('Dataset:')} ${endpoint.dataset}`)
output.print(` ${chalk.bold('Tag:')} ${endpoint.tag}`)
output.print(` ${chalk.bold('Generation:')} ${endpoint.generation}`)
output.print(` ${chalk.bold('Playground:')} ${endpoint.playgroundEnabled}\n`)
})
}
output.print("This project doesn't have any GraphQL endpoints deployed.")
}
|
module.exports = async function listApisAction(args, context) {
const {apiClient, output, chalk} = context
const client = apiClient({
requireUser: true,
requireProject: true
})
let endpoints
try {
endpoints = await client.request({
url: `/apis/graphql`,
method: 'GET'
})
} catch (err) {
if (err.statusCode === 404) {
endpoints = []
} else {
throw err
}
}
endpoints = [{
dataset: 'production',
tag: 'default',
generation: 'gen1',
playgroundEnabled: false
}, {
dataset: 'staging',
tag: 'next',
generation: 'gen2',
playgroundEnabled: true
}]
if (endpoints && endpoints.length > 0) {
output.print('Here are the GraphQL endpoints deployed for this project:')
endpoints.forEach((endpoint, index) => {
output.print(`${index + 1}. ${chalk.bold('Dataset:')} ${endpoint.dataset}`)
output.print(` ${chalk.bold('Tag:')} ${endpoint.tag}`)
output.print(` ${chalk.bold('Generation:')} ${endpoint.generation}`)
output.print(` ${chalk.bold('Playground:')} ${endpoint.playgroundEnabled}\n`)
})
}
output.print("This project doesn't have any GraphQL endpoints deployed.")
}
|
Use application context for analytics provider
|
package com.alexstyl.specialdates.analytics;
import android.content.Context;
import com.alexstyl.specialdates.common.BuildConfig;
import com.mixpanel.android.mpmetrics.MixpanelAPI;
public class AnalyticsProvider {
private static Analytics ANALYTICS;
public static Analytics getAnalytics(Context context) {
if (ANALYTICS == null) {
ANALYTICS = createMixpanelAnalytics(context.getApplicationContext());
}
return ANALYTICS;
}
private static Analytics createMixpanelAnalytics(Context context) {
String projectToken = BuildConfig.MIXPANEL_TOKEN;
MixpanelAPI mixpanel = MixpanelAPI.getInstance(context, projectToken);
return new MixPanel(mixpanel);
}
}
|
package com.alexstyl.specialdates.analytics;
import android.content.Context;
import com.alexstyl.specialdates.common.BuildConfig;
import com.mixpanel.android.mpmetrics.MixpanelAPI;
public class AnalyticsProvider {
private static Analytics ANALYTICS;
public static Analytics getAnalytics(Context context) {
if (ANALYTICS == null) {
ANALYTICS = createMixpanelAnalytics(context);
}
return ANALYTICS;
}
private static Analytics createMixpanelAnalytics(Context context) {
String projectToken = BuildConfig.MIXPANEL_TOKEN;
MixpanelAPI mixpanel = MixpanelAPI.getInstance(context, projectToken);
return new MixPanel(mixpanel);
}
}
|
DRILL-3819: Remove redundant check to ignore files beginning with '.'
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.drill.exec.store.dfs;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.Utils;
public class DrillPathFilter extends Utils.OutputFileUtils.OutputFilesFilter {
@Override
public boolean accept(Path path) {
if (path.getName().startsWith(DrillFileSystem.HIDDEN_FILE_PREFIX)) {
return false;
}
if (path.getName().startsWith(DrillFileSystem.DOT_FILE_PREFIX)) {
return false;
}
return super.accept(path);
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.drill.exec.store.dfs;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.Utils;
public class DrillPathFilter extends Utils.OutputFileUtils.OutputFilesFilter {
@Override
public boolean accept(Path path) {
if (path.getName().startsWith(DrillFileSystem.HIDDEN_FILE_PREFIX)) {
return false;
}
if (path.getName().startsWith(DrillFileSystem.DOT_FILE_PREFIX)) {
return false;
}
if (path.getName().startsWith(".")) {
return false;
}
return super.accept(path);
}
}
|
Use the common mailer in the sendQueuedEmails cronjob
|
<?php
namespace Backend\Core\Cronjobs;
/*
* This file is part of Fork CMS.
*
* For the full copyright and license information, please view the license
* file that was distributed with this source code.
*/
use Backend\Core\Engine\Base\Cronjob;
use Common\Mailer;
/**
* This is the cronjob to send the queued emails.
*
* @author Tijs Verkoyen <tijs@sumocoders.be>
* @author Davy Hellemans <davy@spoon-library.com>
*/
class BackendCoreCronjobSendQueuedEmails extends Cronjob
{
/**
* Execute the action
*/
public function execute()
{
// set busy file
$this->setBusyFile();
// send all queued e-mails
$mailer = $this->get('mailer');
foreach ($mailer->getQueuedMailIds() as $id) {
$mailer->send($id);
}
// remove busy file
$this->clearBusyFile();
}
}
|
<?php
namespace Backend\Core\Cronjobs;
/*
* This file is part of Fork CMS.
*
* For the full copyright and license information, please view the license
* file that was distributed with this source code.
*/
use Backend\Core\Engine\Base\Cronjob;
use Backend\Core\Engine\Mailer;
/**
* This is the cronjob to send the queued emails.
*
* @author Tijs Verkoyen <tijs@sumocoders.be>
* @author Davy Hellemans <davy@spoon-library.com>
*/
class BackendCoreCronjobSendQueuedEmails extends Cronjob
{
/**
* Execute the action
*/
public function execute()
{
// set busy file
$this->setBusyFile();
// send all queued e-mails
foreach (Mailer::getQueuedMailIds() as $id) {
Mailer::send($id);
}
// remove busy file
$this->clearBusyFile();
}
}
|
Add trace logs for response duration
|
'use strict';
var http = require('http');
var config = require('./lib/configLoader');
var urlUtils = require('./lib/urlUtils');
var api = require('./lib/api');
var logger = config.logger;
process.on('uncaughtException', function(err) {
logger.error('Uncaught exception: %s', JSON.stringify(err, null, 4));
});
api.initChangesSync();
http.createServer(function(req, resp) {
try {
var startDate = Date.now();
var isGet = req.method === 'GET';
var module = urlUtils.module(req.url);
var tarball = urlUtils.tarball(req.url);
if (isGet && tarball) {
api.manageAttachment(req, resp, tarball);
} else if (isGet && module) {
api.manageModule(req, resp, module);
} else {
api.proxyToCentralRepository(req, resp);
}
resp.on('finish', function() {
logger.trace('%s: response in %sms', req.url, Date.now() - startDate);
});
} catch (error) {
logger.error(error);
}
}).listen(config.port, function() {
logger.info('Server running at http://localhost:%s with config:\n%s', config.port, JSON.stringify(config, null, 4));
});
|
'use strict';
var http = require('http');
var config = require('./lib/configLoader');
var urlUtils = require('./lib/urlUtils');
var api = require('./lib/api');
var logger = config.logger;
process.on('uncaughtException', function(err) {
logger.error('Uncaught exception: %s', JSON.stringify(err, null, 4));
});
api.initChangesSync();
http.createServer(function(req, resp) {
try {
var isGet = req.method === 'GET';
var module = urlUtils.module(req.url);
var tarball = urlUtils.tarball(req.url);
if (isGet && tarball) {
api.manageAttachment(req, resp, tarball);
} else if (isGet && module) {
api.manageModule(req, resp, module);
} else {
api.proxyToCentralRepository(req, resp);
}
} catch (error) {
logger.error(error);
}
}).listen(config.port, function() {
logger.info('Server running at http://localhost:%s with config:\n%s', config.port, JSON.stringify(config, null, 4));
});
|
Extend test code to verify behaviour of vaults with transactions
|
package node.company;
import java.util.Map;
import org.joda.time.DateTime;
import data.trainnetwork.BookableSection;
import transaction.FailedTransactionException;
import transaction.TransactionContent;
import transaction.Vault;
public abstract class TransactionContentGenerator extends TransactionContent<String, Vault<BookableSection>> {
/**
*
*/
private static final long serialVersionUID = 3685066724312335230L;
public static TransactionContent<String, Vault<BookableSection>> getTestContent() {
TransactionContent<String, Vault<BookableSection>> c
= new TransactionContent<String, Vault<BookableSection>>() {
private static final long serialVersionUID = -8167406104784795108L;
@Override
public void run() throws FailedTransactionException {
BookableSection s = new BookableSection("section", 1, DateTime.now(), 10, 10);
System.out.println("EXECUTING");
Map <String, Vault<BookableSection>> _data = (Map<String, Vault<BookableSection>>) manager.writeLock(new Vault(data));
_data.put(s.getID(), new Vault<BookableSection>(s));
}
};
return c;
}
}
|
package node.company;
import org.joda.time.DateTime;
import data.trainnetwork.BookableSection;
import transaction.FailedTransactionException;
import transaction.TransactionContent;
import transaction.Vault;
public abstract class TransactionContentGenerator extends TransactionContent<String, Vault<BookableSection>> {
/**
*
*/
private static final long serialVersionUID = 3685066724312335230L;
public static TransactionContent<String, Vault<BookableSection>> getTestContent() {
TransactionContent<String, Vault<BookableSection>> c
= new TransactionContent<String, Vault<BookableSection>>() {
private static final long serialVersionUID = -8167406104784795108L;
@Override
public void run() throws FailedTransactionException {
BookableSection s = new BookableSection("section", 1, DateTime.now(), 10, 10);
System.out.println("EXECUTING");
data.put(s.getID(), new Vault<BookableSection>(s));
}
};
return c;
}
}
|
JasonLeyba: Remove unnecessary modifiers and cleanup whitespace.
git-svn-id: aa1aa1384423cb28c2b1e29129bb3a91de1d9196@12481 07704840-8298-11de-bf8c-fd130f914ac9
|
/*
Copyright 2007-2009 WebDriver committers
Copyright 2007-2009 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 org.openqa.selenium.lift;
import org.hamcrest.Matcher;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.lift.find.Finder;
/**
* Interface for objects that provide a context (maintaining any state) for web tests.
* @author rchatley (Robert Chatley)
*
*/
public interface TestContext {
void goTo(String url);
void assertPresenceOf(Finder<WebElement, WebDriver> finder);
void assertPresenceOf(Matcher<Integer> cardinalityConstraint,
Finder<WebElement, WebDriver> finder);
void type(String input, Finder<WebElement, WebDriver> finder);
void clickOn(Finder<WebElement, WebDriver> finder);
void waitFor(Finder<WebElement, WebDriver> finder, long timeout);
void quit();
}
|
/*
Copyright 2007-2009 WebDriver committers
Copyright 2007-2009 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 org.openqa.selenium.lift;
import org.hamcrest.Matcher;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.lift.find.Finder;
/**
* Interface for objects that provide a context (maintaining any state) for web tests.
* @author rchatley (Robert Chatley)
*
*/
public interface TestContext {
public abstract void goTo(String url);
public abstract void assertPresenceOf(Finder<WebElement, WebDriver> finder);
public abstract void assertPresenceOf(
Matcher<Integer> cardinalityConstraint,
Finder<WebElement, WebDriver> finder);
public abstract void type(String input, Finder<WebElement, WebDriver> finder);
public abstract void clickOn(Finder<WebElement, WebDriver> finder);
public abstract void waitFor(Finder<WebElement, WebDriver> finder, long timeout);
public abstract void quit();
}
|
Fix a debug line in a test lib
|
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Iterator, Dict
from lib.constants import SRC
from lib.pipeline import DataPipeline
def get_pipeline_names() -> Iterator[str]:
""" Iterator with all the names of available data pipelines """
for item in (SRC / "pipelines").iterdir():
if not item.name.startswith("_") and not item.is_file():
yield item.name
def get_table_names() -> Iterator[str]:
""" Iterator with all the available table names """
for pipeline_name in get_pipeline_names():
yield pipeline_name.replace("_", "-")
def get_pipelines() -> Iterator[DataPipeline]:
""" Iterator with all the available data pipelines """
for pipeline_name in get_pipeline_names():
yield DataPipeline.load(pipeline_name)
def get_schema() -> Dict[str, type]:
""" Outputs all known column schemas """
schema: Dict[str, type] = {}
for pipeline in get_pipelines():
schema.update(pipeline.schema)
return schema
|
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Iterator, Dict
from lib.constants import SRC
from lib.pipeline import DataPipeline
def get_pipeline_names() -> Iterator[str]:
""" Iterator with all the names of available data pipelines """
for item in (SRC / "pipelines").iterdir():
if not item.name.startswith("_") and not item.is_file() and item.name == "epidemiology":
yield item.name
def get_table_names() -> Iterator[str]:
""" Iterator with all the available table names """
for pipeline_name in get_pipeline_names():
yield pipeline_name.replace("_", "-")
def get_pipelines() -> Iterator[DataPipeline]:
""" Iterator with all the available data pipelines """
for pipeline_name in get_pipeline_names():
yield DataPipeline.load(pipeline_name)
def get_schema() -> Dict[str, type]:
""" Outputs all known column schemas """
schema: Dict[str, type] = {}
for pipeline in get_pipelines():
schema.update(pipeline.schema)
return schema
|
Split out an inner loop into a separate function.
|
var csv = require('ya-csv');
function documentsToCsv(writer, handlerName, documents) {
var csvWriter = new csv.CsvWriter(writer);
(documents || []).forEach(function (doc) {
var rows = documentToRows(handlerName, doc);
rows.forEach(function (row) {
csvWriter.writeRecord(row);
});
});
}
function documentToRows(handlerName, doc) {
var rows = [];
(doc[handlerName] || []).forEach(function (entryObject) {
var row = objectToRow(entryObject);
row.unshift(doc._id);
rows.push(row);
});
return rows;
}
function objectToRow(entryObject) {
var row = [];
Object.keys(entryObject).forEach(function (prop) {
row.push(entryObject[prop]);
});
return row;
}
module.exports = documentsToCsv;
|
var csv = require('ya-csv');
function documentsToCsv(writer, handlerName, documents) {
var csvWriter = new csv.CsvWriter(writer);
(documents || []).forEach(function (doc) {
var entries = doc[handlerName];
entries.forEach(function (entryObject) {
var row = objectToRow(entryObject);
row.unshift(doc._id);
csvWriter.writeRecord(row);
});
});
}
function objectToRow(entryObject) {
var row = [];
Object.keys(entryObject).forEach(function (prop) {
row.push(entryObject[prop]);
});
return row;
}
module.exports = documentsToCsv;
|
Return to old setting of repetitions for fast testing
|
import unittest
try:
import spotpy
except ImportError:
import sys
sys.path.append(".")
import spotpy
from spotpy.examples.spot_setup_hymod_python import spot_setup
class TestFast(unittest.TestCase):
def setUp(self):
self.spot_setup = spot_setup()
self.rep = 200 # REP must be a multiply of amount of parameters which are in 7 if using hymod
self.timeout = 10 # Given in Seconds
def test_fast(self):
sampler = spotpy.algorithms.fast(self.spot_setup, parallel="seq", dbname='test_FAST', dbformat="ram",
sim_timeout=self.timeout)
results = []
sampler.sample(self.rep)
results = sampler.getdata()
self.assertEqual(203,len(results))
if __name__ == '__main__':
unittest.main()
|
import unittest
try:
import spotpy
except ImportError:
import sys
sys.path.append(".")
import spotpy
from spotpy.examples.spot_setup_hymod_python import spot_setup
class TestFast(unittest.TestCase):
def setUp(self):
self.spot_setup = spot_setup()
self.rep = 200 # REP must be a multiply of amount of parameters which are in 7 if using hymod
self.timeout = 10 # Given in Seconds
def test_fast(self):
sampler = spotpy.algorithms.fast(self.spot_setup, parallel="seq", dbname='test_FAST', dbformat="ram",
sim_timeout=self.timeout)
results = []
sampler.sample(self.rep)
results = sampler.getdata()
self.assertEqual(200,len(results))
if __name__ == '__main__':
unittest.main()
|
Add canonical import paths to storage packages
The comment will ensure that only imports with
this path will compile.This is needed to make sure
that the vanity url k8s.io is used as the import path
instead of github.com.
See https://golang.org/doc/go1.4#canonicalimports
for more details.
|
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// +k8s:conversion-gen=k8s.io/kubernetes/pkg/apis/storage
// +k8s:conversion-gen-external-types=k8s.io/api/storage/v1
// +groupName=storage.k8s.io
// +k8s:defaulter-gen=TypeMeta
// +k8s:defaulter-gen-input=../../../../vendor/k8s.io/api/storage/v1
package v1 // import "k8s.io/kubernetes/pkg/apis/storage/v1"
|
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// +k8s:conversion-gen=k8s.io/kubernetes/pkg/apis/storage
// +k8s:conversion-gen-external-types=k8s.io/api/storage/v1
// +groupName=storage.k8s.io
// +k8s:defaulter-gen=TypeMeta
// +k8s:defaulter-gen-input=../../../../vendor/k8s.io/api/storage/v1
package v1
|
Use pathlib in the filter
|
#!/usr/bin/env python
import json
import sys
from pathlib import Path
from os import remove
from datetime import datetime
START_DT = datetime(2016, 7, 1, 0, 0, 0)
END_DT = datetime(2016, 12, 1, 0, 0, 0)
DRY_RUN = True
for path in Path('preprocessed/').iterdir():
with path.open() as f:
# read the json into d
try:
d = json.load(f)
except:
print('[Error]', path, sep='\t', file=sys.stderr)
continue
# decide keep or remove
authores_dt = datetime.fromtimestamp(d['authored_ts'])
# print [DATETIME] path KEEP|REMOVE DRY_RUN?
print(authores_dt, path, sep='\t', end='\t')
if START_DT <= authores_dt < END_DT:
print('KEEP')
else:
if DRY_RUN:
print('REMOVE', 'DRY_RUN', sep='\t')
else:
print('REMOVE', sep='\t')
remove(str(path))
|
#!/usr/bin/env python
import json
import sys
from os import scandir, remove
from datetime import datetime
START_DT = datetime(2016, 7, 1, 0, 0, 0)
END_DT = datetime(2016, 12, 1, 0, 0, 0)
DRY_RUN = True
for dir_entry in scandir('preprocessed'):
path = dir_entry.path
with open(path) as f:
# read the json into d
try:
d = json.load(f)
except:
print('[Error]', path, sep='\t', file=sys.stderr)
continue
# decide keep or remove
authores_dt = datetime.fromtimestamp(d['authored_ts'])
# print [DATETIME] path KEEP|REMOVE DRY_RUN?
print(authores_dt, path, sep='\t', end='\t')
if START_DT <= authores_dt < END_DT:
print('KEEP')
else:
if DRY_RUN:
print('REMOVE', 'DRY_RUN', sep='\t')
else:
print('REMOVE', sep='\t')
remove(path)
|
Rename functions to match APC functions
|
<?php
class Better_PHP_Cache
{
public function __construct()
{
}
public function store($entry_name, $entry_value, $time_to_live)
{
if(!($entry_name && $entry_value && $time_to_live))
{
return FALSE;
}
return apc_store($entry_name, $entry_value, $time_to_live);
}
public function fetch($entry_name)
{
if(!$entry_name)
{
return FALSE;
}
return apc_fetch($entry_name);
}
public function delete($entry_name)
{
}
}
?>
|
<?php
class Better_PHP_Cache
{
public function __construct()
{
}
public function add($entry_name, $entry_value, $time_to_live)
{
if(!($entry_name && $entry_value && $time_to_live))
{
return FALSE;
}
return apc_store($entry_name, $entry_value, $time_to_live);
}
public function get($entry_name)
{
if(!$entry_name)
{
return FALSE;
}
return apc_fetch($entry_name);
}
public function delete($entry_name)
{
}
}
?>
|
Update sqsadaptor test to match implementation
|
package sqsadaptor
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
func init() {
}
func TestAdaptorConstruction(t *testing.T) {
testsqs := NewSQSAdaptor("testqueue")
assert.Equal(t, testsqs.QueueURL, "testqueue")
}
func TestJSON(t *testing.T) {
result := Result{
"2016-01-01 10:00:00",
"example.com",
"Fetch",
200,
int64(12345), // elapsed, first byte
int64(6789), // elapsed, last byte
int64(4567), // elapsed, total
4711, //bytes
"Success",
"aws-lambda-4711", // AWS lamba instance
}
str, jsonerr := jsonFromResult(result)
if jsonerr != nil {
fmt.Println("JSON error")
return
}
assert.Equal(t, str, "{\"time\":\"2016-01-01 10:00:00\",\"host\":\"example.com\",\"type\":\"Fetch\",\"status\":200,\"elapsed-first-byte\":12345,\"elapsed-last-byte\":6789,\"elapsed\":4567,\"bytes\":4711,\"state\":\"Success\",\"instance\":\"aws-lambda-4711\"}")
}
|
package sqsadaptor
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
func init() {
}
func TestAdaptorConstruction(t *testing.T) {
testsqs := NewSQSAdaptor("testqueue")
assert.Equal(t, testsqs.QueueURL, "testqueue")
}
func TestJSON(t *testing.T) {
result := Result{
"2016-01-01 10:00:00",
"example.com",
"Fetch",
"928429348",
200,
238947,
2398,
"Finished",
}
str, jsonerr := jsonFromResult(result)
if jsonerr != nil {
fmt.Println("JSON error")
return
}
assert.Equal(t, str, "{\"time\":\"2016-01-01 10:00:00\",\"host\":\"example.com\",\"type\":\"Fetch\",\"requestID\":\"928429348\",\"status\":200,\"elapsed\":238947,\"bytes\":2398,\"state\":\"Finished\"}")
}
|
Add to first on add button clicked
|
function randomId() {
return 'v-' + Math.random().toString(36).slice(-8);
}
function prepareMxDbmsProductVue(data) {
return new Vue({
el: '#mx_dbms_product_form',
data: data,
methods: {
addDataType: function() {
this.$data.data_types.splice(0, 0, { id: randomId(), name: '', sizable: false, scalable: false, use_by_default: false });
},
removeDataType: function(dataType) {
this.$data.data_types.$remove(dataType.$index);
},
duplicateDataType: function(dataType) {
var data = dataType.$data.data_type;
this.$data.data_types.splice(dataType.$index + 1, 0, { id: randomId(), name: data.name, sizable: data.sizable, scalable: data.scalable, use_by_default: data.use_by_default });
}
}
});
}
|
function randomId() {
return 'v-' + Math.random().toString(36).slice(-8);
}
function prepareMxDbmsProductVue(data) {
return new Vue({
el: '#mx_dbms_product_form',
data: data,
methods: {
addDataType: function() {
this.$data.data_types.push({ id: randomId(), name: '', sizable: false, scalable: false, use_by_default: false });
},
removeDataType: function(dataType) {
this.$data.data_types.$remove(dataType.$index);
},
duplicateDataType: function(dataType) {
var data = dataType.$data.data_type;
this.$data.data_types.splice(dataType.$index + 1, 0, { id: randomId(), name: data.name, sizable: data.sizable, scalable: data.scalable, use_by_default: data.use_by_default });
}
}
});
}
|
Send notification to client if their job dies
|
const config = require('../../config.js');
const {job, logger, websocket} = config;
const utils = require('../../utils');
module.exports = {
//finds users in the waiting list not in the request list and deletes their jobs
"pre-request": async (ctx, next) => {
const {requestState, waitingState} = ctx;
for (let id in waitingState) {
if (!requestState[id]) { //user in waiting is not in the requests
logger.debug(`Stopping job of user ${id}`); //core-hmi-${id}
const jobName = await job.idToJobName(id);
await utils.stopJob(jobName, true); //purge the job from Nomad
//inform the client that the job is now gone
const msgObj = {
type: "dead",
data: {}
};
await websocket.send(id, JSON.stringify(msgObj));
}
}
next();
}
}
|
const config = require('../../config.js');
const {job, logger} = config;
const utils = require('../../utils');
module.exports = {
//finds users in the waiting list not in the request list and deletes their jobs
"pre-request": async (ctx, next) => {
const {requestState, waitingState} = ctx;
for (let id in waitingState) {
if (!requestState[id]) { //user in waiting is not in the requests
logger.debug(`Stopping job of user ${id}`); //core-hmi-${id}
const jobName = await job.idToJobName(id);
await utils.stopJob(jobName, true); //purge the job from Nomad
}
}
next();
}
}
|
Use 340x260 For displaying the YouTube player.
|
PostStreamLinkYoutube = {
autoplay: 1,
width: '340',
height: '260',
color: "#FFFFFF",
play: function(video_key, id) {
// remove any videos that are playing
$$('.post_stream_video').each(function(layer) { layer.update(); layer.hide(); });
// display the video thumbnails
$$('.post_stream_thumbnail').invoke('show');
$('post_stream_thumbnail_' + id).hide();
layer_id = "post_stream_video_" + id
container_id = "youtube_video_" + id
$(layer_id).show();
$(layer_id).insert( '<div id="' + container_id + '"></div>' );
swfobject.embedSWF(PostStreamLinkYoutube.youtubeVideoUrl(video_key), container_id, PostStreamLinkYoutube.width, PostStreamLinkYoutube.height, '8', '/javascripts/swfobject/plugins/expressInstall.swf', {}, {wmode: 'transparent', quality: 'hight'}, {style: 'outline : none'}, false);
},
youtubeVideoUrl: function(video_key) {
return "http://www.youtube.com/v/" + video_key + "&rel=0&autoplay=" + PostStreamLinkYoutube.autoplay;
}
}
|
PostStreamLinkYoutube = {
autoplay: 1,
width: '400',
height: '300',
color: "#FFFFFF",
play: function(video_key, id) {
// remove any videos that are playing
$$('.post_stream_video').each(function(layer) { layer.update(); layer.hide(); });
// display the video thumbnails
$$('.post_stream_thumbnail').invoke('show');
$('post_stream_thumbnail_' + id).hide();
layer_id = "post_stream_video_" + id
container_id = "youtube_video_" + id
$(layer_id).show();
$(layer_id).insert( '<div id="' + container_id + '"></div>' );
swfobject.embedSWF(PostStreamLinkYoutube.youtubeVideoUrl(video_key), container_id, PostStreamLinkYoutube.width, PostStreamLinkYoutube.height, '8', '/javascripts/swfobject/plugins/expressInstall.swf', {}, {wmode: 'transparent', quality: 'hight'}, {style: 'outline : none'}, false);
},
youtubeVideoUrl: function(video_key) {
return "http://www.youtube.com/v/" + video_key + "&rel=0&autoplay=" + PostStreamLinkYoutube.autoplay;
}
}
|
Use subscripts for provided methods.
|
<?php
namespace Pippin;
use ArrayAccess;
final class IPN implements ArrayAccess {
private $data = [];
public function __construct($data) {
$this->data = $data;
}
private function getDataValueOrNull($key) {
if (array_key_exists($key, $this->data)) {
return $this->data[$key];
}
return null;
}
public function getPayerEmail() {
return $this['payer_email'];
}
public function getReceiverEmail() {
return $this['receiver_email'];
}
public function getTransactionId() {
return $this['txn_id'];
}
// ---
public function offsetSet($key, $value) {
throw RuntimeException('offsetSet is unavailable for IPN, as it represents an immutable data type.');
}
public function offsetExists($key) {
return isset($this->data[$key]);
}
public function offsetUnset($key) {
throw RuntimeException('offsetUnset is unavailable for IPN, as it represents an immutable data type.');
}
public function offsetGet($key) {
return $this->getDataValueOrNull($key);
}
}
|
<?php
namespace Pippin;
use ArrayAccess;
final class IPN implements ArrayAccess {
private $data = [];
public function __construct($data) {
$this->data = $data;
}
private function getDataValueOrNull($key) {
if (array_key_exists($key, $this->data)) {
return $this->data[$key];
}
return null;
}
public function getPayerEmail() {
return $this->getDataValueOrNull('payer_email');
}
public function getReceiverEmail() {
return $this->getDataValueOrNull('receiver_email');
}
public function getTransactionId() {
return $this->getDataValueOrNull('txn_id');
}
// ---
public function offsetSet($key, $value) {
throw RuntimeException('offsetSet is unavailable for IPN, as it represents an immutable data type.');
}
public function offsetExists($key) {
return isset($this->data[$key]);
}
public function offsetUnset($key) {
throw RuntimeException('offsetUnset is unavailable for IPN, as it represents an immutable data type.');
}
public function offsetGet($key) {
return $this->getDataValueOrNull($key);
}
}
|
Make eyes and mouths required
|
module.exports = [
{
id: 'Hairstyles',
required: false,
sortOrder: 1
},
{
id: 'Beards',
required: false,
sortOrder: 4
},
{
id: 'Body',
required: true,
sortOrder: 0
},
{
id: 'Glasses',
required: false,
sortOrder: 2
},
{
id: 'Scarfes',
required: false,
sortOrder: 3
},
{
id: 'Shirts',
required: false,
sortOrder: 1
},
{
id: 'Tie',
required: false,
sortOrder: 2
},
{
id: 'Eyes',
required: true,
sortOrder: 1
},
{
id: 'Jackets',
required: false,
sortOrder: 1
},
{
id: 'Mouths',
required: true,
sortOrder: 1
}
];
|
module.exports = [
{
id: 'Hairstyles',
required: false,
sortOrder: 1
},
{
id: 'Beards',
required: false,
sortOrder: 4
},
{
id: 'Body',
required: true,
sortOrder: 0
},
{
id: 'Glasses',
required: false,
sortOrder: 2
},
{
id: 'Scarfes',
required: false,
sortOrder: 3
},
{
id: 'Shirts',
required: false,
sortOrder: 1
},
{
id: 'Tie',
required: false,
sortOrder: 2
},
{
id: 'Eyes',
required: false,
sortOrder: 1
},
{
id: 'Jackets',
required: false,
sortOrder: 1
},
{
id: 'Mouths',
required: false,
sortOrder: 1
}
];
|
Use a reduce instead of forEach
|
const check = require('validator').check
const db = require('../lib/db');
const Issuers = db.table('issuers', {
fields: [
'id',
'slug',
'name',
'url',
'description',
'email',
'imageId'
],
});
Issuers.validateRow = function (row) {
return this.fields.reduce(function (errors, field) {
try {
const validator = validation[field] || noop
validator(row[field])
}
catch(e) {
e.field = field
errors.push(e)
}
return errors
}, [])
}
const validation = {
id: function (id) {
if (typeof id == 'undefined') return;
check(id).isInt();
},
slug: function (slug) {
check(slug).len(1, 50);
},
name: function (name) {
check(name).len(1, 50);
},
url: function (url) {
check(url).isUrl();
},
description: function (desc) {
check(desc).len(0, 255);
},
email: function (email) {
if (typeof email == 'undefined') return;
check(email).isEmail();
},
}
function noop() {}
exports = module.exports = Issuers;
|
const check = require('validator').check
const db = require('../lib/db');
const Issuers = db.table('issuers', {
fields: [
'id',
'slug',
'name',
'url',
'description',
'email',
'imageId'
],
});
Issuers.validateRow = function (row) {
const errors = []
this.fields.forEach(function (field) {
try {
const validator = validation[field] || noop
validator(row[field])
}
catch(e) {
e.field = field
errors.push(e)
}
})
return errors
}
const validation = {
id: function (id) {
if (typeof id == 'undefined') return;
check(id).isInt();
},
slug: function (slug) {
check(slug).len(1, 50);
},
name: function (name) {
check(name).len(1, 50);
},
url: function (url) {
check(url).isUrl();
},
description: function (desc) {
check(desc).len(0, 255);
},
email: function (email) {
if (typeof email == 'undefined') return;
check(email).isEmail();
},
}
function noop() {}
exports = module.exports = Issuers;
|
Mark diviner atoms as closed in search index
Summary: Ref T4558. If a Diviner atom is a ghost (i.e. the underlying source code has been removed), mark it as closed in the search index.
Test Plan: Searched for a ghost atom in global searcn and saw the results show "Closed".
Reviewers: epriestley, #blessed_reviewers
Reviewed By: epriestley, #blessed_reviewers
Subscribers: epriestley, Korvin
Maniphest Tasks: T4558
Differential Revision: https://secure.phabricator.com/D13297
|
<?php
final class DivinerAtomSearchIndexer extends PhabricatorSearchDocumentIndexer {
public function getIndexableObject() {
return new DivinerLiveSymbol();
}
protected function buildAbstractDocumentByPHID($phid) {
$atom = $this->loadDocumentByPHID($phid);
$book = $atom->getBook();
if (!$atom->getIsDocumentable()) {
return null;
}
$doc = $this->newDocument($phid)
->setDocumentTitle($atom->getTitle())
->setDocumentCreated($book->getDateCreated())
->setDocumentModified($book->getDateModified());
$doc->addField(
PhabricatorSearchDocumentFieldType::FIELD_BODY,
$atom->getSummary());
$doc->addRelationship(
PhabricatorSearchRelationship::RELATIONSHIP_BOOK,
$atom->getBookPHID(),
DivinerBookPHIDType::TYPECONST,
PhabricatorTime::getNow());
$doc->addRelationship(
$atom->getGraphHash()
? PhabricatorSearchRelationship::RELATIONSHIP_CLOSED
: PhabricatorSearchRelationship::RELATIONSHIP_OPEN,
$atom->getBookPHID(),
DivinerBookPHIDType::TYPECONST,
PhabricatorTime::getNow());
return $doc;
}
}
|
<?php
final class DivinerAtomSearchIndexer extends PhabricatorSearchDocumentIndexer {
public function getIndexableObject() {
return new DivinerLiveSymbol();
}
protected function buildAbstractDocumentByPHID($phid) {
$atom = $this->loadDocumentByPHID($phid);
$book = $atom->getBook();
if (!$atom->getIsDocumentable()) {
return null;
}
$doc = $this->newDocument($phid)
->setDocumentTitle($atom->getTitle())
->setDocumentCreated($book->getDateCreated())
->setDocumentModified($book->getDateModified());
$doc->addField(
PhabricatorSearchDocumentFieldType::FIELD_BODY,
$atom->getSummary());
$doc->addRelationship(
PhabricatorSearchRelationship::RELATIONSHIP_BOOK,
$atom->getBookPHID(),
DivinerBookPHIDType::TYPECONST,
$book->getDateCreated());
return $doc;
}
}
|
Change moment localisation towards 2.8+ spec
Add ability to use unix timestamps as dates
|
(function (dust, moment) {
dust.helpers = dust.helpers || {};
dust.helpers.formatDate = function(chunk, context, bodies, params) {
var date = dust.helpers.tap(params.date, chunk, context);
var format = dust.helpers.tap(params.format, chunk, context);
var lan = dust.helpers.tap(params.lan, chunk, context) || 'en-US';
var timestamp = +date;
if (timestamp) {
date = timestamp;
}
moment.locale(lan);
return chunk.write(date ? moment(date).format(format) : '');
};
if (typeof exports !== 'undefined') {
module.exports = dust;
}
}(
typeof exports !== 'undefined' ? require('dustjs-linkedin') : dust,
typeof exports !== 'undefined' ? require('moment') : moment
));
|
(function (dust, moment) {
dust.helpers = dust.helpers || {};
dust.helpers.formatDate = function(chunk, context, bodies, params) {
var date = dust.helpers.tap(params.date, chunk, context);
var format = dust.helpers.tap(params.format, chunk, context);
var lan = dust.helpers.tap(params.lan, chunk, context) || 'en-US';
moment.lang(lan);
return chunk.write(date ? moment(date).format(format) : '');
};
if (typeof exports !== 'undefined') {
module.exports = dust;
}
}(
typeof exports !== 'undefined' ? require('dustjs-linkedin') : dust,
typeof exports !== 'undefined' ? require('moment') : moment
));
|
Fix for something that should've changed automatically..
|
package com.benberi.cadesim.server.model.player.vessel.impl;
import com.benberi.cadesim.server.model.player.Player;
import com.benberi.cadesim.server.model.player.vessel.CannonType;
import com.benberi.cadesim.server.model.player.vessel.Vessel;
public class Junk extends Vessel {
public Junk(Player p) {
super(p);
}
@Override
public int getID() {
return 5;
}
@Override
public int getSize() {
return 2;
}
@Override
public int getInfluenceDiameter() {
return 4;
}
@Override
public int getMaxCannons() {
return 12;
}
@Override
public boolean isDualCannon() {
return false;
}
@Override
public boolean isManuaver() {
return true;
}
@Override
public double getMaxDamage() {
return 16.66;
}
@Override
public double getRamDamage() {
return 1;
}
@Override
public CannonType getCannonType() {
return CannonType.LARGE;
}
}
|
package com.benberi.cadesim.server.model.player.vessel.impl;
import com.benberi.cadesim.server.model.player.Player;
import com.benberi.cadesim.server.model.player.vessel.CannonType;
import com.benberi.cadesim.server.model.player.vessel.Vessel;
public class WarBrig extends Vessel {
public WarBrig(Player p) {
super(p);
}
@Override
public int getID() {
return 5;
}
@Override
public int getSize() {
return 2;
}
@Override
public int getInfluenceDiameter() {
return 4;
}
@Override
public int getMaxCannons() {
return 12;
}
@Override
public boolean isDualCannon() {
return false;
}
@Override
public boolean isManuaver() {
return true;
}
@Override
public double getMaxDamage() {
return 16.66;
}
@Override
public double getRamDamage() {
return 1;
}
@Override
public CannonType getCannonType() {
return CannonType.LARGE;
}
}
|
Use existing code. Delay after delete.
* Use existing code to get the elasticsearch connection. This should
prevent tests from failing in case the way connections to
elasticsearch are made change.
* Delay a while after deleting to allow elasticsearch to re-index the
data, thus preventing subtle bugs in the test.
|
import logging
import unittest
from wqflask import app
from utility.elasticsearch_tools import get_elasticsearch_connection, get_user_by_unique_column
from elasticsearch import Elasticsearch, TransportError
class ParametrizedTest(unittest.TestCase):
def __init__(self, methodName='runTest', gn2_url="http://localhost:5003", es_url="localhost:9200"):
super(ParametrizedTest, self).__init__(methodName=methodName)
self.gn2_url = gn2_url
self.es_url = es_url
def setUp(self):
self.es = get_elasticsearch_connection()
self.es_cleanup = []
es_logger = logging.getLogger("elasticsearch")
es_logger.setLevel(app.config.get("LOG_LEVEL"))
es_logger.addHandler(
logging.FileHandler("/tmp/es_TestRegistrationInfo.log"))
es_trace_logger = logging.getLogger("elasticsearch.trace")
es_trace_logger.addHandler(
logging.FileHandler("/tmp/es_TestRegistrationTrace.log"))
def tearDown(self):
from time import sleep
self.es.delete_by_query(
index="users"
, doc_type="local"
, body={"query":{"match":{"email_address":"test@user.com"}}})
sleep(1)
|
import logging
import unittest
from wqflask import app
from elasticsearch import Elasticsearch, TransportError
class ParametrizedTest(unittest.TestCase):
def __init__(self, methodName='runTest', gn2_url="http://localhost:5003", es_url="localhost:9200"):
super(ParametrizedTest, self).__init__(methodName=methodName)
self.gn2_url = gn2_url
self.es_url = es_url
def setUp(self):
self.es = Elasticsearch([self.es_url])
self.es_cleanup = []
es_logger = logging.getLogger("elasticsearch")
es_logger.setLevel(app.config.get("LOG_LEVEL"))
es_logger.addHandler(
logging.FileHandler("/tmp/es_TestRegistrationInfo.log"))
es_trace_logger = logging.getLogger("elasticsearch.trace")
es_trace_logger.addHandler(
logging.FileHandler("/tmp/es_TestRegistrationTrace.log"))
def tearDown(self):
self.es.delete_by_query(
index="users"
, doc_type="local"
, body={"query":{"match":{"email_address":"test@user.com"}}})
|
Add godoc to Base64EncodeFileName and Base64Encode
|
package mastodon
import (
"encoding/base64"
"net/http"
"os"
)
// Base64EncodeFileName returns the base64 data URI format string of the file with the file name.
func Base64EncodeFileName(filename string) (string, error) {
file, err := os.Open(filename)
if err != nil {
return "", err
}
defer file.Close()
return Base64Encode(file)
}
// Base64Encode returns the base64 data URI format string of the file.
func Base64Encode(file *os.File) (string, error) {
fi, err := file.Stat()
if err != nil {
return "", err
}
d := make([]byte, fi.Size())
_, err = file.Read(d)
if err != nil {
return "", err
}
return "data:" + http.DetectContentType(d) +
";base64," + base64.StdEncoding.EncodeToString(d), nil
}
// String is a helper function to get the pointer value of a string.
func String(v string) *string { return &v }
|
package mastodon
import (
"encoding/base64"
"net/http"
"os"
)
func Base64EncodeFileName(filename string) (string, error) {
file, err := os.Open(filename)
if err != nil {
return "", err
}
defer file.Close()
return Base64Encode(file)
}
func Base64Encode(file *os.File) (string, error) {
fi, err := file.Stat()
if err != nil {
return "", err
}
d := make([]byte, fi.Size())
_, err = file.Read(d)
if err != nil {
return "", err
}
return "data:" + http.DetectContentType(d) +
";base64," + base64.StdEncoding.EncodeToString(d), nil
}
// String is a helper function to get the pointer value of a string.
func String(v string) *string { return &v }
|
Add ability to transform queries using QueryTraversal with full type information.
|
package graphql.util;
import graphql.PublicApi;
import java.util.Objects;
/**
* A specific {@link NodeLocation} inside a node. This means {@link #getNode()} returns a Node which has a child
* at {@link #getLocation()}
*
* A list of Breadcrumbs is used to identify the exact location of a specific node inside a tree.
*
* @param <T>
*/
@PublicApi
public class Breadcrumb<T> {
private final T node;
private final NodeLocation location;
public Breadcrumb(T node, NodeLocation location) {
this.node = node;
this.location = location;
}
public T getNode() {
return node;
}
public NodeLocation getLocation() {
return location;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Breadcrumb<?> that = (Breadcrumb<?>) o;
return Objects.equals(node, that.node) &&
Objects.equals(location, that.location);
}
@Override
public int hashCode() {
return Objects.hash(node, location);
}
@Override
public String toString() {
return super.toString();
}
}
|
package graphql.util;
import graphql.PublicApi;
import java.util.Objects;
/**
* A specific {@link NodeLocation} inside a node. This means {@link #getNode()} returns a Node which has a child
* at {@link #getLocation()}
* <p/>
* A list of Breadcrumbs is used to identify the exact location of a specific node inside a tree.
*
* @param <T>
*/
@PublicApi
public class Breadcrumb<T> {
private final T node;
private final NodeLocation location;
public Breadcrumb(T node, NodeLocation location) {
this.node = node;
this.location = location;
}
public T getNode() {
return node;
}
public NodeLocation getLocation() {
return location;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Breadcrumb<?> that = (Breadcrumb<?>) o;
return Objects.equals(node, that.node) &&
Objects.equals(location, that.location);
}
@Override
public int hashCode() {
return Objects.hash(node, location);
}
@Override
public String toString() {
return super.toString();
}
}
|
Fix carousel next and prev buttons
|
<div {!! $attributes !!}>
<ol class="carousel-indicators">
@foreach($items as $key => $item)
<li data-target="#{!! $id !!}" data-slide-to="{{$key}}" class="{{ $key == 0 ? 'active' : '' }}"></li>
@endforeach
</ol>
<div class="carousel-inner">
@foreach($items as $key => $item)
<div class="item {{ $key == 0 ? 'active' : '' }}">
<img src="{{ url($item['image']) }}" alt="{{$item['caption']}}">
<div class="carousel-caption">
{{$item['caption']}}
</div>
</div>
@endforeach
</div>
<a class="left carousel-control" href="#{!! $id !!}" data-slide="prev">
<span class="fa fa-angle-left"></span>
</a>
<a class="right carousel-control" href="#{!! $id !!}" data-slide="next">
<span class="fa fa-angle-right"></span>
</a>
</div>
|
<div {!! $attributes !!}>
<ol class="carousel-indicators">
@foreach($items as $key => $item)
<li data-target="#carousel-example-generic" data-slide-to="{{$key}}" class="{{ $key == 0 ? 'active' : '' }}"></li>
@endforeach
</ol>
<div class="carousel-inner">
@foreach($items as $key => $item)
<div class="item {{ $key == 0 ? 'active' : '' }}">
<img src="{{ url($item['image']) }}" alt="{{$item['caption']}}">
<div class="carousel-caption">
{{$item['caption']}}
</div>
</div>
@endforeach
</div>
<a class="left carousel-control" href="#carousel-example-generic" data-slide="prev">
<span class="fa fa-angle-left"></span>
</a>
<a class="right carousel-control" href="#carousel-example-generic" data-slide="next">
<span class="fa fa-angle-right"></span>
</a>
</div>
|
Fix JSLint to pass build
|
/**
* Created by i070970 on 8/26/14.
*/
(function () {
'use strict';
function sapSharedNotificationsService() {
var items = [];
this.setItems = function (collection) {
items.length = 0;
Array.prototype.forEach.call(collection, function (item) {
items.push(item);
});
};
this.getItems = function () {
return items;
};
}
angular.
module('sapShared').
service('sapSharedNotificationsService', [
sapSharedNotificationsService
]);
}());
|
/**
* Created by i070970 on 8/26/14.
*/
(function () {
'use strict';
function sapSharedNotificationsService($rootScope) {
var items = [];
this.setItems = function (collection) {
items.length = 0;
Array.prototype.forEach.call(collection, function (item) {
items.push(item);
});
};
this.getItems = function () {
return items;
};
}
angular.
module('sapShared').
service('sapSharedNotificationsService', [
'$rootScope',
sapSharedNotificationsService
]);
}());
|
Normalize case in my assertion.
|
#!/usr/bin/env python
"""
Copyright (c) 2008 Dustin Sallings <dustin@spy.net>
"""
import os
import sys
sys.path.append(os.path.join(sys.path[0], '..', 'lib'))
sys.path.append('lib')
from twisted.internet import reactor, protocol, defer, task
import twitter
fetchCount = 0
@defer.deferredGenerator
def getSome(tw, user):
global fetchCount
fetchCount = 0
def gotEntry(msg):
global fetchCount
fetchCount += 1
assert msg.title.lower().startswith(user.lower() + ": ")
l = len(user)
print msg.title[l+2:]
page = 1
while True:
fetchCount = 0
sys.stderr.write("Fetching page %d\n" % page)
d = tw.user_timeline(gotEntry, user, {'count': '200', 'page': str(page)})
page += 1
wfd = defer.waitForDeferred(d)
yield wfd
wfd.getResult()
if fetchCount == 0:
reactor.stop()
user = None
if len(sys.argv) > 3:
user = sys.argv[3]
tw = twitter.Twitter(sys.argv[1], sys.argv[2])
defer.maybeDeferred(getSome, tw, user)
reactor.run()
|
#!/usr/bin/env python
"""
Copyright (c) 2008 Dustin Sallings <dustin@spy.net>
"""
import os
import sys
sys.path.append(os.path.join(sys.path[0], '..', 'lib'))
sys.path.append('lib')
from twisted.internet import reactor, protocol, defer, task
import twitter
fetchCount = 0
@defer.deferredGenerator
def getSome(tw, user):
global fetchCount
fetchCount = 0
def gotEntry(msg):
global fetchCount
fetchCount += 1
assert msg.title.startswith(user + ": ")
l = len(user)
print msg.title[l+2:]
page = 1
while True:
fetchCount = 0
sys.stderr.write("Fetching page %d\n" % page)
d = tw.user_timeline(gotEntry, user, {'count': '200', 'page': str(page)})
page += 1
wfd = defer.waitForDeferred(d)
yield wfd
wfd.getResult()
if fetchCount == 0:
reactor.stop()
user = None
if len(sys.argv) > 3:
user = sys.argv[3]
tw = twitter.Twitter(sys.argv[1], sys.argv[2])
defer.maybeDeferred(getSome, tw, user)
reactor.run()
|
Add example for inMemory room database
|
package com.sample.database.room;
import android.arch.persistence.room.Room;
import android.content.Context;
import java.util.List;
/**
* Created by anandgaurav on 12/02/18.
*/
public class UserDBHelper {
private final AppDatabase appDatabase;
private final AppDatabase inMemoryAppDatabase;
public UserDBHelper(Context context) {
appDatabase = Room.databaseBuilder(context, AppDatabase.class, "User-Database")
.allowMainThreadQueries()
.build();
inMemoryAppDatabase = Room.inMemoryDatabaseBuilder(context, AppDatabase.class)
.allowMainThreadQueries()
.build();
}
public void insertUser(List<User> userList) {
appDatabase.userDao().insertAll(userList);
}
public void insertUserInMemory(List<User> userList) {
inMemoryAppDatabase.userDao().insertAll(userList);
}
public int count() {
return appDatabase.userDao().loadAll().size();
}
public int countInMemory() {
return inMemoryAppDatabase.userDao().loadAll().size();
}
}
|
package com.sample.database.room;
import android.arch.persistence.room.Room;
import android.content.Context;
import java.util.List;
/**
* Created by anandgaurav on 12/02/18.
*/
public class UserDBHelper {
private final AppDatabase appDatabase;
private final AppDatabase inMemoryAppDatabase;
public UserDBHelper(Context context) {
appDatabase = Room.databaseBuilder(context, AppDatabase.class, "User-Database")
.allowMainThreadQueries()
.build();
inMemoryAppDatabase = Room.inMemoryDatabaseBuilder(context, AppDatabase.class).build();
}
public void insertUser(List<User> userList) {
appDatabase.userDao().insertAll(userList);
}
public void insertUserInMemory(List<User> userList) {
inMemoryAppDatabase.userDao().insertAll(userList);
}
public int count() {
return appDatabase.userDao().loadAll().size();
}
public int countInMemory() {
return inMemoryAppDatabase.userDao().loadAll().size();
}
}
|
Add callCheck to deleteTag ajax action to avoid security check pbms
|
<?php
/**
* ownCloud - bookmarks plugin
*
* @author Arthur Schiwon
* @copyright 2011 Arthur Schiwon blizzz@arthur-schiwon.de
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
// Check if we are a user
OCP\JSON::checkLoggedIn();
OCP\JSON::callCheck();
OCP\JSON::checkAppEnabled('bookmarks');
if(isset($_POST['old_name']))
{
OC_Bookmarks_Bookmarks::deleteTag($_POST['old_name']);
OCP\JSON::success();
exit();
}
OC_JSON::error();
exit();
|
<?php
/**
* ownCloud - bookmarks plugin
*
* @author Arthur Schiwon
* @copyright 2011 Arthur Schiwon blizzz@arthur-schiwon.de
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
// Check if we are a user
OCP\JSON::checkLoggedIn();
OCP\JSON::checkAppEnabled('bookmarks');
if(isset($_POST['old_name']))
{
OC_Bookmarks_Bookmarks::deleteTag($_POST['old_name']);
OCP\JSON::success();
exit();
}
OC_JSON::error();
exit();
|
Disable colored logging for Windows
|
""" Formatter for the logging module, coloring terminal output according to error criticity. """
import enum
import logging
import sys
Colors = enum.Enum("Colors", ("RED", "GREEN", "YELLOW", "BLUE"))
LEVEL_COLOR_MAPPING = {logging.WARNING: Colors.YELLOW,
logging.ERROR: Colors.RED,
logging.CRITICAL: Colors.RED}
LEVEL_BOLD_MAPPING = {logging.WARNING: False,
logging.ERROR: False,
logging.CRITICAL: True}
class ColoredFormatter(logging.Formatter):
def format(self, record):
message = super().format(record)
if sys.stderr.isatty() and not sys.platform.startswith("win32"):
try:
color_code = LEVEL_COLOR_MAPPING[record.levelno].value
bold = LEVEL_BOLD_MAPPING[record.levelno]
except KeyError:
pass
else:
message = "\033[%u;%um%s\033[0m" % (int(bold), 30 + color_code, message)
return message
|
""" Formatter for the logging module, coloring terminal output according to error criticity. """
import enum
import logging
import sys
Colors = enum.Enum("Colors", ("RED", "GREEN", "YELLOW", "BLUE"))
LEVEL_COLOR_MAPPING = {logging.WARNING: Colors.YELLOW,
logging.ERROR: Colors.RED,
logging.CRITICAL: Colors.RED}
LEVEL_BOLD_MAPPING = {logging.WARNING: False,
logging.ERROR: False,
logging.CRITICAL: True}
class ColoredFormatter(logging.Formatter):
def format(self, record):
message = super().format(record)
if sys.stderr.isatty():
try:
color_code = LEVEL_COLOR_MAPPING[record.levelno].value
bold = LEVEL_BOLD_MAPPING[record.levelno]
except KeyError:
pass
else:
message = "\033[%u;%um%s\033[0m" % (int(bold), 30 + color_code, message)
return message
|
Add a default time zone
|
<?php
if ( ! defined('COOKIE_SESSION') ) {
ini_set('session.use_cookies', '0');
ini_set('session.use_only_cookies',0);
ini_set('session.use_trans_sid',1);
}
error_reporting(E_ALL & ~E_NOTICE);
error_reporting(E_ALL );
ini_set('display_errors', 1);
date_default_timezone_set('America/New_York');
function do_analytics() {
global $CFG;
if ( $CFG->analytics_key ) { ?>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
<?php
echo(" ga('create', '{$CFG->analytics_key}', '{$CFG->analytics_name}');\n");
?>
ga('send', 'pageview');
</script>
<?php
} // if
}
// No trailer
|
<?php
if ( ! defined('COOKIE_SESSION') ) {
ini_set('session.use_cookies', '0');
ini_set('session.use_only_cookies',0);
ini_set('session.use_trans_sid',1);
}
error_reporting(E_ALL & ~E_NOTICE);
error_reporting(E_ALL );
ini_set('display_errors', 1);
function do_analytics() {
global $CFG;
if ( $CFG->analytics_key ) { ?>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
<?php
echo(" ga('create', '{$CFG->analytics_key}', '{$CFG->analytics_name}');\n");
?>
ga('send', 'pageview');
</script>
<?php
} // if
}
// No trailer
|
Set broker to version 2.7
|
package com.emc.ecs.serviceBroker.config;
import java.net.URL;
import org.cloudfoundry.community.servicebroker.model.BrokerApiVersion;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import com.emc.ecs.managementClient.Connection;
import com.emc.ecs.serviceBroker.repository.EcsRepositoryCredentials;
@Configuration
@ComponentScan(basePackages = "com.emc.ecs.serviceBroker")
public class BrokerConfig {
@Bean
public Connection ecsConnection() {
URL certificate = getClass().getClassLoader().getResource("localhost.pem");
return new Connection("https://104.197.239.202:4443", "root", "ChangeMe", certificate);
}
@Bean
public BrokerApiVersion brokerApiVersion() {
return new BrokerApiVersion("2.7");
}
@Bean
public EcsRepositoryCredentials getRepositoryCredentials() {
return new EcsRepositoryCredentials("ecs-cf-service-broker-repository", "ecs-cf-service-broker-repository",
"ns1", "urn:storageos:ReplicationGroupInfo:f81a7335-cadf-48fb-8eda-4856b250e9de:global");
}
}
|
package com.emc.ecs.serviceBroker.config;
import java.net.URL;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import com.emc.ecs.managementClient.Connection;
import com.emc.ecs.serviceBroker.repository.EcsRepositoryCredentials;
@Configuration
@ComponentScan(basePackages = "com.emc.ecs.serviceBroker")
public class BrokerConfig {
@Bean
public Connection ecsConnection() {
URL certificate = getClass().getClassLoader().getResource("localhost.pem");
return new Connection("https://8.34.215.78:4443", "root", "ChangeMe", certificate);
}
@Bean
public EcsRepositoryCredentials getRepositoryCredentials() {
return new EcsRepositoryCredentials("ecs-cf-service-broker-repository", "ecs-cf-service-broker-repository",
"ns1", "urn:storageos:ReplicationGroupInfo:d4fc7068-1051-49ee-841f-1102e44c841e:global");
}
}
|
Use a more descriptive test case name
|
from unittest import TestCase
from prudent.mapping import Mapping
class MappingTest(TestCase):
def setUp(self):
self.mapping = Mapping([(1, 2), (2, 3), (3, 4)])
def test_iter_preserves_keys(self):
keys = [1, 2, 3]
for _ in range(2):
assert list(self.mapping) == keys
def test_contains(self):
assert 1 in self.mapping
assert 1 in self.mapping
assert 3 in self.mapping
def test_getitem(self):
assert self.mapping[1] == 2
assert self.mapping[3] == 4
assert self.mapping[2] == 3
def test_len(self):
assert len(self.mapping) == 0
self.mapping[3]
assert len(self.mapping) == 3
|
from unittest import TestCase
from prudent.mapping import Mapping
class MappingTest(TestCase):
def setUp(self):
self.mapping = Mapping([(1, 2), (2, 3), (3, 4)])
def test_iter(self):
keys = [1, 2, 3]
for _ in range(2):
assert list(self.mapping) == keys
def test_contains(self):
assert 1 in self.mapping
assert 1 in self.mapping
assert 3 in self.mapping
def test_getitem(self):
assert self.mapping[1] == 2
assert self.mapping[3] == 4
assert self.mapping[2] == 3
def test_len(self):
assert len(self.mapping) == 0
self.mapping[3]
assert len(self.mapping) == 3
|
Fix the circle to rectangle code
Was totally incorrect previously
|
from menpo.shape import PointDirectedGraph
import numpy as np
def pointgraph_from_circle(fitting):
diameter = fitting.diameter
radius = diameter / 2.0
y, x = fitting.center
y -= radius
x -= radius
return PointDirectedGraph(np.array(((y, x),
(y + diameter, x),
(y + diameter, x + diameter),
(y, x + diameter))),
np.array([[0, 1], [1, 2], [2, 3], [3, 0]]))
|
from menpo.shape import PointDirectedGraph
import numpy as np
def pointgraph_from_circle(fitting):
y, x = fitting.center
radius = fitting.diameter / 2.0
return PointDirectedGraph(np.array(((y, x),
(y + radius, x),
(y + radius, x + radius),
(y, x + radius))),
np.array([[0, 1], [1, 2], [2, 3], [3, 0]]))
|
Set the raw API directly.
|
// Used to detect for Cygwin
var os = require('os');
// Required for Windows/Cygwin support
var root = [__dirname, '/vendor/libgit2/build/shared'].join(''),
path = process.env.PATH;
if (~os.type().indexOf('CYGWIN') && !~path.indexOf(root)) {
process.env.PATH = root + ':' + path;
}
// Assign raw api to module
var rawApi;
try {
rawApi = require('./build/Release/nodegit');
} catch (e) {
rawApi = require('./build/Debug/nodegit');
}
// Set the exports prototype to the raw API.
exports.__proto__ = rawApi;
// Import extensions
require('./lib/commit.js');
require('./lib/blob.js');
require('./lib/object.js');
require('./lib/signature.js');
require('./lib/odb.js');
require('./lib/oid.js');
require('./lib/index.js');
require('./lib/repo.js');
require('./lib/reference.js');
require('./lib/revwalk.js');
require('./lib/tree.js');
require('./lib/diff_list.js');
require('./lib/tree_entry.js');
require('./lib/tree_builder.js');
// Set version
exports.version = require('./package').version;
// Initialize threads
exports.Threads.init();
|
// Used to detect for Cygwin
var os = require('os');
// Required for Windows/Cygwin support
var root = [__dirname, '/vendor/libgit2/build/shared'].join(''),
path = process.env.PATH;
if (~os.type().indexOf('CYGWIN') && !~path.indexOf(root)) {
process.env.PATH = root + ':' + path;
}
// Assign raw api to module
var rawApi;
try {
rawApi = require('./build/Release/nodegit');
} catch (e) {
rawApi = require('./build/Debug/nodegit');
}
for (var key in rawApi) {
exports[key] = rawApi[key];
}
// Import extensions
require('./lib/commit.js');
require('./lib/blob.js');
require('./lib/object.js');
require('./lib/signature.js');
require('./lib/odb.js');
require('./lib/oid.js');
require('./lib/index.js');
require('./lib/repo.js');
require('./lib/reference.js');
require('./lib/revwalk.js');
require('./lib/tree.js');
require('./lib/diff_list.js');
require('./lib/tree_entry.js');
require('./lib/tree_builder.js');
// Set version
exports.version = require('./package').version;
// Initialize threads
exports.Threads.init();
|
Add timeout for kernel boot test for travis.
|
/*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
'use strict';
var assert = require('assert');
var prepareConfig = require('../helpers/prepare-config');
var Kernel = require('../../lib/kernel');
describe('kernel load test', function() {
it('should load the kernel on a good config', function(done){
this.timeout(10000);
var config = prepareConfig(require('../data/basic-config'));
new Kernel(config, function(err) {
assert(!err);
done();
});
});
});
|
/*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
'use strict';
var assert = require('assert');
var prepareConfig = require('../helpers/prepare-config');
var Kernel = require('../../lib/kernel');
describe('kernel load test', function() {
it('should load the kernel on a good config', function(done){
var config = prepareConfig(require('../data/basic-config'));
new Kernel(config, function(err) {
assert(!err);
done();
});
});
});
|
Update generate_secret function to the root of the app
|
import os
import random
import string
from datetime import date, datetime
def random_name():
return ''.join([random.choice(string.ascii_lowercase + string.digits) for n in range(20)])
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, (datetime, date)):
return obj.isoformat()
raise TypeError("Type %s not serializable" % type(obj))
def secret_key_gen():
filepath = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + '/secret.ini'
generated_key = ''.join([random.SystemRandom().choice(string.ascii_letters + string.digits + string.punctuation)
for _ in range(50)])
with open(filepath, 'w') as secret_file:
secret_file.write(
'[SECRET_KEY]\nKEY: %(key)s' % dict(key=generated_key)
)
print('Find your secret key at %(path)s' % dict(path=filepath))
|
import os
import random
import string
from datetime import date, datetime
def random_name():
return ''.join([random.choice(string.ascii_lowercase + string.digits) for n in range(20)])
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, (datetime, date)):
return obj.isoformat()
raise TypeError("Type %s not serializable" % type(obj))
def secret_key_gen():
filepath = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/secret.ini'
generated_key = ''.join([random.SystemRandom().choice(string.ascii_letters + string.digits + string.punctuation)
for _ in range(50)])
with open(filepath, 'w') as secret_file:
secret_file.write(
'[SECRET_KEY]\nKEY: %(key)s' % dict(key=generated_key)
)
print('Find your secret key at %(path)s' % dict(path=filepath))
|
Remove API to clear stored modules
|
/*jslint browser:true, node:true*/
'use strict';
/**
* Module Dependencies
*/
var View = require('./view');
var store = require('./store');
/**
* Creates and registers a
* FruitMachine view constructor.
*
* @param {Object|View}
* @return {View}
*/
module.exports = function(props) {
var module = props.module || 'undefined';
var view;
// Move the module key
delete props.module;
props._module = module;
// If an existing FruitMachine.View
// has been passed in, use that.
// If just an object literal has
// been passed in then we extend the
// default FruitMachine.View prototype
// with the properties passed in.
view = (props.__super__)
? props
: View.extend(props);
// Store the module by module type
// so that module can be referred to
// by just a string in layout definitions
return store.modules[module] = view;
};
|
/*jslint browser:true, node:true*/
'use strict';
/**
* Module Dependencies
*/
var View = require('./view');
var store = require('./store');
/**
* Creates and registers a
* FruitMachine view constructor.
*
* @param {Object|View}
* @return {View}
*/
module.exports = function(props) {
var module = props.module || 'undefined';
var view;
// Remove the module key
delete props.module;
props._module = module;
// If an existing FruitMachine.View
// has been passed in, use that.
// If just an object literal has
// been passed in then we extend the
// default FruitMachine.View prototype
// with the properties passed in.
view = (props.__super__)
? props
: View.extend(props);
// Store the module by module type
// so that module can be referred to
// by just a string in layout definitions
return store.modules[module] = view;
};
/**
* Removes a module
* from the module store.
*
* If no module key is passed
* the entire store is cleared.
*
* @param {String|undefined} module
* @api public
*/
module.exports.clear = function(module) {
if (module) delete store.modules[module];
else store.modules = {};
};
|
Change output filenaming to have .txt
|
#! /usr/bin/python3
import sys
import os
import math
from astropy.io import fits
inputFolder = sys.argv[1]
outputFolder = sys.argv[2]
eLo = int(sys.argv[3])
eHi = int(sys.argv[4])
binSize = int(sys.argv[5])
fnames = os.listdir(inputFolder)
for fname in fnames:
print(fname)
hdulist = fits.open(inputFolder+"/"+fname)
for i in range(1,5):
timeRange = hdulist[i].header["TSTOP"] - hdulist[i].header["TSTART"]
nBins = math.ceil(timeRange/binSize)
count = [0]*nBins
for event in hdulist[i].data:
if(event["ENERGY"]>=eLo or event["ENERGY"]<=eHi):
index = math.floor( nBins*(event["Time"] - hdulist[i].header["TSTART"])/timeRange )
count[index] += 1
sigClass = 1
outputFile = outputFolder+"/"+os.path.splitext(fname)[0]+"_Q{0}.txt".format(i)
with open(outputFile,'w') as f:
f.write("{0} {1}\n".format(nBins,sigClass))
for j in range(nBins):
f.write("{0}\n".format(count[j]))
|
#! /usr/bin/python3
import sys
import os
import math
from astropy.io import fits
inputFolder = sys.argv[1]
outputFolder = sys.argv[2]
eLo = int(sys.argv[3])
eHi = int(sys.argv[4])
binSize = int(sys.argv[5])
fnames = os.listdir(inputFolder)
for fname in fnames:
print(fname)
hdulist = fits.open(inputFolder+"/"+fname)
for i in range(1,5):
timeRange = hdulist[i].header["TSTOP"] - hdulist[i].header["TSTART"]
nBins = math.ceil(timeRange/binSize)
count = [0]*nBins
for event in hdulist[i].data:
if(event["ENERGY"]>=eLo or event["ENERGY"]<=eHi):
index = math.floor( nBins*(event["Time"] - hdulist[i].header["TSTART"])/timeRange )
count[index] += 1
sigClass = 1
with open(outputFolder+"/{0}_{1}".format(fname,i),'w') as f:
f.write("{0} {1}\n".format(nBins,sigClass))
for j in range(nBins):
f.write("{0}\n".format(count[j]))
|
Drop table for device report logs.
|
from datetime import datetime, timedelta
from celery.schedules import crontab
from celery.task import periodic_task
from django.conf import settings
from django.db import connection
from phonelog.models import UserErrorEntry, ForceCloseEntry, UserEntry
@periodic_task(run_every=crontab(minute=0, hour=0), queue=getattr(settings, 'CELERY_PERIODIC_QUEUE', 'celery'))
def purge_old_device_report_entries():
max_age = datetime.utcnow() - timedelta(days=settings.DAYS_TO_KEEP_DEVICE_LOGS)
with connection.cursor() as cursor:
partitoned_db_format = 'phonelog_daily_partitioned_devicereportentry_y%Yd%j'
table_to_drop = (max_age - timedelta(days=1)).strftime(partitoned_db_format)
cursor.execute("DROP TABLE {}".format(table_to_drop))
UserErrorEntry.objects.filter(server_date__lt=max_age).delete()
ForceCloseEntry.objects.filter(server_date__lt=max_age).delete()
UserEntry.objects.filter(server_date__lt=max_age).delete()
|
from datetime import datetime, timedelta
from celery.schedules import crontab
from celery.task import periodic_task
from django.conf import settings
from phonelog.models import DeviceReportEntry, UserErrorEntry, ForceCloseEntry, UserEntry
@periodic_task(run_every=crontab(minute=0, hour=0), queue=getattr(settings, 'CELERY_PERIODIC_QUEUE', 'celery'))
def purge_old_device_report_entries():
max_age = datetime.utcnow() - timedelta(days=settings.DAYS_TO_KEEP_DEVICE_LOGS)
DeviceReportEntry.objects.filter(server_date__lt=max_age).delete()
UserErrorEntry.objects.filter(server_date__lt=max_age).delete()
ForceCloseEntry.objects.filter(server_date__lt=max_age).delete()
UserEntry.objects.filter(server_date__lt=max_age).delete()
|
Change keepEmptyPriority default to true
|
'use strict';
var path = require('path');
// #ARCHIVE:0 Eliminate unused config options id:1203
var DEFAULT_EXCLUDE_PATTERN = "^(node_modules|bower_components|\\.imdone|target|build|dist|logs)[\\/\\\\]?|\\.(git|svn|hg|npmignore)|\\~$|\\.(jpg|png|gif|swp|ttf|otf)$";
var CONFIG_DIR = ".imdone";
module.exports = {
CONFIG_DIR: CONFIG_DIR,
CONFIG_FILE: path.join(CONFIG_DIR,"config.json"),
IGNORE_FILE: '.imdoneignore',
DEFAULT_FILE_PATTERN: "^(readme\\.md|home\\.md)$",
DEFAULT_EXCLUDE_PATTERN: DEFAULT_EXCLUDE_PATTERN,
DEFAULT_CONFIG: {
exclude: [DEFAULT_EXCLUDE_PATTERN],
watcher: true,
keepEmptyPriority: true,
code: {
include_lists:[
"TODO", "DOING", "DONE", "PLANNING", "FIXME", "ARCHIVE", "HACK", "CHANGED", "XXX", "IDEA", "NOTE", "REVIEW"
]
},
lists: [],
marked : {
gfm: true,
tables: true,
breaks: false,
pedantic: false,
smartLists: true,
langPrefix: 'language-' }
},
ERRORS: {
NOT_A_FILE: "file must be of type File",
CALLBACK_REQUIRED: "Last paramter must be a callback function"
}
};
|
'use strict';
var path = require('path');
// #ARCHIVE:0 Eliminate unused config options id:1203
var DEFAULT_EXCLUDE_PATTERN = "^(node_modules|bower_components|\\.imdone|target|build|dist|logs)[\\/\\\\]?|\\.(git|svn|hg|npmignore)|\\~$|\\.(jpg|png|gif|swp|ttf|otf)$";
var CONFIG_DIR = ".imdone";
module.exports = {
CONFIG_DIR: CONFIG_DIR,
CONFIG_FILE: path.join(CONFIG_DIR,"config.json"),
IGNORE_FILE: '.imdoneignore',
DEFAULT_FILE_PATTERN: "^(readme\\.md|home\\.md)$",
DEFAULT_EXCLUDE_PATTERN: DEFAULT_EXCLUDE_PATTERN,
DEFAULT_CONFIG: {
exclude: [DEFAULT_EXCLUDE_PATTERN],
watcher: true,
keepEmptyPriority: false,
code: {
include_lists:[
"TODO", "DOING", "DONE", "PLANNING", "FIXME", "ARCHIVE", "HACK", "CHANGED", "XXX", "IDEA", "NOTE", "REVIEW"
]
},
lists: [],
marked : {
gfm: true,
tables: true,
breaks: false,
pedantic: false,
smartLists: true,
langPrefix: 'language-' }
},
ERRORS: {
NOT_A_FILE: "file must be of type File",
CALLBACK_REQUIRED: "Last paramter must be a callback function"
}
};
|
Use composition instead of inheritance for PluginPass
|
import type Plugin from "./plugin";
import Store from "../store";
import traverse from "comal-traverse";
import File from "./file";
export default class PluginPass {
constructor(file: File, plugin: Plugin, options: Object = {}) {
this.store = new Store();
this.plugin = plugin;
this.file = file;
this.opts = options;
}
plugin: Plugin;
file: File;
opts: Object;
transform() {
let file = this.file;
file.log.debug(`Start transformer ${this.key}`);
traverse(file.ast, this.plugin.visitor, file.scope, file);
file.log.debug(`Finish transformer ${this.key}`);
}
addHelper(...args) {
return this.file.addHelper(...args);
}
addImport(...args) {
return this.file.addImport(...args);
}
getModuleName(...args) {
return this.file.getModuleName(...args);
}
buildCodeFrameError(...args) {
return this.file.buildCodeFrameError(...args);
}
}
|
import type Plugin from "./plugin";
import Store from "../store";
import traverse from "comal-traverse";
import File from "./file";
export default class PluginPass extends Store {
constructor(file: File, plugin: Plugin, options: Object = {}) {
super();
this.plugin = plugin;
this.file = file;
this.opts = options;
}
plugin: Plugin;
file: File;
opts: Object;
transform() {
let file = this.file;
file.log.debug(`Start transformer ${this.key}`);
traverse(file.ast, this.plugin.visitor, file.scope, file);
file.log.debug(`Finish transformer ${this.key}`);
}
addHelper(...args) {
return this.file.addHelper(...args);
}
addImport(...args) {
return this.file.addImport(...args);
}
getModuleName(...args) {
return this.file.getModuleName(...args);
}
buildCodeFrameError(...args) {
return this.file.buildCodeFrameError(...args);
}
}
|
Add check for Heroku before .env import
Heroku was rightfully breaking when loadenv() was called as it already
had the proper environment variables. Add a check for Heroku before
loading the variables.
|
'''
The user login module for SaltBot
'''
import requests
import os
from dotenv import load_dotenv, find_dotenv
URL_SIGNIN = 'https://www.saltybet.com/authenticate?signin=1'
def saltbot_login():
# Default the return values to None
session = None
request = None
# Start a session so we can have persistant cookies
session = requests.session()
# Obtain login specifics from .env if running locally
if os.environ.get('HEROKU') is None:
load_dotenv(find_dotenv())
# This is the form data that the page sends when logging in
login_data = {
'email': os.environ.get('EMAIL'),
'pword': os.environ.get('PASSWORD'),
'authenticate': 'signin'
}
# Authenticate
request = session.post(URL_SIGNIN, data=login_data)
# Check for successful login & redirect
if request.url != "https://www.saltybet.com/" and request.url != "http://www.saltybet.com/":
print("Error: Wrong URL: " + request.url)
return session, request
|
'''
The user login module for SaltBot
'''
import requests
import os
from dotenv import load_dotenv, find_dotenv
URL_SIGNIN = 'https://www.saltybet.com/authenticate?signin=1'
def saltbot_login():
# Default the return values to None
session = None
request = None
# Start a session so we can have persistant cookies
session = requests.session()
# Obtain login specifics from .env
load_dotenv(find_dotenv())
# This is the form data that the page sends when logging in
login_data = {
'email': os.environ.get('EMAIL'),
'pword': os.environ.get('PASSWORD'),
'authenticate': 'signin'
}
# Authenticate
request = session.post(URL_SIGNIN, data=login_data)
# Check for successful login & redirect
if request.url != "https://www.saltybet.com/" and request.url != "http://www.saltybet.com/":
print("Error: Wrong URL: " + request.url)
return session, request
|
Add call to pull schedule
|
package gof1
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
const baseUrl = "http://ergast.com/api/f1/"
func GetRacesInSeason(year int) []Race {
url := fmt.Sprintf("%s%v/schedule.json", baseUrl, year)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Println("NewRequest:", err)
return nil
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Println("Do:", err)
return nil
}
defer resp.Body.Close()
var result F1
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
log.Println(err)
}
return result.MRData.RaceTable.Races
}
// GetRacesWithResults queries the Ergast api and returns the details of every completed race in the F1 season specified
func GetRacesWithResults(year int) []Race {
url := fmt.Sprintf("%s%v/results.json", baseUrl, year)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Println("NewRequest:", err)
return nil
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Println("Do:", err)
return nil
}
defer resp.Body.Close()
var result F1
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
log.Println(err)
}
return result.MRData.RaceTable.Races
}
|
package gof1
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
// GetRaces queries the Ergast api and returns the details of every completed race in the F1 season specified
func GetRaces(year int) []Race {
url := fmt.Sprintf("http://ergast.com/api/f1/%v/results.json?limit=1000&offset=0", year)
fmt.Println(url)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Println("NewRequest:", err)
return nil
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Println("Do:", err)
return nil
}
defer resp.Body.Close()
var result F1
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
log.Println(err)
}
return result.MRData.RaceTable.Races
}
|
Use request.defaults() to simplify GitHub API calls
|
var _ = require('underscore');
var async = require('async');
var request = require('request');
var linters = require('./linters');
var repoURL = 'https://api.github.com/repos/nicolasmccurdy/repos';
var githubRequest = request.defaults({
headers: {
Accept: 'application/vnd.github.v3',
'User-Agent': 'ghlint'
},
qs: {
client_id: process.env.GHLINT_ID,
client_secret: process.env.GHLINT_SECRET
}
});
module.exports = {
linters: linters,
lintAll: function (callback) {
githubRequest(repoURL, function (err, repo) {
githubRequest(repoURL + '/commits', function (err, commits) {
callback(err, linters.map(function (linter) {
return {
message: linter.message,
result: linter.lint(repo, commits)
};
}));
});
});
}
};
|
var _ = require('underscore');
var async = require('async');
var request = require('request');
var linters = require('./linters');
var repoURL = 'https://api.github.com/repos/nicolasmccurdy/repos';
var options = {
headers: {
Accept: 'application/vnd.github.v3',
'User-Agent': 'ghlint'
},
qs: {
client_id: process.env.GHLINT_ID,
client_secret: process.env.GHLINT_SECRET
},
url: repoURL
};
var commitOptions = _.extend(options, { url: repoURL + '/commits' });
module.exports = {
linters: linters,
lintAll: function (callback) {
request(options, function (err, repo) {
request(commitOptions, function (err, commits) {
callback(err, linters.map(function (linter) {
return {
message: linter.message,
result: linter.lint(repo, commits)
};
}));
});
});
}
};
|
Add use of local playsoud.py
|
from ..queues import QueueTtS
from ..components import _BaseComponent
from gtts import gTTS
from .playsound import playsound
import os
class TextToSpeech(_BaseComponent):
def __init__(self):
super().__init__()
self.queue_tts = QueueTtS()
def run(self):
sentence = self.queue_tts.get()
print('To say out loud : {}'.format(sentence))
# TODO change the language to match user's settings
tts = gTTS(text=sentence, lang='en')
tts.save("tts.mp3")
playsound("tts.mp3")
os.remove("tts.mp3")
self.queue_tts.task_done()
|
from ..queues import QueueTtS
from ..components import _BaseComponent
from gtts import gTTS
from playsound import playsound
import os
class TextToSpeech(_BaseComponent):
def __init__(self):
super().__init__()
self.queue_tts = QueueTtS()
def run(self):
sentence = self.queue_tts.get()
print('To say out loud : {}'.format(sentence))
# TODO change the language to match user's settings
tts = gTTS(text=sentence, lang='en')
tts.save("tts.mp3")
playsound("tts.mp3")
os.remove("tts.mp3")
self.queue_tts.task_done()
|
Fix missing dependencies in simplebar-react bundle
|
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
import license from 'rollup-plugin-license';
import uglify from 'rollup-plugin-uglify';
import pkg from './package.json';
const banner = {
banner: `
${pkg.name} - v${pkg.version}
${pkg.description}
${pkg.homepage}
Made by ${pkg.author}
Under ${pkg.license} License
`
};
const globals = {
'prop-types': 'PropTypes',
'react': 'React'
};
const external = [...Object.keys(pkg.dependencies), 'react'];
export default [
{
input: 'index.js',
output: {
name: 'SimpleBar',
file: pkg.main,
format: 'umd',
globals: globals
},
external: external,
plugins: [
babel(),
resolve(), // so Rollup can find dependencies
commonjs(), // so Rollup can convert dependencies to an ES module
uglify(),
license(banner)
]
},
{
input: 'index.js',
external: external,
output: {
file: pkg.module,
format: 'es'
},
plugins: [
babel(),
license(banner)
]
}
];
|
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
import license from 'rollup-plugin-license';
import uglify from 'rollup-plugin-uglify';
import pkg from './package.json';
const banner = {
banner: `
${pkg.name} - v${pkg.version}
${pkg.description}
${pkg.homepage}
Made by ${pkg.author}
Under ${pkg.license} License
`
};
const globals = {
'prop-types': 'PropTypes',
'react-dom': 'ReactDOM',
'react': 'React'
};
const external = Object.keys(globals);
export default [
{
input: 'index.js',
output: {
name: 'SimpleBar',
file: pkg.main,
format: 'umd',
globals: globals
},
external: external,
plugins: [
babel(),
resolve(), // so Rollup can find dependencies
commonjs(), // so Rollup can convert dependencies to an ES module
uglify(),
license(banner)
]
},
{
input: 'index.js',
external: external,
output: {
file: pkg.module,
format: 'es'
},
plugins: [
babel(),
license(banner)
]
}
];
|
Enhance currency filter to allow format string to be specified
This allows the positioning of the currency symbol to be controlled.
Fixes #311
|
import locale
from django import template
from django.conf import settings
register = template.Library()
@register.filter(name='currency')
def currency(value):
"""
Format decimal value as currency
"""
try:
locale.setlocale(locale.LC_ALL, settings.LOCALE)
except AttributeError:
locale.setlocale(locale.LC_ALL, '')
# We allow the currency symbol to be overridden as the version in system
# locales if often not the desired one.
try:
symbol = getattr(settings, 'CURRENCY_SYMBOL', None)
if symbol:
# A custom currency symbol is specified. Check to see if a
# custom format is specified too - this allows the position of the
# currency symbol to be controlled.
format = getattr(
settings, 'CURRENCY_FORMAT', u"%(symbol)s%(value)s")
return format % {
'symbol': symbol,
'value': locale.format("%.2f", value, grouping=True)}
else:
# Use locale's currency format
c = locale.currency(value, symbol=True, grouping=True)
return unicode(c, 'utf8')
except TypeError:
return ''
|
import locale
from django import template
from django.conf import settings
register = template.Library()
@register.filter(name='currency')
def currency(value):
"""
Return value converted to a locale currency
"""
try:
locale.setlocale(locale.LC_ALL, settings.LOCALE)
except AttributeError:
locale.setlocale(locale.LC_ALL, '')
# We allow the currency symbol to be overridden
symbol = getattr(settings, 'CURRENCY_SYMBOL', None)
try:
if symbol:
return u"%s%s" % (symbol, locale.format("%.2f",
value, grouping=True))
else:
c = locale.currency(value, symbol=True, grouping=True)
return unicode(c, 'utf8')
except TypeError:
return ''
|
Use py.test directly instead of through runtests.py
|
import subprocess
import sys
from setuptools import setup, Command
import restle
class PyTest(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call(['py.test', 'test_restle.py'])
raise SystemExit(errno)
setup(
name='restle',
description='A REST client framework',
keywords='rest,mapper,client',
version=restle.__version__,
packages=['restle'],
requires=['six', 'requests'],
url='https://github.com/consbio/restle',
license='BSD',
tests_require=['pytest', 'httpretty==0.8.6', 'mock'],
cmdclass={'test': PyTest}
)
|
import subprocess
import sys
from setuptools import setup, Command
import restle
class PyTest(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, 'runtests.py'])
raise SystemExit(errno)
setup(
name='restle',
description='A REST client framework',
keywords='rest,mapper,client',
version=restle.__version__,
packages=['restle'],
requires=['six', 'requests'],
url='https://github.com/consbio/restle',
license='BSD',
tests_require=['pytest', 'httpretty==0.8.6', 'mock'],
cmdclass={'test': PyTest}
)
|
Use upper case variable for global vars
|
#! /usr/bin/env python
# coding:utf-8
from os import path
# the number of loop for train IBM Model 2
LOOP_COUNT = 10
PHRASE_MODEL_FILE = path.join(
path.abspath(path.dirname(__file__)),
"phrase.model"
)
BIGRAM_MODEL_FILE = path.join(
path.abspath(path.dirname(__file__)),
"bigram.model"
)
if __name__ == '__main__':
print("{} = {}".format(
"LOOP_COUNT",
LOOP_COUNT))
print("{} = {}".format(
"phrase_model_file",
PHRASE_MODEL_FILE))
print("{} = {}".format(
"bigram_model_file",
BIGRAM_MODEL_FILE))
|
#! /usr/bin/env python
# coding:utf-8
from os import path
# the number of loop for train IBM Model 2
loop_count = 10
phrase_model_file = path.join(
path.abspath(path.dirname(__file__)),
"phrase.model"
)
bigram_model_file = path.join(
path.abspath(path.dirname(__file__)),
"bigram.model"
)
if __name__ == '__main__':
print("{} = {}".format(
"loop_count",
loop_count))
print("{} = {}".format(
"phrase_model_file",
phrase_model_file))
print("{} = {}".format(
"bigram_model_file",
bigram_model_file))
|
Fix relative path in hash mode history.
|
import { resolvePath, hashChange } from '../utils'
function HashHistory(option) {
this.onChange = option.onChange;
}
HashHistory.prototype.start = function() {
var self = this;
this.listener = function () {
var path = location.hash;
var raw = path.replace(/^#!/, '');
if (raw.charAt(0) !== '/') {
raw = '/' + raw;
}
var formattedPath = self.formatPath(raw);
if (formattedPath !== path) {
location.replace(formattedPath);
return;
}
self.onChange(decodeURI(path.replace(/^#!/, '')));
};
hashChange.bind(this.listener);
this.listener();
};
HashHistory.prototype.stop = function() {
hashChange.remove(this.listener);
};
HashHistory.prototype.go = function(path, replace) {
var location = window.location;
path = this.formatPath(path);
location.hash = path;
};
HashHistory.prototype.formatPath = function(path) {
var prefix = '#!';
var start = path.charAt(0);
return start === '/'
? prefix + path
: start === '#'
? prefix + location.hash.replace(/^#!/, '').replace(/#.*/g, '') + path
: prefix + resolvePath(location.hash.replace(/^#!/, '').replace(/#.*/g, ''), path);
};
export default HashHistory
|
import { resolvePath, hashChange } from '../utils'
function HashHistory(option) {
this.onChange = option.onChange;
}
HashHistory.prototype.start = function() {
var self = this;
this.listener = function () {
var path = location.hash;
var raw = path.replace(/^#!/, '');
if (raw.charAt(0) !== '/') {
raw = '/' + raw;
}
var formattedPath = self.formatPath(raw);
if (formattedPath !== path) {
location.replace(formattedPath);
return;
}
self.onChange(decodeURI(path.replace(/^#!/, '')));
};
hashChange.bind(this.listener);
this.listener();
};
HashHistory.prototype.stop = function() {
hashChange.remove(this.listener);
};
HashHistory.prototype.go = function(path, replace) {
var location = window.location;
if (path.indexOf('#') === 0) {
location.hash = '#!' + location.hash.replace(/^#!/, '').replace(/#.*/g, '') + path;
return;
}
path = this.formatPath(path);
location.hash = path;
};
HashHistory.prototype.formatPath = function(path) {
var prefix = '#!';
return path.charAt(0) === '/'
? prefix + path
: prefix + resolvePath(location.hash.replace(/^#!/, ''), path);
};
export default HashHistory
|
Use the new url pattern
|
# -*- coding: utf-8 -*-
# vim: set ts=4
# Copyright 2014 Rémi Duraffort
# This file is part of Artifactorial.
#
# Artifactorial is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Artifactorial is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Artifactorial. If not, see <http://www.gnu.org/licenses/>
from __future__ import unicode_literals
from django.conf.urls import patterns, url
import Artifactorial.views as a_views
urlpatterns = [
url(r'^artifacts/(?P<filename>.*)$', a_views.artifacts, name='artifacts'),
url(r'^shared/(?P<token>.*)$', a_views.shared, name='shared')
]
|
# -*- coding: utf-8 -*-
# vim: set ts=4
# Copyright 2014 Rémi Duraffort
# This file is part of Artifactorial.
#
# Artifactorial is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Artifactorial is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Artifactorial. If not, see <http://www.gnu.org/licenses/>
from __future__ import unicode_literals
from django.conf.urls import patterns, url
urlpatterns = patterns('Artifactorial.views',
url(r'^artifacts/(?P<filename>.*)$', 'artifacts', name='artifacts'),
url(r'^shared/(?P<token>.*)$', 'shared', name='shared'))
|
Make sur the rgb values are within [0, 255] range.
|
from .module import Module, interact
class Led(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'LED', id, alias, robot)
self.color = (0, 0, 0)
@property
def color(self):
return self._value
@color.setter
def color(self, new_color):
new_color = [int(min(max(c, 0), 255)) for c in new_color]
if new_color != self._value:
self._value = new_color
self._push_value('rgb', new_color)
def control(self):
def change_color(red, green, blue):
self.color = (red, green, blue)
return interact(change_color,
red=(0, 255, 1),
green=(0, 255, 1),
blue=(0, 255, 1))
|
from .module import Module, interact
class Led(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'LED', id, alias, robot)
self.color = (0, 0, 0)
@property
def color(self):
return self._value
@color.setter
def color(self, new_color):
if new_color != self._value:
self._value = new_color
self._push_value('rgb', new_color)
def control(self):
def change_color(red, green, blue):
self.color = (red, green, blue)
return interact(change_color,
red=(0, 255, 1),
green=(0, 255, 1),
blue=(0, 255, 1))
|
Change language a tiny bit.
|
import React, { PureComponent } from 'react';
import connect from 'react-redux/es/connect/connect';
import {Callout, Tag} from '@blueprintjs/core';
import {FormattedMessage} from 'react-intl';
import SearchAlert from 'src/components/SearchAlert/SearchAlert';
import {selectAlerts, selectSession} from 'src/selectors';
class SuggestAlert extends PureComponent{
render(){
const { queryText, session} = this.props;
if (!session.loggedIn || !queryText || !queryText.trim().length || SearchAlert.doesAlertExist(this.props)) {
return null;
}
return (<Callout>
<FormattedMessage
id="alert.suggest.text"
defaultMessage={`Get notified {alertComponent} when data related to {queryText} is added.`}
values={{alertComponent: <SearchAlert queryText={queryText}/>, queryText:<Tag large>{queryText}</Tag>}}
/>
</Callout>)
}
}
const mapStateToProps = (state) => {
return {
alerts: selectAlerts(state),
session: selectSession(state),
}
};
SuggestAlert = connect(mapStateToProps)(SuggestAlert)
export {SuggestAlert};
export default SuggestAlert;
|
import React, { PureComponent } from 'react';
import connect from 'react-redux/es/connect/connect';
import {Callout, Tag} from '@blueprintjs/core';
import {FormattedMessage} from 'react-intl';
import SearchAlert from 'src/components/SearchAlert/SearchAlert';
import {selectAlerts, selectSession} from 'src/selectors';
class SuggestAlert extends PureComponent{
render(){
const { queryText, session} = this.props;
if (!session.loggedIn || !queryText || !queryText.trim().length || SearchAlert.doesAlertExist(this.props)) {
return null;
}
return (<Callout>
<FormattedMessage
id="alert.suggest.text"
defaultMessage={`or get notified {alertComponent} when {queryText} related data will be added.`}
values={{alertComponent: <SearchAlert queryText={queryText}/>, queryText:<Tag large>{queryText}</Tag>}}
/>
</Callout>)
}
}
const mapStateToProps = (state) => {
return {
alerts: selectAlerts(state),
session: selectSession(state),
}
};
SuggestAlert = connect(mapStateToProps)(SuggestAlert)
export {SuggestAlert};
export default SuggestAlert;
|
Fix selecting node text when moving
|
import React, { PropTypes } from 'react';
import { StyleSheet, css } from 'aphrodite';
const styles = StyleSheet.create({
node: {
cursor: 'move',
userSelect: 'none',
},
});
const renderState = (state, index) => (
<text key={state} x="5" y={37 + (18 * index)}>
<tspan>{state}</tspan>
<tspan x="155" textAnchor="end">99.9</tspan>
</text>
);
const Node = props => (
<g
className={css(styles.node)}
onMouseDown={props.onMouseDown}
transform={`translate(${props.x} ${props.y})`}
>
<rect
height={20 + (20 * props.states.length)}
width="160"
fill="#ff8"
stroke="#333"
ref={props.rectRef}
/>
<text x="5" y="15">{props.id}</text>
<path d="M0,20 h160" stroke="#333" />
{props.states.map(renderState)}
</g>
);
Node.propTypes = {
id: PropTypes.string.isRequired,
states: PropTypes.arrayOf(PropTypes.string).isRequired,
rectRef: PropTypes.func,
onMouseDown: PropTypes.func,
x: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
y: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
};
export default Node;
|
import React, { PropTypes } from 'react';
import { StyleSheet, css } from 'aphrodite';
const styles = StyleSheet.create({
node: {
cursor: 'move',
},
});
const renderState = (state, index) => (
<text key={state} x="5" y={37 + (18 * index)}>
<tspan>{state}</tspan>
<tspan x="155" textAnchor="end">99.9</tspan>
</text>
);
const Node = props => (
<g
className={css(styles.node)}
onMouseDown={props.onMouseDown}
transform={`translate(${props.x} ${props.y})`}
>
<rect
height={20 + (20 * props.states.length)}
width="160"
fill="#ff8"
stroke="#333"
ref={props.rectRef}
/>
<text x="5" y="15">{props.id}</text>
<path d="M0,20 h160" stroke="#333" />
{props.states.map(renderState)}
</g>
);
Node.propTypes = {
id: PropTypes.string.isRequired,
states: PropTypes.arrayOf(PropTypes.string).isRequired,
rectRef: PropTypes.func,
onMouseDown: PropTypes.func,
x: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
y: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
};
export default Node;
|
CHANGE - Updates version to 0.4.0
|
from distutils.core import setup
setup(
name = 'athletic_pandas',
packages = ['athletic_pandas'],
version = '0.4.0',
description = 'Workout analysis',
author='Aart Goossens',
author_email='aart@goossens.me',
url='https://github.com/AartGoossens/athletic_pandas',
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 3.6',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering',
]
)
|
from distutils.core import setup
setup(
name = 'athletic_pandas',
packages = ['athletic_pandas'],
version = '0.3',
description = 'Workout analysis',
author='Aart Goossens',
author_email='aart@goossens.me',
url='https://github.com/AartGoossens/athletic_pandas',
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 3.6',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering',
]
)
|
Document unused type parameter for tests
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3.test;
/**
* Allows for testing an exception that is not visible to
* {@link org.apache.commons.lang3.exception.ExceptionUtils}
*/
public class NotVisibleExceptionFactory {
private NotVisibleExceptionFactory() {}
/**
* Create a new Exception whose getCause method returns the
* provided cause.
* @param cause the cause of the exception
* @return a new {@link Exception}
*/
public static Exception createException(final Throwable cause) {
return new NotVisibleException(cause);
}
private static class NotVisibleException extends Exception {
private static final long serialVersionUID = 1L; // avoid warning
private final Throwable cause;
private NotVisibleException(final Throwable cause) {
this.cause = cause;
}
@Override
public synchronized Throwable getCause() {
return cause;
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3.test;
/**
* Allows for testing an exception that is not visible to
* {@link org.apache.commons.lang3.exception.ExceptionUtils}
*/
public class NotVisibleExceptionFactory {
private NotVisibleExceptionFactory() {}
/**
* Create a new Exception whose getCause method returns the
* provided cause.
* @param cause the cause of the exception
* @return a new {@link Exception}
*/
public static Exception createException(final Throwable cause) {
return new NotVisibleException(cause);
}
private static class NotVisibleException extends Exception {
private static final long serialVersionUID = 1L; // avoid warning
private final Throwable cause;
private NotVisibleException(final Throwable cause) {
this.cause = cause;
}
@Override
public Throwable getCause() {
return cause;
}
}
}
|
Add period at end of description
This is in line with other plug-ins.
Contributes to issue CURA-1190.
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import LocalFileOutputDevicePlugin
from UM.i18n import i18nCatalog
catalog = i18nCatalog("uranium")
def getMetaData():
return {
"plugin": {
"name": catalog.i18nc("@label", "Local File Output Device"),
"description": catalog.i18nc("@info:whatsthis", "Enables saving to local files."),
"author": "Ultimaker B.V.",
"version": "1.0",
"api": 2,
}
}
def register(app):
return { "output_device": LocalFileOutputDevicePlugin.LocalFileOutputDevicePlugin() }
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import LocalFileOutputDevicePlugin
from UM.i18n import i18nCatalog
catalog = i18nCatalog("uranium")
def getMetaData():
return {
"plugin": {
"name": catalog.i18nc("@label", "Local File Output Device"),
"description": catalog.i18nc("@info:whatsthis", "Enables saving to local files"),
"author": "Ultimaker B.V.",
"version": "1.0",
"api": 2,
}
}
def register(app):
return { "output_device": LocalFileOutputDevicePlugin.LocalFileOutputDevicePlugin() }
|
Remove copyright line in license headers
|
/*
* 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.skife.jdbi.v2;
public class SampleValueType {
public static SampleValueType valueOf(String value) {
return new SampleValueType(value);
}
private final String value;
private SampleValueType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SampleValueType that = (SampleValueType) o;
return !(value != null ? !value.equals(that.value) : that.value != null);
}
@Override
public int hashCode() {
return value != null ? value.hashCode() : 0;
}
@Override
public String toString() {
return value;
}
}
|
/*
* Copyright (C) 2015 Zane Benefits
*
* 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.skife.jdbi.v2;
public class SampleValueType {
public static SampleValueType valueOf(String value) {
return new SampleValueType(value);
}
private final String value;
private SampleValueType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SampleValueType that = (SampleValueType) o;
return !(value != null ? !value.equals(that.value) : that.value != null);
}
@Override
public int hashCode() {
return value != null ? value.hashCode() : 0;
}
@Override
public String toString() {
return value;
}
}
|
Use more readable version comparision
|
import sys
import pstats
import cProfile
import unittest
from django.test.simple import DjangoTestSuiteRunner
class ProfilingTestRunner(DjangoTestSuiteRunner):
def run_suite(self, suite, **kwargs):
stream = open('profiled_tests.txt', 'w')
# failfast keyword was added in Python 2.7 so we need to leave it out
# when creating the runner if we are running an older python version.
if sys.version_info >= (2, 7):
runner = unittest.TextTestRunner(verbosity=self.verbosity, failfast=self.failfast).run
else:
runner = unittest.TextTestRunner(verbosity=self.verbosity).run
profile = cProfile.Profile()
profile.runctx('result = run_tests(suite)', {
'run_tests': runner,
'suite': suite,
}, locals())
profile.create_stats()
stats = pstats.Stats(profile, stream=stream)
stats.sort_stats('time')
stats.print_stats()
return locals()['result']
|
import sys
import pstats
import cProfile
import unittest
from django.test.simple import DjangoTestSuiteRunner
class ProfilingTestRunner(DjangoTestSuiteRunner):
def run_suite(self, suite, **kwargs):
stream = open('profiled_tests.txt', 'w')
# failfast keyword was added in Python 2.7 so we need to leave it out
# when creating the runner if we are running an older python version.
if sys.hexversion >= 0x02070000:
runner = unittest.TextTestRunner(verbosity=self.verbosity, failfast=self.failfast).run
else:
runner = unittest.TextTestRunner(verbosity=self.verbosity).run
profile = cProfile.Profile()
profile.runctx('result = run_tests(suite)', {
'run_tests': runner,
'suite': suite,
}, locals())
profile.create_stats()
stats = pstats.Stats(profile, stream=stream)
stats.sort_stats('time')
stats.print_stats()
return locals()['result']
|
Enable appstats by default in dev too.
|
# -*- coding: utf-8 -*-
"""WSGI app setup."""
import os
import sys
if 'lib' not in sys.path:
# Add lib as primary libraries directory, with fallback to lib/dist
# and optionally to lib/dist.zip, loaded using zipimport.
sys.path[0:0] = ['lib', 'lib/dist', 'lib/dist.zip']
from tipfy import Tipfy
from config import config
from urls import rules
def enable_appstats(app):
"""Enables appstats middleware."""
from google.appengine.ext.appstats.recording import \
appstats_wsgi_middleware
app.wsgi_app = appstats_wsgi_middleware(app.wsgi_app)
def enable_jinja2_debugging():
"""Enables blacklisted modules that help Jinja2 debugging."""
if not debug:
return
# This enables better debugging info for errors in Jinja2 templates.
from google.appengine.tools.dev_appserver import HardenedModulesHook
HardenedModulesHook._WHITE_LIST_C_MODULES += ['_ctypes', 'gestalt']
# Is this the development server?
debug = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
# Instantiate the application.
app = Tipfy(rules=rules, config=config, debug=debug)
enable_appstats(app)
enable_jinja2_debugging()
def main():
# Run the app.
app.run()
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
"""WSGI app setup."""
import os
import sys
if 'lib' not in sys.path:
# Add lib as primary libraries directory, with fallback to lib/dist
# and optionally to lib/dist.zip, loaded using zipimport.
sys.path[0:0] = ['lib', 'lib/dist', 'lib/dist.zip']
from tipfy import Tipfy
from config import config
from urls import rules
def enable_appstats(app):
"""Enables appstats middleware."""
if debug:
return
from google.appengine.ext.appstats.recording import appstats_wsgi_middleware
app.wsgi_app = appstats_wsgi_middleware(app.wsgi_app)
def enable_jinja2_debugging():
"""Enables blacklisted modules that help Jinja2 debugging."""
if not debug:
return
# This enables better debugging info for errors in Jinja2 templates.
from google.appengine.tools.dev_appserver import HardenedModulesHook
HardenedModulesHook._WHITE_LIST_C_MODULES += ['_ctypes', 'gestalt']
# Is this the development server?
debug = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
# Instantiate the application.
app = Tipfy(rules=rules, config=config, debug=debug)
enable_appstats(app)
enable_jinja2_debugging()
def main():
# Run the app.
app.run()
if __name__ == '__main__':
main()
|
Add PlaybookFile edit view url
|
from django.conf.urls import url
from ansible.forms import AnsibleForm1, AnsibleForm2
from ansible.views import (
PlaybookWizard, PlaybookListView, PlaybookDetailView,
PlaybookFileEditView, PlaybookFileView
)
from . import views
urlpatterns = [
url(r'^create/$', PlaybookWizard.as_view([AnsibleForm1, AnsibleForm2])),
url(r'^$', PlaybookListView.as_view(), name='playbook-list'),
url(r'^(?P<pk>[-\w]+)/$',
PlaybookDetailView.as_view(), name='playbook-detail'
),
url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/$',
PlaybookFileView.as_view(), name='playbook-file-detail'
),
url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/edit$',
PlaybookFileEditView.as_view(), name='playbook-file-edit'
),
]
|
from django.conf.urls import url
from ansible.forms import AnsibleForm1, AnsibleForm2
from ansible.views import (
PlaybookWizard, PlaybookListView, PlaybookDetailView,
PlaybookFileView
)
from . import views
urlpatterns = [
url(r'^create/$', PlaybookWizard.as_view([AnsibleForm1, AnsibleForm2])),
url(r'^$', PlaybookListView.as_view(), name='playbook-list'),
url(r'^(?P<pk>[-\w]+)/$',
PlaybookDetailView.as_view(), name='playbook-detail'
),
url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/$',
PlaybookFileView.as_view(), name='playbook-file-detail'
),
]
|
Make async `runs` a bit better.
|
// Lifted from Atom
exports.beforeEach = function (fn) {
global.beforeEach(function () {
var result = fn()
if (result instanceof Promise) {
waitsForPromise(function () { return result })
}
})
}
exports.afterEach = function (fn) {
global.afterEach(function () {
var result = fn()
if (result instanceof Promise) {
waitsForPromise(function () { return result })
}
})
}
exports.runs = function (fn) {
global.runs(function () {
var result = fn()
if (result instanceof Promise) {
waitsForPromise(function () { return result })
}
})
}
var matchers = ['it', 'fit', 'ffit', 'fffit'] // inlining this makes things fail wtf.
matchers.forEach(function (name) {
exports[name] = function (description, fn) {
global[name](description, function () {
var result = fn()
if (result instanceof Promise) {
waitsForPromise(function () { return result })
}
})
}
})
function waitsForPromise (fn) {
var promise = fn()
waitsFor('spec promise to resolve', 30000, function (done) {
promise.then(done, function (error) {
jasmine.getEnv().currentSpec.fail(error)
return done()
})
})
}
exports.waitsForPromise = waitsForPromise
|
// Lifted from Atom
exports.beforeEach = function (fn) {
global.beforeEach(function () {
var result = fn()
if (result instanceof Promise) {
waitsForPromise(function () { return result })
}
})
}
exports.afterEach = function (fn) {
global.afterEach(function () {
var result = fn()
if (result instanceof Promise) {
waitsForPromise(function () { return result })
}
})
}
var matchers = ['it', 'fit', 'ffit', 'fffit'] // inlining this makes things fail wtf.
matchers.forEach(function (name) {
exports[name] = function (description, fn) {
global[name](description, function () {
var result = fn()
if (result instanceof Promise) {
waitsForPromise(function () { return result })
}
})
}
})
function waitsForPromise (fn) {
var promise = fn()
waitsFor('spec promise to resolve', 30000, function (done) {
promise.then(done, function (error) {
jasmine.getEnv().currentSpec.fail(error)
return done()
})
})
}
exports.waitsForPromise = waitsForPromise
|
Update thymeleaf.cache-ttl documentation to indicate the default value
|
package com.peterphi.std.guice.web.rest.templating.thymeleaf;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.name.Named;
import com.peterphi.std.annotation.Doc;
import com.peterphi.std.threading.Timeout;
import org.thymeleaf.templateresolver.ITemplateResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
import java.util.concurrent.TimeUnit;
public class TemplateResolverProvider implements Provider<ITemplateResolver>
{
@Inject(optional = true)
@Named("thymeleaf.cache-ttl")
@Doc("The maximum Time-To-Live value on the thymeleaf in-memory template cache (default 1h)")
Timeout cacheTTL = new Timeout(1, TimeUnit.HOURS);
@Override
public ITemplateResolver get()
{
ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
resolver.setTemplateMode("HTML5");
// Load templates from WEB-INF/templates/{name}.html
resolver.setPrefix("/WEB-INF/template/");
resolver.setSuffix(".html");
if (cacheTTL.getMilliseconds() > 0)
{
// cache templates for an hour
resolver.setCacheTTLMs(cacheTTL.getMilliseconds());
resolver.setCacheable(true);
}
else
{
// Don't cache
resolver.setCacheable(false);
}
return resolver;
}
}
|
package com.peterphi.std.guice.web.rest.templating.thymeleaf;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.name.Named;
import com.peterphi.std.annotation.Doc;
import com.peterphi.std.threading.Timeout;
import org.thymeleaf.templateresolver.ITemplateResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
import java.util.concurrent.TimeUnit;
public class TemplateResolverProvider implements Provider<ITemplateResolver>
{
@Inject(optional = true)
@Named("thymeleaf.cache-ttl")
@Doc("The maximum Time-To-Live value on the thymeleaf in-memory template cache")
Timeout cacheTTL = new Timeout(1, TimeUnit.HOURS);
@Override
public ITemplateResolver get()
{
ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
resolver.setTemplateMode("HTML5");
// Load templates from WEB-INF/templates/{name}.html
resolver.setPrefix("/WEB-INF/template/");
resolver.setSuffix(".html");
if (cacheTTL.getMilliseconds() > 0)
{
// cache templates for an hour
resolver.setCacheTTLMs(cacheTTL.getMilliseconds());
resolver.setCacheable(true);
}
else
{
// Don't cache
resolver.setCacheable(false);
}
return resolver;
}
}
|
Modify "iRail is a member of (...)"
Linking only "iRail" to hello.irail.be and leaving the "is a member of" string out of the link seems more logical
|
<footer class="footer container">
<hr/>
<p class="small"><a href="{{ URL::to('language') }}">{{Lang::get('client.language')}}</a> | 'iRail' © 2015, Open Knowledge Belgium. <a href="http://hello.iRail.be" target="_blank"></a>{{Lang::get('client.isPartOf')}} <a href="http://www.openknowledge.be/" target="_blank">Open Knowledge Belgium</a>. | <a href="{{ URL::to('contributors') }}">{{Lang::get('contributors.title')}}</a> | <a href="https://github.com/iRail/hyperRail"><i class="fa fa-github"></i></a></p>
</footer>
<script>
var _gaq = [['_setAccount', 'UA-263695-8'], ['_trackPageview']];
(function(d, t) {
var g = d.createElement(t),
s = d.getElementsByTagName(t)[0];
g.src = '//www.google-analytics.com/ga.js';
s.parentNode.insertBefore(g, s);
}(document, 'script'));
</script>
|
<footer class="footer container">
<hr/>
<p class="small"><a href="{{ URL::to('language') }}">{{Lang::get('client.language')}}</a> | 'iRail' © 2015, Open Knowledge Belgium. <a href="http://hello.iRail.be" target="_blank">{{Lang::get('client.isPartOf')}}</a> <a href="http://www.openknowledge.be/" target="_blank">Open Knowledge Belgium</a>. | <a href="{{ URL::to('contributors') }}">{{Lang::get('contributors.title')}}</a> | <a href="https://github.com/iRail/hyperRail"><i class="fa fa-github"></i></a></p>
</footer>
<script>
var _gaq = [['_setAccount', 'UA-263695-8'], ['_trackPageview']];
(function(d, t) {
var g = d.createElement(t),
s = d.getElementsByTagName(t)[0];
g.src = '//www.google-analytics.com/ga.js';
s.parentNode.insertBefore(g, s);
}(document, 'script'));
</script>
|
fix(shape): Update kittik-shape-basic to the latest version
BREAKING CHANGE: Change signature for render() method
|
import Shape from 'kittik-shape-basic';
/**
* Implements rectangle shape with text support.
*
* @since 1.0.0
*/
export default class Rectangle extends Shape {
render() {
const cursor = this.getCursor();
const text = this.getText();
const width = this.getWidth();
const height = this.getHeight();
const x1 = this.getX();
const y1 = this.getY();
const x2 = x1 + width;
const y2 = y1 + height;
const background = this.getBackground();
const foreground = this.getForeground();
const filler = ' '.repeat(width);
cursor.moveTo(x1, y1).background(background).foreground(foreground);
for (let y = y1; y <= y2; y++) cursor.write(filler).moveTo(x1, y);
cursor.moveTo(x1 + (width / 2 - text.length / 2), y1 + (height / 2)).write(text);
return this;
}
}
|
import Shape from 'kittik-shape-basic';
/**
* Implements rectangle shape with text support.
*
* @since 1.0.0
*/
export default class Rectangle extends Shape {
render(cursor) {
const text = this.getText();
const width = this.getWidth();
const height = this.getHeight();
const x1 = this.getX();
const y1 = this.getY();
const x2 = x1 + width;
const y2 = y1 + height;
const background = this.getBackground();
const foreground = this.getForeground();
const filler = ' '.repeat(width);
cursor.moveTo(x1, y1).background(background).foreground(foreground);
for (let y = y1; y <= y2; y++) cursor.write(filler).moveTo(x1, y);
cursor.moveTo(x1 + (width / 2 - text.length / 2), y1 + (height / 2)).write(text);
return this;
}
}
|
Add a change to test
|
<?php
namespace Tests\Feature;
use App\User;
use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class CategoryTest extends TestCase
{
use DatabaseTransactions;
/**
* A basic test example.
*
* @return void
*/
public function testCreateCategory()
{
//$faker = Faker\Factory::create();
$user = factory(User::class)->create();
$category = array(
'user_id' => $user->id,
'name' => 'Category Temporal'
);
$response = $this->post('api/categories', $category);
$response->assertStatus(201);
$this->assertDatabaseHas('categories', $category);
}
}
|
<?php
namespace Tests\Feature;
use App\User;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class CategoryTest extends TestCase
{
private function createUser()
{
// Creating an temporal user
return User::create( [
'name' => 'Temporal',
'email' => 'temporal@gmail.com',
'password' => bcrypt('secret'),
] );
}
/**
* A basic test example.
*
* @depends testCreateUser
*
* @param User $user
*
* @return void
*/
public function testCreateCategory(User $user)
{
$temporal_category = [
'user_id' => $user->id,
'name' => 'Temporal Category',
];
$category = $this->post('api/categories', $temporal_category);
$category->assertStatus(201);
$this->assertDatabaseHas('categories', $temporal_category);
}
}
|
Use the correct topic->routing key replacement.
|
'use strict';
var debug = require('debug')('frontend:mqtt');
var express = require('express');
var router = express.Router();
var auth = require('../../passport');
var restUtils = require('../utils');
var os = require('os');
router.post('/mqtt', auth.requireAPIAuth(), function(req, res) {
var userId = req.user.id;
var topic = req.query.topic;
var payload = req.body;
if (typeof payload === 'object') {
payload = JSON.stringify(payload);
}
var routingKey = userId + '.' + topic.replace(/\//g, '.');
req.app.get('service').facet('amqp').then(function(amqp) {
amqp.publish('amq.topic', routingKey, new Buffer(payload));
debug('Publishing to routing key', routingKey, 'payload', payload);
restUtils.standardResponse(res, { "success": true }, {type: 'object'});
});
});
module.exports = function(parent) {
parent.use(router);
};
|
'use strict';
var debug = require('debug')('frontend:mqtt');
var express = require('express');
var router = express.Router();
var auth = require('../../passport');
var restUtils = require('../utils');
var os = require('os');
router.post('/mqtt', auth.requireAPIAuth(), function(req, res) {
var userId = req.user.id;
var topic = req.query.topic;
var payload = req.body;
if (typeof payload === 'object') {
payload = JSON.stringify(payload);
}
var routingKey = userId + '.' + topic.replace('/', '.');
req.app.get('service').facet('amqp').then(function(amqp) {
amqp.publish('amq.topic', routingKey, new Buffer(payload));
debug('Publishing to routing key', routingKey, 'payload', payload);
restUtils.standardResponse(res, { "success": true }, {type: 'object'});
});
});
module.exports = function(parent) {
parent.use(router);
};
|
Make Headroom pin even if scroll position has not changed
|
(function() {
// construct Headroom
var headroom = new Headroom(document.querySelector(".js-nvbr"), {
"offset": Options.navbarOffset,
"tolerance": Options.navbarTolerance
});
// initialize Headroom
headroom.init();
// add click events to sidebar nav links
document.addEventListener("DOMContentLoaded", function() {
// choose elements to add click event to
var elements = document.getElementsByClassName("x2b-sdbr-lnk");
// iterate over elements
for (var i = 0; elements[i]; ++i) {
// add click event
elements[i].onclick = function() {
// fudge scroll position to make Headroom pin
headroom.lastKnownScrollY = headroom.getScrollerHeight();
// make Headroom pin even if scroll position has not changed
window.requestAnimationFrame(function() { headroom.pin() });
}
}
});
})();
|
(function() {
// construct Headroom
var headroom = new Headroom(document.querySelector(".js-nvbr"), {
"offset": Options.navbarOffset,
"tolerance": Options.navbarTolerance
});
// initialize Headroom
headroom.init();
// add click events to sidebar nav links
document.addEventListener("DOMContentLoaded", function() {
// choose elements to add click event to
var elements = document.getElementsByClassName("x2b-sdbr-lnk");
// iterate over elements
for (var i = 0; elements[i]; ++i) {
// add click event
elements[i].onclick = function() {
// fudge scroll position to make Headroom pin
headroom.lastKnownScrollY = headroom.getScrollerHeight();
}
}
});
})();
|
Reset in Reminders in Portuguese
|
<?php
return array(
/*
|--------------------------------------------------------------------------
| Password Reminder Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are the default lines which match reasons
| that are given by the password broker for a password update attempt
| has failed, such as for an invalid token or invalid new password.
|
*/
"password" => "A senha deverá conter pelo menos seis carateres e ser igual à confirmação.",
"user" => "Não conseguimos encontrar nenhum usuário com o endereço de email indicado.",
"token" => "Este código de recuperação da senha é inválido.",
"sent" => "O lembrete da senha foi enviado!",
"reset" => "A senha foi redefinida!",
);
|
<?php
return array(
/*
|--------------------------------------------------------------------------
| Password Reminder Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are the default lines which match reasons
| that are given by the password broker for a password update attempt
| has failed, such as for an invalid token or invalid new password.
|
*/
"password" => "A senha deverá conter pelo menos seis carateres e ser igual à confirmação.",
"user" => "Não conseguimos encontrar nenhum usuário com o endereço de email indicado.",
"token" => "Este código de recuperação da senha é inválido.",
"sent" => "O lembrete da senha foi enviado!",
"reset" => "Password has been reset!",
);
|
Improve EEXIST error message for copySync
|
var fs = require('graceful-fs')
var BUF_LENGTH = 64 * 1024
var _buff = new Buffer(BUF_LENGTH)
function copyFileSync (srcFile, destFile, options) {
var clobber = options.clobber
var preserveTimestamps = options.preserveTimestamps
if (fs.existsSync(destFile)) {
if (clobber) {
fs.chmodSync(destFile, parseInt('777', 8))
fs.unlinkSync(destFile)
} else {
var err = new Error('EEXIST: ' + destFile + ' already exists.')
err.code = 'EEXIST'
err.errno = -17
err.path = destFile
throw err
}
}
var fdr = fs.openSync(srcFile, 'r')
var stat = fs.fstatSync(fdr)
var fdw = fs.openSync(destFile, 'w', stat.mode)
var bytesRead = 1
var pos = 0
while (bytesRead > 0) {
bytesRead = fs.readSync(fdr, _buff, 0, BUF_LENGTH, pos)
fs.writeSync(fdw, _buff, 0, bytesRead)
pos += bytesRead
}
if (preserveTimestamps) {
fs.futimesSync(fdw, stat.atime, stat.mtime)
}
fs.closeSync(fdr)
fs.closeSync(fdw)
}
module.exports = copyFileSync
|
var fs = require('graceful-fs')
var BUF_LENGTH = 64 * 1024
var _buff = new Buffer(BUF_LENGTH)
function copyFileSync (srcFile, destFile, options) {
var clobber = options.clobber
var preserveTimestamps = options.preserveTimestamps
if (fs.existsSync(destFile)) {
if (clobber) {
fs.chmodSync(destFile, parseInt('777', 8))
fs.unlinkSync(destFile)
} else {
throw Error('EEXIST')
}
}
var fdr = fs.openSync(srcFile, 'r')
var stat = fs.fstatSync(fdr)
var fdw = fs.openSync(destFile, 'w', stat.mode)
var bytesRead = 1
var pos = 0
while (bytesRead > 0) {
bytesRead = fs.readSync(fdr, _buff, 0, BUF_LENGTH, pos)
fs.writeSync(fdw, _buff, 0, bytesRead)
pos += bytesRead
}
if (preserveTimestamps) {
fs.futimesSync(fdw, stat.atime, stat.mtime)
}
fs.closeSync(fdr)
fs.closeSync(fdw)
}
module.exports = copyFileSync
|
Disable back button for thank-you frame
Do not allow participants to click the back
button after completing the study.
|
import Ember from 'ember';
export default Ember.Route.extend({
setupController(controller, session) {
this._super(controller, session);
controller.set('experiment', this.controllerFor('participate.survey').get('experiment'));
controller.set('session', session);
controller.set('pastSessions', []);
},
actions: {
willTransition(transition) {
this._super(transition);
if (transition.targetName === 'participate.survey.results' || transition.targetName === 'exit') {
return true;
}
var frameIndex = this.controllerFor('participate.survey.index').get('frameIndex');
var framePage = this.controllerFor('participate.survey.index').get('framePage');
if (frameIndex !== 0) {
this.replaceWith('participate.survey.index');
// Disable back button in qsort page 2, rating-form page 1, and thank-you page
if (!(frameIndex === 2 && framePage === 1) && frameIndex !== 3 && frameIndex !== 4) {
this.controllerFor('participate.survey.index').set('frameIndex', frameIndex - 1);
}
// Update pages within the rating-form
if (frameIndex === 3 && framePage !== 0) {
this.controllerFor('participate.survey.index').set('framePage', framePage - 1);
}
}
}
}
});
|
import Ember from 'ember';
export default Ember.Route.extend({
setupController(controller, session) {
this._super(controller, session);
controller.set('experiment', this.controllerFor('participate.survey').get('experiment'));
controller.set('session', session);
controller.set('pastSessions', []);
},
actions: {
willTransition(transition) {
this._super(transition);
if (transition.targetName === 'participate.survey.results' || transition.targetName === 'exit') {
return true;
}
var frameIndex = this.controllerFor('participate.survey.index').get('frameIndex');
var framePage = this.controllerFor('participate.survey.index').get('framePage');
if (frameIndex !== 0) {
this.replaceWith('participate.survey.index');
// Disable back button in qsort page 2, and rating-form page 1
if (!(frameIndex === 2 && framePage === 1) && frameIndex !== 3) {
this.controllerFor('participate.survey.index').set('frameIndex', frameIndex - 1);
}
// Update pages within the rating-form
if (frameIndex === 3 && framePage !== 0) {
this.controllerFor('participate.survey.index').set('framePage', framePage - 1);
}
}
}
}
});
|
Exit after redirecting to prevent to entire application from being executed.
|
<?php
/*
* This file is part of Fork CMS.
*
* For the full copyright and license information, please view the license
* file that was distributed with this source code.
*/
// vendors not installed
if(!is_dir(__DIR__ . '/vendor'))
{
echo 'You are missing some dependencies. Please run <code>composer install</code>.';
exit;
}
// Fork has not yet been installed
$installer = dirname(__FILE__) . '/install/cache';
if(
file_exists($installer) &&
is_dir($installer) &&
!file_exists($installer . '/installed.txt') &&
substr($_SERVER['REQUEST_URI'], 0, 8) != '/install'
)
{
header('Location: /install');
exit;
}
use Symfony\Component\HttpFoundation\Request;
require_once __DIR__ . '/autoload.php';
require_once __DIR__ . '/app/AppKernel.php';
$kernel = new AppKernel();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
|
<?php
/*
* This file is part of Fork CMS.
*
* For the full copyright and license information, please view the license
* file that was distributed with this source code.
*/
// vendors not installed
if(!is_dir(__DIR__ . '/vendor'))
{
echo 'You are missing some dependencies. Please run <code>composer install</code>.';
exit;
}
// Fork has not yet been installed
$installer = dirname(__FILE__) . '/install/cache';
if(
file_exists($installer) &&
is_dir($installer) &&
!file_exists($installer . '/installed.txt') &&
substr($_SERVER['REQUEST_URI'], 0, 8) != '/install'
)
{
header('Location: /install');
}
use Symfony\Component\HttpFoundation\Request;
require_once __DIR__ . '/autoload.php';
require_once __DIR__ . '/app/AppKernel.php';
$kernel = new AppKernel();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
|
Update humanize requirement from <0.6,>=0.5.1 to >=0.5.1,<1.1
Updates the requirements on [humanize](https://github.com/jmoiron/humanize) to permit the latest version.
- [Release notes](https://github.com/jmoiron/humanize/releases)
- [Commits](https://github.com/jmoiron/humanize/compare/0.5.1...1.0.0)
Signed-off-by: dependabot-preview[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com>
|
from setuptools import setup, find_packages
setup(
name='panoptescli',
version='1.1.1',
url='https://github.com/zooniverse/panoptes-cli',
author='Adam McMaster',
author_email='adam@zooniverse.org',
description=(
'A command-line client for Panoptes, the API behind the Zooniverse'
),
packages=find_packages(),
include_package_data=True,
install_requires=[
'Click>=6.7,<7.1',
'PyYAML>=5.1,<5.4',
'panoptes-client>=1.0,<2.0',
'humanize>=0.5.1,<1.1',
'pathvalidate>=0.29.0,<0.30',
],
entry_points='''
[console_scripts]
panoptes=panoptes_cli.scripts.panoptes:cli
''',
)
|
from setuptools import setup, find_packages
setup(
name='panoptescli',
version='1.1.1',
url='https://github.com/zooniverse/panoptes-cli',
author='Adam McMaster',
author_email='adam@zooniverse.org',
description=(
'A command-line client for Panoptes, the API behind the Zooniverse'
),
packages=find_packages(),
include_package_data=True,
install_requires=[
'Click>=6.7,<7.1',
'PyYAML>=5.1,<5.4',
'panoptes-client>=1.0,<2.0',
'humanize>=0.5.1,<0.6',
'pathvalidate>=0.29.0,<0.30',
],
entry_points='''
[console_scripts]
panoptes=panoptes_cli.scripts.panoptes:cli
''',
)
|
Work around the usual long/int issues
|
/*******************************************************************************
* Copyright (c) 2010-2015, Benedek Izso, Gabor Szarnyas, Istvan Rath and Daniel Varro
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Benedek Izso - initial API and implementation
* Gabor Szarnyas - initial API and implementation
*******************************************************************************/
package hu.bme.mit.trainbenchmark.benchmark.neo4j.comparators;
import hu.bme.mit.trainbenchmark.constants.ModelConstants;
import org.neo4j.graphdb.Node;
import java.util.Comparator;
public class NodeComparator implements Comparator<Node> {
@Override
public int compare(final Node node1, final Node node2) {
final long id1 = getLongId(node1);
final long id2 = getLongId(node2);
return Long.compare(id1, id2);
}
private long getLongId(Node node) {
Object o = node.getProperty(ModelConstants.ID);
if (o instanceof Long) {
return (Long) o;
}
if (o instanceof Integer) {
return Long.valueOf((Integer) o);
}
throw new IllegalStateException("ID should be int or long");
}
}
|
/*******************************************************************************
* Copyright (c) 2010-2015, Benedek Izso, Gabor Szarnyas, Istvan Rath and Daniel Varro
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Benedek Izso - initial API and implementation
* Gabor Szarnyas - initial API and implementation
*******************************************************************************/
package hu.bme.mit.trainbenchmark.benchmark.neo4j.comparators;
import hu.bme.mit.trainbenchmark.constants.ModelConstants;
import org.neo4j.graphdb.Node;
import java.util.Comparator;
public class NodeComparator implements Comparator<Node> {
@Override
public int compare(final Node node1, final Node node2) {
final long id1 = (Long) node1.getProperty(ModelConstants.ID);
final long id2 = (Long) node2.getProperty(ModelConstants.ID);
return Long.compare(id1, id2);
}
}
|
Store the author id in the local storage
|
var createEditor;
var author;
function injectCreate(id) {
$("#" + id).load("create/html/createHTML", function() {
injectCreateEditor();
// Check to see if we already have an author ID
if (localStorage.getItem('author')) {
// Reuse the same author ID
author = localStorage.getItem('todos');
}
else {
// Generate a random number from 1 to 10000
author = Math.floor((Math.random() * 10000) + 1);
localStorage.setItem('author', author);
}
});
}
function injectCreateEditor() {
Range = ace.require('ace/range').Range;
createEditor = ace.edit("editor");
createEditor.setTheme("ace/theme/github");
// Set this to RESOLVE mode
var ResolveMode = ace.require("ace/mode/resolve").Mode;
createEditor.session.setMode(new ResolveMode());
// Gets rid of a weird Ace Editor bug
//createEditor.$blockScrolling = Infinity;
createEditor.getSession().on('change', removeAllVCMarkers);
createEditor.setFontSize(18);
}
|
var createEditor;
var author;
function injectCreate(id) {
$("#" + id).load("create/html/createHTML", function() {
injectCreateEditor();
// Generate a random number from 1 to 10000
author = Math.floor((Math.random() * 10000) + 1);
});
}
function injectCreateEditor() {
Range = ace.require('ace/range').Range;
createEditor = ace.edit("editor");
createEditor.setTheme("ace/theme/github");
// Set this to RESOLVE mode
var ResolveMode = ace.require("ace/mode/resolve").Mode;
createEditor.session.setMode(new ResolveMode());
// Gets rid of a weird Ace Editor bug
//createEditor.$blockScrolling = Infinity;
createEditor.getSession().on('change', removeAllVCMarkers);
createEditor.setFontSize(18);
}
|
Remove useless assertion in test
|
package cgeo.geocaching;
import static org.assertj.core.api.Assertions.assertThat;
import cgeo.geocaching.connector.gc.GCConstants;
import cgeo.geocaching.maps.mapsforge.MapsforgeMapProvider;
import cgeo.geocaching.settings.Settings;
import android.annotation.TargetApi;
import android.test.ActivityInstrumentationTestCase2;
@TargetApi(8)
public class SettingsTest extends ActivityInstrumentationTestCase2<MainActivity> {
public SettingsTest() {
super(MainActivity.class);
}
/**
* access settings.
* this should work fine without an exception (once there was an exception because of the empty map file string)
*/
public static void testSettingsException() {
// We just want to ensure that it does not throw any exception but we do not know anything about the result
MapsforgeMapProvider.isValidMapFile(Settings.getMapFile());
}
public static void testSettings() {
// unfortunately, several other tests depend on being a premium member and will fail if run by a basic member
assertThat(Settings.getGCMemberStatus()).isEqualTo(GCConstants.MEMBER_STATUS_PM);
}
public static void testDeviceHasNormalLogin() {
// if the unit tests were interrupted in a previous run, the device might still have the "temporary" login data from the last tests
assertThat("c:geo".equals(Settings.getUsername())).isFalse();
}
}
|
package cgeo.geocaching;
import static org.assertj.core.api.Assertions.assertThat;
import cgeo.geocaching.connector.gc.GCConstants;
import cgeo.geocaching.maps.mapsforge.MapsforgeMapProvider;
import cgeo.geocaching.settings.Settings;
import android.annotation.TargetApi;
import android.test.ActivityInstrumentationTestCase2;
@TargetApi(8)
public class SettingsTest extends ActivityInstrumentationTestCase2<MainActivity> {
public SettingsTest() {
super(MainActivity.class);
}
/**
* access settings.
* this should work fine without an exception (once there was an exception because of the empty map file string)
*/
public static void testSettingsException() {
final String mapFile = Settings.getMapFile();
// We just want to ensure that it does not throw any exception but we do not know anything about the result
MapsforgeMapProvider.isValidMapFile(mapFile);
assertThat(true).isTrue();
}
public static void testSettings() {
// unfortunately, several other tests depend on being a premium member and will fail if run by a basic member
assertThat(Settings.getGCMemberStatus()).isEqualTo(GCConstants.MEMBER_STATUS_PM);
}
public static void testDeviceHasNormalLogin() {
// if the unit tests were interrupted in a previous run, the device might still have the "temporary" login data from the last tests
assertThat("c:geo".equals(Settings.getUsername())).isFalse();
}
}
|
Correct rendering of "Another Herald Rule" conditions in Herald
Summary: Fixes T8920. These are semi-magical and need to be slightly special cased, now.
Test Plan: {F654502}
Reviewers: chad, btrahan
Reviewed By: btrahan
Subscribers: epriestley
Maniphest Tasks: T8920
Differential Revision: https://secure.phabricator.com/D13696
|
<?php
final class HeraldAnotherRuleField extends HeraldField {
const FIELDCONST = 'rule';
public function getHeraldFieldName() {
return pht('Another Herald rule');
}
public function getFieldGroupKey() {
return HeraldBasicFieldGroup::FIELDGROUPKEY;
}
public function supportsObject($object) {
return true;
}
public function getHeraldFieldValue($object) {
return null;
}
public function getHeraldFieldConditions() {
return array(
HeraldAdapter::CONDITION_RULE,
HeraldAdapter::CONDITION_NOT_RULE,
);
}
public function getHeraldFieldValueType($condition) {
// NOTE: This is a bit magical because we don't currently have a reasonable
// way to populate it from here.
return id(new HeraldSelectFieldValue())
->setKey(self::FIELDCONST)
->setOptions(array());
}
public function renderConditionValue(
PhabricatorUser $viewer,
$condition,
$value) {
$value = (array)$value;
return $viewer->renderHandleList($value);
}
}
|
<?php
final class HeraldAnotherRuleField extends HeraldField {
const FIELDCONST = 'rule';
public function getHeraldFieldName() {
return pht('Another Herald rule');
}
public function getFieldGroupKey() {
return HeraldBasicFieldGroup::FIELDGROUPKEY;
}
public function supportsObject($object) {
return true;
}
public function getHeraldFieldValue($object) {
return null;
}
public function getHeraldFieldConditions() {
return array(
HeraldAdapter::CONDITION_RULE,
HeraldAdapter::CONDITION_NOT_RULE,
);
}
public function getHeraldFieldValueType($condition) {
// NOTE: This is a bit magical because we don't currently have a reasonable
// way to populate it from here.
return id(new HeraldSelectFieldValue())
->setKey(self::FIELDCONST)
->setOptions(array());
}
}
|
Use "cythonize" if Cython is installed.
|
from distutils.core import Extension, setup
try:
from Cython.Build import cythonize
from Cython.Distutils import build_ext
except ImportError:
use_cython = False
else:
use_cython = True
if use_cython:
extensions = cythonize([
Extension('mathix.vector', ['mathix/vector.pyx']),
])
cmdclass = {
'build_ext': build_ext
}
else:
extensions = [
Extension('mathix.vector', ['mathix/vector.c']),
]
cmdclass = {}
setup(
name='mathix',
author='Peith Vergil',
version='0.1',
license='MIT',
cmdclass=cmdclass,
packages=[
'mathix',
],
keywords='useless simple math library',
description='A useless simple math library.',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Programming Language :: Cython',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
ext_modules=extensions
)
|
from distutils.core import Extension, setup
try:
from Cython.Distutils import build_ext
except ImportError:
use_cython = False
else:
use_cython = True
if use_cython:
extensions = [
Extension('mathix.vector', ['mathix/vector.pyx']),
]
cmdclass = {
'build_ext': build_ext
}
else:
extensions = [
Extension('mathix.vector', ['mathix/vector.c']),
]
cmdclass = {}
setup(
name='mathix',
author='Peith Vergil',
version='0.1',
license='MIT',
cmdclass=cmdclass,
packages=[
'mathix',
],
keywords='useless simple math library',
description='A useless simple math library.',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Programming Language :: Cython',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
ext_modules=extensions
)
|
Check rock-csrf else throw Exception.
|
<?php
namespace rock\validate\rules;
use rock\validate\ValidateException;
class CSRF extends Rule
{
/** @var string|array|\rock\csrf\CSRF */
public $csrf = 'csrf';
public function init()
{
if (!is_object($this->csrf)) {
if (class_exists('\rock\di\Container')) {
$this->csrf = \rock\di\Container::load($this->csrf);
return;
}
throw new ValidateException(ValidateException::NOT_INSTALL_CSRF);
}
}
/**
* @inheritdoc
*/
public function validate($input)
{
return $this->csrf->valid($input);
}
}
|
<?php
namespace rock\validate\rules;
use rock\validate\ValidateException;
class CSRF extends Rule
{
/**
* @inheritdoc
*/
public function validate($input)
{
return $this->getCSRF()->valid($input);
}
/**
* Get CSRF.
*
* If exists {@see \rock\di\Container} that uses it.
*
* @return \rock\csrf\CSRF
* @throws \rock\di\ContainerException
*/
protected function getCSRF()
{
if (class_exists('\rock\di\Container')) {
return \rock\di\Container::load('csrf');
}
if (class_exists('\rock\csrf\CSRF')) {
return new \rock\csrf\CSRF();
}
throw new ValidateException(ValidateException::UNKNOWN_CLASS, ['class' => '\rock\csrf\CSRF']);
}
}
|
Provision of middleware now requires function to allow request to be passed in on server-side
|
import {createStore, combineReducers, compose, applyMiddleware} from 'redux';
import {routerReducer, routerMiddleware} from 'react-router-redux';
import {reducer as reduxAsyncConnect} from 'redux-connect';
import thunkMiddleware from 'redux-thunk';
function configureStoreCreator(reducers, middleware = () => [thunkMiddleware]) {
const reducer = combineReducers({
routing: routerReducer,
reduxAsyncConnect,
...reducers
});
return (forClient, history, initialState = {}, req) => {
const devToolsEnhancer = forClient && window.devToolsExtension ? window.devToolsExtension() : f => f;
return createStore(
reducer,
initialState,
compose(
applyMiddleware(
...middleware(req),
routerMiddleware(history)
),
devToolsEnhancer
)
);
};
}
export default configureStoreCreator;
|
import {createStore, combineReducers, compose, applyMiddleware} from 'redux';
import {routerReducer, routerMiddleware} from 'react-router-redux';
import {reducer as reduxAsyncConnect} from 'redux-connect';
import thunkMiddleware from 'redux-thunk';
function configureStoreCreator(reducers, middleware = [thunkMiddleware]) {
const reducer = combineReducers({
routing: routerReducer,
reduxAsyncConnect,
...reducers
});
return (forClient, history, initialState = {}) => {
const devToolsEnhancer = forClient && window.devToolsExtension ? window.devToolsExtension() : f => f;
return createStore(
reducer,
initialState,
compose(
applyMiddleware(
...middleware,
routerMiddleware(history)
),
devToolsEnhancer
)
);
};
}
export default configureStoreCreator;
|
Fix installation, broken since started doing import in __init__
Thanks @myint for the catch and code suggestion
|
from setuptools import setup
import ast
import os
def version():
"""Return version string."""
with open(os.path.join('curtsies', '__init__.py')) as input_file:
for line in input_file:
if line.startswith('__version__'):
return ast.parse(line).body[0].value.s
setup(name='curtsies',
version=version(),
description='Curses-like terminal wrapper, with colored strings!',
url='https://github.com/thomasballinger/curtsies',
author='Thomas Ballinger',
author_email='thomasballinger@gmail.com',
license='MIT',
packages=['curtsies'],
install_requires = [
'blessings==1.5.1'
],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python',
],
zip_safe=False)
|
from setuptools import setup
import curtsies
setup(name='curtsies',
version=curtsies.__version__,
description='Curses-like terminal wrapper, with colored strings!',
url='https://github.com/thomasballinger/curtsies',
author='Thomas Ballinger',
author_email='thomasballinger@gmail.com',
license='MIT',
packages=['curtsies'],
install_requires = [
'blessings==1.5.1'
],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python',
],
zip_safe=False)
|
Fix access error by removing old $_SESSION['user'] references
|
<?php
@session_start();
require_once "php/config.php" ;
if ($_SESSION['user_id'] && $_SESSION['access_level']==100){
$DBDEF=array(
'user'=>$CONFIG['DB']['USER'],#required
'pwd'=>$CONFIG['DB']['PWD'], #required
'db'=>$CONFIG['DB']['DBNAME'], #optional, default DB
'host'=>$CONFIG['DB']['HOST'],#optional
'port'=>$CONFIG['DB']['PORT'],#optional
'chset'=>"utf8",#optional, default charset
);
loadcfg();
if (!isset($_REQUEST['q'])) {
$_REQUEST['XSS']=$_SESSION['XSS'];
$_REQUEST['q']=b64e('SHOW TABLE STATUS');
}
}else{
#$ACCESS_PWD=''; #set Access password here to enable access to database as non-logged admin
if (!$ACCESS_PWD){
rw("Set \$ACCESS_PWD or login to site as an Administrator");
exit;
}
}
?>
|
<?php
@session_start();
require_once "php/config.php" ;
if ($_SESSION['user'] && $_SESSION['user']['id'] && $_SESSION['access_level']==100){
$DBDEF=array(
'user'=>$CONFIG['DB']['USER'],#required
'pwd'=>$CONFIG['DB']['PWD'], #required
'db'=>$CONFIG['DB']['DBNAME'], #optional, default DB
'host'=>$CONFIG['DB']['HOST'],#optional
'port'=>$CONFIG['DB']['PORT'],#optional
'chset'=>"utf8",#optional, default charset
);
loadcfg();
if (!isset($_REQUEST['q'])) {
$_REQUEST['XSS']=$_SESSION['XSS'];
$_REQUEST['q']=b64e('SHOW TABLE STATUS');
}
}else{
#$ACCESS_PWD=''; #set Access password here to enable access to database as non-logged admin
if (!$ACCESS_PWD){
rw("Set \$ACCESS_PWD or login to site as an Administrator");
exit;
}
}
?>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.