text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Check worker's FQDN against username.
|
# -*- coding: utf-8 -*-
import socket
from django.core.exceptions import PermissionDenied, SuspiciousOperation
from kobo.decorators import decorator_with_args
from kobo.django.xmlrpc.decorators import *
def validate_worker(func):
def _new_func(request, *args, **kwargs):
if not request.user.is_authenticated():
raise PermissionDenied("Login required.")
if getattr(request, 'worker', None) is None:
raise SuspiciousOperation("User doesn't match any worker: %s" % request.user.username)
fqdn = socket.getfqdn(request.META["REMOTE_ADDR"])
prefix, hostname = request.user.username.split("/", 1)
if hostname != fqdn:
raise SuspiciousOperation("Worker's FQDN (%s) doesn't match username (%s)" % (fqdn, hostname))
return func(request, *args, **kwargs)
_new_func.__name__ = func.__name__
_new_func.__doc__ = func.__doc__
_new_func.__dict__.update(func.__dict__)
return _new_func
|
# -*- coding: utf-8 -*-
from django.core.exceptions import PermissionDenied, SuspiciousOperation
from kobo.decorators import decorator_with_args
from kobo.django.xmlrpc.decorators import *
def validate_worker(func):
def _new_func(request, *args, **kwargs):
if not request.user.is_authenticated():
raise PermissionDenied("Login required.")
if getattr(request, 'worker', None) is None:
raise SuspiciousOperation("User doesn't match any worker: %s" % request.user.username)
return func(request, *args, **kwargs)
_new_func.__name__ = func.__name__
_new_func.__doc__ = func.__doc__
_new_func.__dict__.update(func.__dict__)
return _new_func
|
PI-27: Disable debug_toolbar from catching http redirects...pretty annoying
|
# Grab the base settings
from .base import *
# Override at will!
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ['*']
##
#
##
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'stackdio',
'HOST': 'localhost',
'PORT': '3306',
'USER': getenv('MYSQL_USER'),
'PASSWORD': getenv('MYSQL_PASS'),
}
}
##
# Celery & RabbitMQ
##
BROKER_URL = 'amqp://guest:guest@localhost:5672/'
##
# Add in additional middleware
##
MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',)
##
# Add in additional applications
##
INSTALLED_APPS += ('debug_toolbar',)
##
# For debug_toolbar to load
##
INTERNAL_IPS = ('127.0.0.1',)
##
# debug_toolbar configuration
##
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': False,
}
##
# The local storage directory for storing file data
##
FILE_STORAGE_DIRECTORY = normpath(join(SITE_ROOT, 'storage'))
|
# Grab the base settings
from .base import *
# Override at will!
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ['*']
##
#
##
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'stackdio',
'HOST': 'localhost',
'PORT': '3306',
'USER': getenv('MYSQL_USER'),
'PASSWORD': getenv('MYSQL_PASS'),
}
}
##
# Celery & RabbitMQ
##
BROKER_URL = 'amqp://guest:guest@localhost:5672/'
##
# Add in additional middleware
##
MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',)
##
# Add in additional applications
##
INSTALLED_APPS += ('debug_toolbar',)
##
# For debug_toolbar to load
##
INTERNAL_IPS = ('127.0.0.1',)
##
# The local storage directory for storing file data
##
FILE_STORAGE_DIRECTORY = normpath(join(SITE_ROOT, 'storage'))
|
Use nonsense board name, no localStorage
|
import Firebase from 'firebase'
import Vue from 'vue'
import VueRouter from 'vue-router'
import nonsense from './nonsense'
import App from './App.vue'
window.randomSet = nonsense.randomSet
window.randomNumber = nonsense.randomNumber
Vue.use(VueRouter)
let router = new VueRouter({
hashboang: false,
history: true,
})
let MEGAKanban = Vue.extend({})
let Redirect = Vue.extend({
ready() {
let boardName = this.randomName()
router.go(boardName)
},
methods: {
randomName() {
return nonsense.randomSet()
.concat(nonsense.randomNumber())
.join('-')
}
}
})
router.map({
'/': {
name: 'root',
component: Redirect
},
'/:board': {
name: 'board',
component: App
}
})
router.start(MEGAKanban, '#main')
|
import Firebase from 'firebase'
import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'
Vue.use(VueRouter)
let router = new VueRouter({
hashboang: false,
history: true,
})
let MEGAKanban = Vue.extend({})
let Redirect = Vue.extend({
ready() {
let boardName = localStorage.getItem('MEGAKanban_board')
if (!boardName) {
boardName = this.randomName()
localStorage.setItem('MEGAKanban_board', boardName)
}
router.go(boardName)
},
methods: {
// generate board name using timestamp
// @todo: generate memorable names
randomName() {
let now = new Date()
return btoa(now)
}
}
})
router.map({
'/': {
name: 'root',
component: Redirect
},
'/:board': {
name: 'board',
component: App
}
})
router.start(MEGAKanban, '#main')
|
Fix app title link not working with ‘source’ query paremeter
|
import Ember from 'ember';
import OsfAgnosticAuthControllerMixin from 'ember-osf/mixins/osf-agnostic-auth-controller';
import {
getAuthUrl
} from 'ember-osf/utils/auth';
export default Ember.Controller.extend(OsfAgnosticAuthControllerMixin,{
toast: Ember.inject.service(),
authUrl: getAuthUrl(),
actions: {
loginSuccess() {
// this.transitionToRoute('researcher.grant');
},
loginFail(/* err */) {
this.get('toast').error('Login failed');
},
transitionToHome(){
this.transitionToRoute('dashboards.dashboard', 'institution');
}
}
});
|
import Ember from 'ember';
import OsfAgnosticAuthControllerMixin from 'ember-osf/mixins/osf-agnostic-auth-controller';
import {
getAuthUrl
} from 'ember-osf/utils/auth';
export default Ember.Controller.extend(OsfAgnosticAuthControllerMixin,{
toast: Ember.inject.service(),
authUrl: getAuthUrl(),
actions: {
loginSuccess() {
// this.transitionToRoute('researcher.grant');
},
loginFail(/* err */) {
this.get('toast').error('Login failed');
},
transitionToHome(){
debugger;
this.transitionToRoute('dashboards.dashboard', 'institution', {
queryParams: {all : 'ucsd'}
});
}
}
});
|
Rename console entry point from __main__ to cli
|
from setuptools import setup, find_packages
setup(name='pyscores',
version='0.2',
description='Football (soccer) scores in your command line',
url='https://github.com/conormag94/pyscores',
author='Conor Maguire',
author_email='conormag94@gmail.com',
license='MIT',
packages=find_packages(),
entry_points={
'console_scripts': [
'scores=pyscores.cli:main'
]
},
install_requires=[
'click==5.1',
'requests==2.8.1',
'tabulate==0.7.5',
'termcolor==1.1.0'
])
|
from setuptools import setup, find_packages
setup(name='pyscores',
version='0.2',
description='Football (soccer) scores in your command line',
url='https://github.com/conormag94/pyscores',
author='Conor Maguire',
author_email='conormag94@gmail.com',
license='MIT',
packages=find_packages(),
entry_points={
'console_scripts': [
'scores=pyscores.__main__:main'
]
},
install_requires=[
'click==5.1',
'requests==2.8.1',
'tabulate==0.7.5',
'termcolor==1.1.0'
])
|
Fix the Redis client connection to actually work
It previously lied.
|
import txredisapi as redis
from twisted.internet import defer, reactor
import config
connection = None
def run_redis_client(on_started):
df = redis.makeConnection(config.redis['host'],
config.redis['port'],
config.redis['db'],
poolsize = 8,
reconnect = True,
isLazy = False)
def done(pony):
global connection
connection = pony
on_started()
df.addCallback(done)
|
import txredisapi as redis
from twisted.internet import defer, reactor
import config
connection = None
@defer.inlineCallbacks
def run_redis_client(on_started):
pony = yield redis.makeConnection(config.redis['host'],
config.redis['port'],
config.redis['db'],
poolsize = 8,
reconnect = True,
isLazy = True)
global connection
connection = pony
on_started()
|
Add test for setting a property on a model
|
<?php
use PhilipBrown\CapsuleCRM\Connection;
class ModelTest extends PHPUnit_Framework_TestCase {
public function setUp()
{
$this->model = new ModelStub(new Connection('', ''), ['name' => 'Philip Brown']);
}
public function testConnectionMethodHasConnection()
{
$this->assertInstanceOf('PhilipBrown\CapsuleCRM\Connection', $this->model->connection());
}
public function testSettingAnArrayOfAttributes()
{
$this->assertEquals('Philip Brown', $this->model->name);
}
public function testSettingAProperty()
{
$this->model->email = 'phil@ipbrown.com';
$this->assertEquals('phil@ipbrown.com', $this->model->email);
}
public function testGetSingularEntityName()
{
$this->assertEquals('modelstubs', $this->model->base()->lowercase()->plural());
}
}
class ModelStub extends PhilipBrown\CapsuleCRM\Model {
protected $fillable = ['name', 'email'];
public function __construct(Connection $connection, $attributes = [])
{
parent::__construct($connection);
$this->fill($attributes);
}
}
|
<?php
use PhilipBrown\CapsuleCRM\Connection;
class ModelTest extends PHPUnit_Framework_TestCase {
public function setUp()
{
$this->model = new ModelStub(new Connection('', ''), ['name' => 'Philip Brown']);
}
public function testConnectionMethodHasConnection()
{
$this->assertInstanceOf('PhilipBrown\CapsuleCRM\Connection', $this->model->connection());
}
public function testSettingAnArrayOfAttributes()
{
$this->assertEquals('Philip Brown', $this->model->name);
}
public function testGetSingularEntityName()
{
$this->assertEquals('modelstubs', $this->model->base()->lowercase()->plural());
}
}
class ModelStub extends PhilipBrown\CapsuleCRM\Model {
protected $fillable = ['name'];
public function __construct(Connection $connection, $attributes = [])
{
parent::__construct($connection);
$this->fill($attributes);
}
}
|
Add support for save on Ctrl/Cmd+S
|
import React, { Component } from 'react';
import AceEditor from 'react-ace';
import githubTheme from 'brace/theme/github';
import markdownSyntax from 'brace/mode/markdown';
import styles from './CodeEditor.styl';
export default ({ file, onCodeChange, onSave }) => {
if (!file) return <div />;
const onLoad = (editor) => {
editor.commands.addCommand({
name: 'saveChanges',
bindKey: {
win: 'Ctrl-Enter|Ctrl-S',
mac: 'Ctrl-Enter|Command-Enter|Command-S'
},
exec: onSave
});
}
return (
<AceEditor
mode='markdown'
theme='github'
name='aceEditor'
value={file.content}
className={styles.aceEditor}
showPrintMargin={false}
editorProps={{$blockScrolling: Infinity}}
onLoad={onLoad}
onChange={onCodeChange}
/>
)
}
|
import React, { Component } from 'react';
import AceEditor from 'react-ace';
import githubTheme from 'brace/theme/github';
import markdownSyntax from 'brace/mode/markdown';
import styles from './CodeEditor.styl';
export default ({ file, onCodeChange, onSave }) => {
if (!file) return <div />;
const onLoad = (editor) => {
editor.commands.addCommand({
name: 'saveChanges',
bindKey: {win: 'Ctrl-Enter', mac: 'Ctrl-Enter|Command-Enter'},
exec: onSave
});
}
return (
<AceEditor
mode='markdown'
theme='github'
name='aceEditor'
value={file.content}
className={styles.aceEditor}
showPrintMargin={false}
editorProps={{$blockScrolling: Infinity}}
onLoad={onLoad}
onChange={onCodeChange}
/>
)
}
|
Remove language pair from counts
|
var _ = require('underscore'),
SHORT = _.template('Languages: jw.org: <%= jworg.total %>, <%= jworg.hasWebContent %> L1+, <%= jworg.isSign %> SLs, <%= jworg.isRTL %> RTL, <%= jworg.isSignWithWeb %> L1+ SLs; jwb: <%= jwb.web.total %>, <%= jwb.web.isSign %> SLs, <%= jwb.appletv.total %> AppleTV, <%= jwb.roku.total %> Roku'),
LONG = _.template('jw.org has <%= jworg.total %> languages with downloadable content, <%= jworg.hasWebContent %> of which have part of the actual site in their language. This includes <%= jworg.isSign %> sign languages with downloadable content, <%= jworg.isSignWithWeb %> of which have part of the actual site in their language. <%= jworg.isRTL %> of these languages are right-to-left.\n\nJW Broadcasting is available in <%= jwb.web.total %> languages, all of which have the monthly program. This includes <%= jwb.web.isSign %> sign languages.');
module.exports = {
SHORT: SHORT,
LONG: LONG,
};
|
var _ = require('underscore'),
SHORT = _.template('Languages: jw.org: <%= jworg.total %>, <%= jworg.hasWebContent %> L1+, <%= jworg.isSign %> SLs, <%= jworg.isRTL %> RTL, <%= jworg.isSignWithWeb %> L1+ SLs; jwb: <%= jwb.web.total %>, <%= jwb.web.isSign %> SLs, <%= jwb.appletv.total %> AppleTV, <%= jwb.roku.total %> Roku, <%= jwb.web.isLangPair %> pairs'),
LONG = _.template('jw.org has <%= jworg.total %> languages with downloadable content, <%= jworg.hasWebContent %> of which have part of the actual site in their language. This includes <%= jworg.isSign %> sign languages with downloadable content, <%= jworg.isSignWithWeb %> of which have part of the actual site in their language. <%= jworg.isRTL %> of these languages are right-to-left.\n\nJW Broadcasting is available in <%= jwb.web.total %> languages, all of which have the monthly program. This includes <%= jwb.web.isSign %> sign languages.');
module.exports = {
SHORT: SHORT,
LONG: LONG,
};
|
Remove unnecessary logging and increase timeout.
|
"use strict";
var fs = require('fs');
var should = require('chai').should();
var pdf2img = require('../index.js');
var input = __dirname + '/test.pdf';
pdf2img.setOptions({
outputdir: __dirname + '/output',
targetname: 'test'
});
describe('Split and covert pdf into images', function() {
it ('Create png files', function(done) {
this.timeout(100000);
pdf2img.convert(input, function(err, info) {
var n = 1;
info.forEach(function(file) {
file.page.should.equal(n);
file.name.should.equal('test_' + n + '.png');
if (n === 3) done();
n++;
});
});
});
it ('Create jpg files', function(done) {
this.timeout(100000);
pdf2img.setOptions({ type: 'jpg' });
pdf2img.convert(input, function(err, info) {
var n = 1;
info.forEach(function(file) {
file.page.should.equal(n);
file.name.should.equal('test_' + n + '.jpg');
if (n === 3) done();
n++;
});
});
});
});
|
"use strict";
var fs = require('fs');
var should = require('chai').should();
var pdf2img = require('../index.js');
var input = __dirname + '/test.pdf';
pdf2img.setOptions({
outputdir: __dirname + '/output',
targetname: 'test'
});
describe('Split and covert pdf into images', function() {
it ('Create png files', function(done) {
this.timeout(100000);
console.log(input);
pdf2img.convert(input, function(err, info) {
var n = 1;
console.log(info);
info.forEach(function(file) {
file.page.should.equal(n);
file.name.should.equal('test_' + n + '.png');
if (n === 3) done();
n++;
});
});
});
it ('Create jpg files', function(done) {
this.timeout(60000);
console.log(input);
pdf2img.setOptions({ type: 'jpg' });
pdf2img.convert(input, function(err, info) {
var n = 1;
info.forEach(function(file) {
file.page.should.equal(n);
file.name.should.equal('test_' + n + '.jpg');
if (n === 3) done();
n++;
});
});
});
});
|
Change output data structure to support faster rsync
|
import numpy as np
import os
import glob
import mdtraj as md
import fahmunge
import pandas as pd
projects = pd.read_csv("./projects.csv", index_col=0)
output_path = "/data/choderalab/fah/munged/"
for (project, location, pdb) in projects.itertuples():
print(project, location, pdb)
allatom_output_path = os.path.join(output_path, "allatoms/", "%s/" % project)
protein_output_path = os.path.join(output_path, "protein/", "%s/" % project)
fahmunge.automation.make_path(allatom_output_path)
fahmunge.automation.make_path(protein_output_path)
fahmunge.automation.merge_fah_trajectories(location, allatom_output_path, pdb)
trj0 = md.load(pdb) # Hacky temporary solution.
top, bonds = trj0.top.to_dataframe()
protein_atom_indices = top.index[top.chainID == 0].values
fahmunge.automation.strip_water(allatom_output_path, protein_output_path, protein_atom_indices)
|
import numpy as np
import os
import glob
import mdtraj as md
import fahmunge
import pandas as pd
projects = pd.read_csv("./projects.csv", index_col=0)
output_path = "/data/choderalab/fah/munged/"
for (project, location, pdb) in projects.itertuples():
print(project, location, pdb)
allatom_output_path = os.path.join(output_path, str(project), "allatoms/")
protein_output_path = os.path.join(output_path, str(project), "protein/")
fahmunge.automation.make_path(allatom_output_path)
fahmunge.automation.make_path(protein_output_path)
fahmunge.automation.merge_fah_trajectories(location, allatom_output_path, pdb)
trj0 = md.load(pdb) # Hacky temporary solution.
top, bonds = trj0.top.to_dataframe()
protein_atom_indices = top.index[top.chainID == 0].values
fahmunge.automation.strip_water(allatom_output_path, protein_output_path, protein_atom_indices)
|
Order secret behind folder breadcrumb in filtered views
|
import React, { PropTypes } from 'react';
import SecretListItemFolderSecret from 'components/secrets/SecretListItem/Secret';
import SecretListBreadcrumb from 'components/secrets/SecretListBreadcrumb';
const propTypes = {
folder: PropTypes.any,
};
function SecretListFolderInfo({ folder }) {
return (
<tbody className="secret-list-content-table-body">
{
!folder.has('root') &&
<tr className="secret-list-folder">
<td colSpan="4" className="secret-list-folder-info">
<SecretListBreadcrumb folders={folder.get('breadcrumb')} withTitle={false} />
</td>
</tr>
}
{
folder.get('secrets').sortBy(secret => secret.get('title').toLowerCase()).map(secret => (
<SecretListItemFolderSecret
key={secret.id}
secret={secret}
/>
)).toArray()
}
</tbody>
);
}
SecretListFolderInfo.propTypes = propTypes;
export default SecretListFolderInfo;
|
import React, { PropTypes } from 'react';
import SecretListItemFolderSecret from 'components/secrets/SecretListItem/Secret';
import SecretListBreadcrumb from 'components/secrets/SecretListBreadcrumb';
const propTypes = {
folder: PropTypes.any,
};
function SecretListFolderInfo({ folder }) {
return (
<tbody className="secret-list-content-table-body">
{
!folder.has('root') &&
<tr className="secret-list-folder">
<td colSpan="4" className="secret-list-folder-info">
<SecretListBreadcrumb folders={folder.get('breadcrumb')} withTitle={false} />
</td>
</tr>
}
{
folder.get('secrets').map(secret => (
<SecretListItemFolderSecret
key={secret.id}
secret={secret}
/>
)).toArray()
}
</tbody>
);
}
SecretListFolderInfo.propTypes = propTypes;
export default SecretListFolderInfo;
|
Load module language files using package and module name.
|
<?php
/**
* @version $Id$
* @package Nooku_Server
* @subpackage Pages
* @copyright Copyright (C) 2011 - 2012 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
/**
* Modules Html View Class
*
* @author Stian Didriksen <http://nooku.assembla.com/profile/stiandidriksen>
* @package Nooku_Server
* @subpackage Pages
*/
class ComPagesViewModulesHtml extends ComDefaultViewHtml
{
public function display()
{
//Load language files for each module
if($this->getLayout() == 'list')
{
foreach($this->getModel()->getList() as $module)
{
$path = $this->getIdentifier()->getApplication($module->application);
JFactory::getLanguage()->load($module->getIdentifier()->package, $module->name, $path );
}
}
return parent::display();
}
}
|
<?php
/**
* @version $Id$
* @package Nooku_Server
* @subpackage Pages
* @copyright Copyright (C) 2011 - 2012 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
/**
* Modules Html View Class
*
* @author Stian Didriksen <http://nooku.assembla.com/profile/stiandidriksen>
* @package Nooku_Server
* @subpackage Pages
*/
class ComPagesViewModulesHtml extends ComDefaultViewHtml
{
public function display()
{
//Load language files for each module
if($this->getLayout() == 'list')
{
foreach($this->getModel()->getList() as $module)
{
$path = $this->getIdentifier()->getApplication($module->application);
JFactory::getLanguage()->load('mod_'.$module->module->path[1], $path );
}
}
return parent::display();
}
}
|
Support __in as operator for backwards comp
|
EQUALS = 'equals'
GT = 'gt'
LT = 'lt'
IN = 'in'
OPERATOR_SEPARATOR = '__'
REVERSE_ORDER = '-'
ALL_OPERATORS = {EQUALS: 1, GT: 1, LT: 1, IN: 1}
def split_to_field_and_filter_type(filter_name):
filter_split = filter_name.split(OPERATOR_SEPARATOR)
filter_type = filter_split[-1] if len(filter_split) > 0 else None
if filter_type in ALL_OPERATORS:
return OPERATOR_SEPARATOR.join(filter_split[:-1]), filter_type
else:
return filter_name, None
def split_to_field_and_order_type(field_name_with_operator):
if field_name_with_operator.startswith(REVERSE_ORDER):
return field_name_with_operator[1:], REVERSE_ORDER
else:
return field_name_with_operator, None
def transform_to_list(val):
if isinstance(val, (list, tuple)):
return val
else:
return [val]
|
EQUALS = 'equals'
GT = 'gt'
LT = 'lt'
OPERATOR_SEPARATOR = '__'
REVERSE_ORDER = '-'
ALL_OPERATORS = {EQUALS: 1, GT: 1, LT: 1}
def split_to_field_and_filter_type(filter_name):
filter_split = filter_name.split(OPERATOR_SEPARATOR)
filter_type = filter_split[-1] if len(filter_split) > 0 else None
if filter_type in ALL_OPERATORS:
return OPERATOR_SEPARATOR.join(filter_split[:-1]), filter_type
else:
return filter_name, None
def split_to_field_and_order_type(field_name_with_operator):
if field_name_with_operator.startswith(REVERSE_ORDER):
return field_name_with_operator[1:], REVERSE_ORDER
else:
return field_name_with_operator, None
def transform_to_list(val):
if isinstance(val, (list, tuple)):
return val
else:
return [val]
|
Test if new conosle command is causing travis issues
|
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
Commands\SecurityCheck::class,
Commands\ParseCachedWebMentions::class,
Commands\ReDownloadWebMentions::class,
Commands\GenerateToken::class,
//Commands\UpdatePlacesURLs::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')
// ->hourly();
}
/**
* Register the Closure based commands for the application.
*
* @return void
*/
protected function commands()
{
require base_path('routes/console.php');
}
}
|
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
Commands\SecurityCheck::class,
Commands\ParseCachedWebMentions::class,
Commands\ReDownloadWebMentions::class,
Commands\GenerateToken::class,
Commands\UpdatePlacesURLs::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')
// ->hourly();
}
/**
* Register the Closure based commands for the application.
*
* @return void
*/
protected function commands()
{
require base_path('routes/console.php');
}
}
|
Enable connection to Heroku/ClearDB database
|
<?php
/**
* Created by PhpStorm.
* User: raynald
* Date: 7/29/15
* Time: 4:54 PM
*/
// This file contains the database access information.
// This file also establishes a connection to MySQL,
// selects the database, and sets the encoding.
if (!LIVE) {
// for local/development mysql server
$url = parse_url('http://test:test@192.168.0.252/nba');
} else {
// for Heroku hosted mysql server
$url = parse_url(getenv("CLEARDB_DATABASE_URL"));
}
$db_server = $url["host"];
$db_user = $url["user"];
$db_pass = $url["pass"];
$db_name = substr($url["path"], 1);
// Make the connection:
$dbc = @mysqli_connect ($db_server, $db_user, $db_pass, $db_name) OR
die ('Could not connect to MySQL: ' . mysqli_connect_error() );
// Set the encoding...
mysqli_set_charset($dbc, 'utf8');
|
<?php
/**
* Created by PhpStorm.
* User: raynald
* Date: 7/29/15
* Time: 4:54 PM
*/
// This file contains the database access information.
// This file also establishes a connection to MySQL,
// selects the database, and sets the encoding.
if (!LIVE) {
// for local/development mysql server
$url = parse_url('http://test:test@192.168.0.252/nba');
} else {
// for Heroku hosted mysql server
// $url = parse_url(getenv("CLEARDB_DATABASE_URL"));
}
$db_server = $url["host"];
$db_user = $url["user"];
$db_pass = $url["pass"];
$db_name = substr($url["path"], 1);
// Make the connection:
$dbc = @mysqli_connect ($db_server, $db_user, $db_pass, $db_name) OR
die ('Could not connect to MySQL: ' . mysqli_connect_error() );
// Set the encoding...
mysqli_set_charset($dbc, 'utf8');
|
Add constants for sound synthesis.
|
package framework;
import java.util.ArrayList;
import framework.editors.SoundEditor;
/**
* Represents a sound entity.
*
* A sound is represented basically by a frequency and a duration.
* It can then be modified by adding different modifiers.
* It is the core of the model in our MVC design pattern implementation.
*/
public abstract class Sound extends Observable {
/**
* Creates a Sound object.
*/
public Sound() {
}
/**
* Add a new Modifier to the list.
* @param m the new Modifier to be added
*/
public void addModifier(Modifier m) {
}
/**
* Remove the specified Modifier from the list.
* @param m the Modifier to be removed
*/
public void removeModifier(Modifier m) {
}
/**
* Instanciate a SoundEditor and hand back its reference.
* @return the reference to the SoundEditor
*/
public SoundEditor addEditor() {
}
private int frequency; // Hertzs
private double duration; // Milliseconds
private byte[] data;
private ArrayList<Modifier> modifiers;
// Constants
private final int SAMPLE_RATE = 44100; // CD quality audio
private final int MAX_16_BITS = Short.MAX_VALUE;
}
|
package framework;
import java.util.ArrayList;
import framework.editors.SoundEditor;
/**
* Represents a sound entity.
*
* A sound is represented basically by a frequency and a duration.
* It can then be modified by adding different modifiers.
* It is the core of the model in our MVC design pattern implementation.
*/
public abstract class Sound extends Observable {
/**
* Creates a Sound object.
*/
public Sound() {
}
/**
* Add a new Modifier to the list.
* @param m the new Modifier to be added
*/
public void addModifier(Modifier m) {
}
/**
* Remove the specified Modifier from the list.
* @param m the Modifier to be removed
*/
public void removeModifier(Modifier m) {
}
/**
* Instanciate a SoundEditor and hand back its reference.
* @return the reference to the SoundEditor
*/
public SoundEditor addEditor() {
}
private int frequency; // Hertzs
private double duration; // Milliseconds
private byte[] data;
private ArrayList<Modifier> modifiers;
}
|
Remove useless named return value
This cleans up the useless named return value stopCh at
SetupSignalHandler().
|
/*
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.
*/
package server
import (
"os"
"os/signal"
)
var onlyOneSignalHandler = make(chan struct{})
// SetupSignalHandler registered for SIGTERM and SIGINT. A stop channel is returned
// which is closed on one of these signals. If a second signal is caught, the program
// is terminated with exit code 1.
func SetupSignalHandler() <-chan struct{} {
close(onlyOneSignalHandler) // panics when called twice
stop := make(chan struct{})
c := make(chan os.Signal, 2)
signal.Notify(c, shutdownSignals...)
go func() {
<-c
close(stop)
<-c
os.Exit(1) // second signal. Exit directly.
}()
return stop
}
|
/*
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.
*/
package server
import (
"os"
"os/signal"
)
var onlyOneSignalHandler = make(chan struct{})
// SetupSignalHandler registered for SIGTERM and SIGINT. A stop channel is returned
// which is closed on one of these signals. If a second signal is caught, the program
// is terminated with exit code 1.
func SetupSignalHandler() (stopCh <-chan struct{}) {
close(onlyOneSignalHandler) // panics when called twice
stop := make(chan struct{})
c := make(chan os.Signal, 2)
signal.Notify(c, shutdownSignals...)
go func() {
<-c
close(stop)
<-c
os.Exit(1) // second signal. Exit directly.
}()
return stop
}
|
Change %default to %(default)s for removing warning
|
# -*- coding: utf-8 -*-
from pytest import fixture
from iamport import Iamport
DEFAULT_TEST_IMP_KEY = 'imp_apikey'
DEFAULT_TEST_IMP_SECRET = (
'ekKoeW8RyKuT0zgaZsUtXXTLQ4AhPFW3ZGseDA6b'
'kA5lamv9OqDMnxyeB9wqOsuO9W3Mx9YSJ4dTqJ3f'
)
def pytest_addoption(parser):
parser.addoption(
'--imp-key',
default=DEFAULT_TEST_IMP_KEY,
help='iamport client key for testing '
'[default: %(default)s]'
)
parser.addoption(
'--imp-secret',
default=DEFAULT_TEST_IMP_SECRET,
help='iamport secret key for testing '
'[default: %(default)s]'
)
@fixture
def iamport(request):
imp_key = request.config.getoption('--imp-key')
imp_secret = request.config.getoption('--imp-secret')
return Iamport(imp_key=imp_key, imp_secret=imp_secret)
|
# -*- coding: utf-8 -*-
from pytest import fixture
from iamport import Iamport
DEFAULT_TEST_IMP_KEY = 'imp_apikey'
DEFAULT_TEST_IMP_SECRET = ('ekKoeW8RyKuT0zgaZsUtXXTLQ4AhPFW3ZGseDA6bkA5lamv9O'
'qDMnxyeB9wqOsuO9W3Mx9YSJ4dTqJ3f')
def pytest_addoption(parser):
parser.addoption('--imp-key', default=DEFAULT_TEST_IMP_KEY,
help='iamport client key for testing '
'[default: %default]')
parser.addoption('--imp-secret', default=DEFAULT_TEST_IMP_SECRET,
help='iamport secret key for testing '
'[default: %default]')
@fixture
def iamport(request):
imp_key = request.config.getoption('--imp-key')
imp_secret = request.config.getoption('--imp-secret')
return Iamport(imp_key=imp_key, imp_secret=imp_secret)
|
Drop the [security] descriptor from requests; it's soon deprecated
|
from setuptools import find_packages, setup
from valohai_cli import __version__
setup(
name='valohai-cli',
version=__version__,
entry_points={'console_scripts': ['vh=valohai_cli.cli:cli']},
author='Valohai',
author_email='hait@valohai.com',
license='MIT',
install_requires=[
'click>=7.0',
'valohai-yaml>=0.9',
'valohai-utils>=0.1.7',
'requests>=2.0.0',
'requests-toolbelt>=0.7.1',
'typing-extensions>=3.7',
],
python_requires='>=3.6',
packages=find_packages(include=('valohai_cli*',)),
)
|
from setuptools import find_packages, setup
from valohai_cli import __version__
setup(
name='valohai-cli',
version=__version__,
entry_points={'console_scripts': ['vh=valohai_cli.cli:cli']},
author='Valohai',
author_email='hait@valohai.com',
license='MIT',
install_requires=[
'click>=7.0',
'valohai-yaml>=0.9',
'valohai-utils>=0.1.7',
'requests[security]>=2.0.0',
'requests-toolbelt>=0.7.1',
'typing-extensions>=3.7',
],
python_requires='>=3.6',
packages=find_packages(include=('valohai_cli*',)),
)
|
Fix alias in update query
|
<?php
namespace Lensky\PerformanceBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* PostRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class PostRepository extends EntityRepository
{
/**
* Find all posts with authors
*
* @return array | Post[]
*/
public function findAllPostsAndAuthors()
{
$qb = $this->createQueryBuilder('p');
$qb->addSelect('a')
->innerJoin('p.author', 'a');
return $qb->getQuery()->getResult();
}
/**
* Update created date for all posts
*
* @param \DateTime $newCreatedAt
*
* @return int
*/
public function updateCreatedAtForAllPosts(\DateTime $newCreatedAt)
{
$qb = $this->createQueryBuilder('p');
$qb->update()
->set('p.createdAt', ':newCreatedAt')
->setParameter('newCreatedAt', $newCreatedAt);
return $qb->getQuery()->execute();
}
}
|
<?php
namespace Lensky\PerformanceBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* PostRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class PostRepository extends EntityRepository
{
/**
* Find all posts with authors
*
* @return array | Post[]
*/
public function findAllPostsAndAuthors()
{
$qb = $this->createQueryBuilder('p');
$qb->addSelect('a')
->innerJoin('p.author', 'a');
return $qb->getQuery()->getResult();
}
/**
* Update created date for all posts
*
* @param \DateTime $newCreatedAt
*
* @return int
*/
public function updateCreatedAtForAllPosts(\DateTime $newCreatedAt)
{
$qb = $this->createQueryBuilder($this->alias);
$qb->update()
->set('p.createdAt', ':newCreatedAt')
->setParameter('newCreatedAt', $newCreatedAt);
return $qb->getQuery()->execute();
}
}
|
Bump deps to match d3m==v2020.5.18
|
from setuptools import setup, find_packages
__version__ = '0.6.0'
setup(
name = 'metalearn',
packages = find_packages(include=['metalearn', 'metalearn.*']),
version = __version__,
description = 'A package to aid in metalearning',
author = 'Roland Laboulaye, Brandon Schoenfeld, Casey Davis',
author_email = 'rlaboulaye@gmail.com, bjschoenfeld@gmail.com, caseykdavis@gmail.com',
url = 'https://github.com/byu-dml/metalearn',
download_url = 'https://github.com/byu-dml/metalearn/archive/{}.tar.gz'.format(__version__),
keywords = ['metalearning', 'machine learning', 'metalearn'],
install_requires = [
'numpy<=1.18.2',
'scikit-learn<=0.22.2.post1',
'pandas<=1.0.3'
],
classifiers = [
'Programming Language :: Python :: 3.6'
],
python_requires='~=3.6',
include_package_data=True,
)
|
from setuptools import setup, find_packages
__version__ = '0.6.0'
setup(
name = 'metalearn',
packages = find_packages(include=['metalearn', 'metalearn.*']),
version = __version__,
description = 'A package to aid in metalearning',
author = 'Roland Laboulaye, Brandon Schoenfeld, Casey Davis',
author_email = 'rlaboulaye@gmail.com, bjschoenfeld@gmail.com, caseykdavis@gmail.com',
url = 'https://github.com/byu-dml/metalearn',
download_url = 'https://github.com/byu-dml/metalearn/archive/{}.tar.gz'.format(__version__),
keywords = ['metalearning', 'machine learning', 'metalearn'],
install_requires = [
'numpy<=1.17.3',
'scikit-learn<=0.21.3',
'pandas<=0.25.2'
],
classifiers = [
'Programming Language :: Python :: 3.6'
],
python_requires='~=3.6',
include_package_data=True,
)
|
Correct mistaken assertTrue() -> assertEquals()
|
from core.models import Category
from django.test.testcases import TestCase
from django.urls import reverse
class ExportViewMixinTest(TestCase):
def setUp(self):
self.url = reverse('export-category')
self.cat1 = Category.objects.create(name='Cat 1')
self.cat2 = Category.objects.create(name='Cat 2')
def test_get(self):
response = self.client.get(self.url)
self.assertContains(response, self.cat1.name, status_code=200)
self.assertEquals(response['Content-Type'], 'text/html; charset=utf-8')
def test_post(self):
data = {
'file_format': '0',
}
response = self.client.post(self.url, data)
self.assertContains(response, self.cat1.name, status_code=200)
self.assertTrue(response.has_header("Content-Disposition"))
self.assertEquals(response['Content-Type'], 'text/csv')
|
from core.models import Category
from django.test.testcases import TestCase
from django.urls import reverse
class ExportViewMixinTest(TestCase):
def setUp(self):
self.url = reverse('export-category')
self.cat1 = Category.objects.create(name='Cat 1')
self.cat2 = Category.objects.create(name='Cat 2')
def test_get(self):
response = self.client.get(self.url)
self.assertContains(response, self.cat1.name, status_code=200)
self.assertTrue(response['Content-Type'], 'text/html')
def test_post(self):
data = {
'file_format': '0',
}
response = self.client.post(self.url, data)
self.assertContains(response, self.cat1.name, status_code=200)
self.assertTrue(response.has_header("Content-Disposition"))
self.assertTrue(response['Content-Type'], 'text/csv')
|
Check the type of the IndexInput rather than the Directory to detect
native implementation. This is a simpler and more correct test. It
also permits the Directory to return a mixture of native and
non-native IndexInput implementations.
git-svn-id: 4c5078813df38efa56971a28e09a55254294f104@150604 13f79535-47bb-0310-9956-ffa450edef68
|
package org.apache.lucene.index;
/**
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import org.apache.lucene.store.GCJIndexInput;
class GCJSegmentReader extends SegmentReader {
/** Try to use an optimized native implementation of TermDocs. The optimized
* implementation can only be used when the segment's directory is a
* GCJDirectory and it is not in compound format. */
public final TermDocs termDocs() throws IOException {
if (freqStream instanceof GCJIndexInput) { // it's a GCJIndexInput
return new GCJTermDocs(this); // so can use GCJTermDocs
} else {
return super.termDocs();
}
}
}
|
package org.apache.lucene.index;
/**
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import org.apache.lucene.store.GCJDirectory;
class GCJSegmentReader extends SegmentReader {
/** Try to use an optimized native implementation of TermDocs. The optimized
* implementation can only be used when the segment's directory is a
* GCJDirectory and it is not in compound format. */
public final TermDocs termDocs() throws IOException {
if (directory() instanceof GCJDirectory // it's a GCJ directory
&& this.cfsReader == null) { // & not in compound format
return new GCJTermDocs(this); // so can use GCJTermDocs
} else {
return super.termDocs();
}
}
}
|
Update paths and remove dupl. plugins from front prod
|
const merge = require('webpack-merge');
const webpack = require('webpack');
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const frontConfig = require('./front.config');
const devConfig = merge(frontConfig, {
output: {
filename: 'js/[name].[chunkhash].js',
},
plugins: [
new ExtractTextPlugin({
filename: 'css/[name].[chunkhash].css',
allChunks: true,
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
},
sourceMap: true,
}),
new OptimizeCSSPlugin(),
],
devtool: '#source-map',
});
module.exports = devConfig;
|
const merge = require('webpack-merge');
const webpack = require('webpack');
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const baseConfig = require('./base.config');
const frontConfig = require('./front.config');
const paths = require('./paths');
const devConfig = merge(baseConfig, frontConfig, {
output: {
filename: '[name].[chunkhash].js',
},
plugins: [
new ExtractTextPlugin({
filename: '/css/[name].[chunkhash].css',
allChunks: true,
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
},
sourceMap: true,
}),
new OptimizeCSSPlugin(),
new ManifestPlugin({
fileName: paths.manifest,
basePath: paths.assets,
}),
],
devtool: '#source-map',
});
module.exports = devConfig;
|
Use debug logs in karma
|
module.exports = config => {
const browser = process.env.BROWSER || 'chrome';
config.set({
basePath: '',
frameworks: ['browserify', 'jasmine'],
files: [
'https://static.opentok.com/v2/js/opentok.js',
'test/**/*.js'
],
preprocessors: {
'src/**/*.js': ['babel', 'browserify'],
'test/**/*.js': ['babel', 'browserify']
},
browserify: {
debug: true,
transform: [
['babelify']
],
configure: bundle => {
bundle.on('prebundle', () => {
bundle.external('react/addons');
bundle.external('react/lib/ReactContext');
bundle.external('react/lib/ExecutionEnvironment');
});
}
},
reporters: ['spec'],
port: 9876,
colors: true,
logLevel: config.LOG_DEBUG,
autoWatch: true,
browsers: [browser[0].toUpperCase() + browser.substr(1)],
singleRun: false
});
};
|
module.exports = config => {
const browser = process.env.BROWSER || 'chrome';
config.set({
basePath: '',
frameworks: ['browserify', 'jasmine'],
files: [
'https://static.opentok.com/v2/js/opentok.js',
'test/**/*.js'
],
preprocessors: {
'src/**/*.js': ['babel', 'browserify'],
'test/**/*.js': ['babel', 'browserify']
},
browserify: {
debug: true,
transform: [
['babelify']
],
configure: bundle => {
bundle.on('prebundle', () => {
bundle.external('react/addons');
bundle.external('react/lib/ReactContext');
bundle.external('react/lib/ExecutionEnvironment');
});
}
},
reporters: ['spec'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: [browser[0].toUpperCase() + browser.substr(1)],
singleRun: false
});
};
|
Revert "increase timeout for server notices room"
|
/*
Copyright 2018 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const assert = require('assert');
const acceptInvite = require("./accept-invite")
module.exports = async function acceptServerNoticesInviteAndConsent(session) {
await acceptInvite(session, "Server Notices");
session.log.step(`accepts terms & conditions`);
const consentLink = await session.waitAndQuery(".mx_EventTile_body a");
const termsPagePromise = session.waitForNewPage();
await consentLink.click();
const termsPage = await termsPagePromise;
const acceptButton = await termsPage.$('input[type=submit]');
await acceptButton.click();
await session.delay(1000); //TODO yuck, timers
await termsPage.close();
session.log.done();
}
|
/*
Copyright 2018 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const assert = require('assert');
const acceptInvite = require("./accept-invite")
module.exports = async function acceptServerNoticesInviteAndConsent(session) {
await acceptInvite(session, "Server Notices");
session.log.step(`accepts terms & conditions`);
const consentLink = await session.waitAndQuery(".mx_EventTile_body a", 10000);
const termsPagePromise = session.waitForNewPage();
await consentLink.click();
const termsPage = await termsPagePromise;
const acceptButton = await termsPage.$('input[type=submit]');
await acceptButton.click();
await session.delay(1000); //TODO yuck, timers
await termsPage.close();
session.log.done();
}
|
Fix early cache resolve bug
|
var Q = require('q');
var _ = require('lodash');
var spawn = require('child_process').spawn;
module.exports = function(args, options) {
var deferred = Q.defer();
options = options || {};
var defaults = {
cwd: process.cwd(),
verbose: false
};
options = _.extend({}, defaults, options);
var child = spawn('git', args, _.omit(options, 'verbose'));
child.on('exit', function(code) {
if (code === 128) {
deferred.reject("git did not exit cleanly");
} else {
deferred.resolve(code);
}
});
child.stdout.on('data', function(data) {
deferred.notify(data.toString());
});
// TODO: Why does this return non-error output?
// i.e. Cloning into...
child.stderr.on('data', function(data) {
deferred.notify(data.toString());
});
return deferred.promise;
};
|
var Q = require('q');
var _ = require('lodash');
var spawn = require('child_process').spawn;
module.exports = function(args, options) {
var deferred = Q.defer();
options = options || {};
var defaults = {
cwd: process.cwd(),
verbose: false
};
options = _.extend({}, defaults, options);
var child = spawn('git', args, _.omit(options, 'verbose'));
child.on('exit', function(code) {
if (code === 128) {
deferred.reject("git did not exit cleanly");
} else {
deferred.resolve(code);
}
});
child.stdout.on('data', function(data) {
deferred.notify(data.toString());
});
child.stderr.on('data', function(data) {
deferred.reject(data.toString());
});
return deferred.promise;
};
|
FIX: Remove leading space that caused the pages tab to break
|
<?php
/**
* Defines the SupportingProjectPage page type - initial code created by ss generator
*/
class PageWithImage extends Page implements RenderableAsPortlet {
static $has_one = array(
'MainImage' => 'Image'
);
// for rendering thumbnail when linked in facebook
function getOGImage() {
return $this->MainImage();
}
function getCMSFields() {
$fields = parent::getCMSFields();
$fields->addFieldToTab( 'Root.Image', $uf = new UploadField('MainImage'));
$dirname = strtolower($this->ClassName).'s';
$uf->setFolderName($dirname);
return $fields;
}
public function getPortletTitle() {
return $this->Title;
}
// FIXME - make this more efficient
public function getPortletImage() {
$result = null;
if ($this->MainImageId) {
$result = DataObject::get_by_id('Image', $this->MainImageID);
}
return $result;
}
public function getPortletCaption() {
return '';
}
}
class PageWithImage_Controller extends Page_Controller {
}
|
<?php
/**
* Defines the SupportingProjectPage page type - initial code created by ss generator
*/
class PageWithImage extends Page implements RenderableAsPortlet {
static $has_one = array(
'MainImage' => 'Image'
);
// for rendering thumbnail when linked in facebook
function getOGImage() {
return $this->MainImage();
}
function getCMSFields() {
$fields = parent::getCMSFields();
$fields->addFieldToTab( 'Root.Image', $uf = new UploadField('MainImage'));
$dirname = strtolower($this->ClassName).'s';
$uf->setFolderName($dirname);
return $fields;
}
public function getPortletTitle() {
return $this->Title;
}
// FIXME - make this more efficient
public function getPortletImage() {
$result = null;
if ($this->MainImageId) {
$result = DataObject::get_by_id('Image', $this->MainImageID);
}
return $result;
}
public function getPortletCaption() {
return '';
}
}
class PageWithImage_Controller extends Page_Controller {
}
|
Update static file directory to /public subfolder
|
var bodyParser = require('body-parser');
var db = require('../models/index');
module.exports = function (app, express) {
//Handle CORS
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://localhost:3000/');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, X-AUTHENTICATION, X-IP, Content-Type, Accept');
res.header('Access-Control-Allow-Credentials', true);
next();
});
//Serve up static files in client folder and other middleware
app.use(bodyParser.json());
app.use(express.static(__dirname + '/../../client/public'));
//For debugging. Log every request
app.use(function (req, res, next) {
console.log('==========================================');
console.log(req.method + ': ' + req.url);
next();
});
};
|
var bodyParser = require('body-parser');
var db = require('../models/index');
module.exports = function (app, express) {
//Handle CORS
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://localhost:3000/');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, X-AUTHENTICATION, X-IP, Content-Type, Accept');
res.header('Access-Control-Allow-Credentials', true);
next();
});
//Serve up static files in client folder and other middleware
app.use(bodyParser.json());
app.use(express.static(__dirname + '/../../client'));
//For debugging. Log every request
app.use(function (req, res, next) {
console.log('==========================================');
console.log(req.method + ': ' + req.url);
next();
});
};
|
Move subprocess stuff to an execution module for Pelican.
|
import salt.exceptions
import subprocess
def build_site(name, output="/srv/www"):
# /srv/salt/_states/pelican.py
# Generates static site with pelican -o $output $name
# Sorry.
# -- Jadon Bennett, 2015
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
current_state = __salt__['pelican.current_state'](name)
if __opts__['test'] == True:
ret['comment'] = 'Markdown files from "{0}" will be converted to HTML and put in "{1}"'.format(name,output)
ret['changes'] = {
'old': current_state,
'new': 'New!',
}
ret['result'] = None
return ret
new_state = __salt__['pelican.generate'](output,path)
ret['comment'] = 'Static site generated from "{0}".'.format(name)
ret['changes'] = {
'old': current_state,
'new': new_state,
}
ret['result'] = True
return ret
|
import salt.exceptions
import subprocess
def build_site(name, output="/srv/www"):
# /srv/salt/_states/pelican.py
# Generates static site with pelican -o $output $name
# Sorry.
# -- Jadon Bennett, 2015
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
# I don't know how to make this work. But it's cool.
#current_state = __salt__['pelican.current_state'](name)
current_state = "cool"
if __opts__['test'] == True:
ret['comment'] = 'Markdown files from "{0}" will be converted to HTML and put in "{1}"'.format(name,output)
ret['changes'] = {
'old': current_state,
'new': 'New!',
}
ret['result'] = None
return ret
subprocess.call(['pelican', '-o', output, name])
ret['comment'] = 'Static site generated from "{0}".'.format(name)
ret['changes'] = {
'old': current_state,
'new': 'Whoopee!',
}
ret['result'] = True
return ret
|
Add pending error code to service-integration-sdk
|
/*
* Copyright 2017 AppDirect, Inc. and/or its affiliates
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.appdirect.sdk.appmarket.events;
/**
* Standard error codes that are sent to the AppMarket
*/
public enum ErrorCode {
USER_ALREADY_EXISTS,
USER_NOT_FOUND,
ACCOUNT_NOT_FOUND,
MAX_USERS_REACHED,
UNAUTHORIZED,
INVALID_OPERATION,
OPERATION_CANCELLED,
CONFIGURATION_ERROR,
PENDING,
INVALID_RESPONSE,
TRANSPORT_ERROR,
UNKNOWN_ERROR,
NOT_FOUND
}
|
/*
* Copyright 2017 AppDirect, Inc. and/or its affiliates
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.appdirect.sdk.appmarket.events;
/**
* Standard error codes that are sent to the AppMarket
*/
public enum ErrorCode {
USER_ALREADY_EXISTS,
USER_NOT_FOUND,
ACCOUNT_NOT_FOUND,
MAX_USERS_REACHED,
UNAUTHORIZED,
INVALID_OPERATION,
OPERATION_CANCELLED,
CONFIGURATION_ERROR,
INVALID_RESPONSE,
TRANSPORT_ERROR,
UNKNOWN_ERROR,
NOT_FOUND
}
|
Fix lowercase conflict on previous test
|
var assert = require('assert');
var filename = require('../').filename;
describe('Filename normalization', function() {
it('should normalize spaces', function() {
assert.equal(filename('1 2 3'), '1_2_3');
});
it('should ignore trailing spaces', function() {
assert.equal(filename('a b c '), 'a_b_c');
});
it('should remove illegal chars', function() {
assert.equal(filename('abc 38 ./.#$#@!/'), 'abc_38');
});
it('should strip dots', function() {
assert.equal(filename('a.b.c'), 'abc');
});
it('should convert to lowecase', function() {
assert.equal(filename('AbC DeF gHi'), 'abc_def_ghi');
});
});
|
var assert = require('assert');
var filename = require('../').filename;
describe('Filename normalization', function() {
it('should normalize spaces', function() {
assert.equal(filename('1 2 3'), '1_2_3');
});
it('should ignore trailing spaces', function() {
assert.equal(filename('a b c '), 'a_b_c');
});
it('should remove illegal chars', function() {
assert.equal(filename('ABC 38 ./.#$#@!/'), 'ABC_38');
});
it('should strip dots', function() {
assert.equal(filename('a.b.c'), 'abc');
});
it('should convert to lowecase', function() {
assert.equal(filename('AbC DeF gHi'), 'abc_def_ghi');
});
});
|
Use the new get_minion_data function
|
# -*- coding: utf-8 -*-
'''
Functions to interact with the pillar compiler on the master
'''
# Import salt libs
import salt.pillar
import salt.utils.minions
def show_top(minion=None, saltenv='base'):
'''
Returns the compiled top data for pillar for a specific minion. If no
minion is specified, we use the first minion we find.
CLI Example:
.. code-block:: bash
salt-run pillar.show_top
'''
id_, grains, _ = salt.utils.minions.get_minion_data(minion, __opts__)
pillar = salt.pillar.Pillar(
__opts__,
grains,
id_,
saltenv)
top, errors = pillar.get_top()
if errors:
return errors
return top
|
# -*- coding: utf-8 -*-
'''
Functions to interact with the pillar compiler on the master
'''
# Import salt libs
import salt.pillar
import salt.utils.minions
def show_top(minion=None, saltenv='base'):
'''
Returns the compiled top data for pillar for a specific minion. If no
minion is specified, we use the first minion we find.
CLI Example:
.. code-block:: bash
salt-run pillar.show_top
'''
id_, grains = salt.utils.minions.get_grains(minion)
pillar = salt.pillar.Pillar(
__opts__,
grains,
id_,
saltenv)
top, errors = pillar.get_top()
if errors:
return errors
return top
|
Change active tags button layout.
|
import React, { Component, PropTypes } from 'react';
import { Button, ButtonGroup } from 'react-bootstrap';
export default class ActiveTags extends Component {
removeTag(tag) {
const { filterObject, position, setFilter } = this.props;
const temp = filterObject[position];
temp.delete(tag);
const newFilterObject =
Object.assign({}, filterObject, { [position]: temp });
setFilter(newFilterObject);
}
render() {
const { tags } = this.props;
const buttons = [];
Array.from(tags).sort().map((t, i) => {
buttons.push(
<Button bsSize={'xsmall'}
key={'tag' + i}
style={{ marginTop: '-1px', borderRadius: '0px' }}
onClick={() => { this.removeTag(t); }}
>
× {t}
</Button>);
});
const content = [];
if (buttons.length) {
content.push(<ButtonGroup key={'bg'}>{buttons}</ButtonGroup>);
} else {
content.push(<p key={'p'}><small>No active tags.</small></p>);
}
return (<div>
{content}
</div>);
}
}
ActiveTags.propTypes = {
filterObject: PropTypes.object,
position: PropTypes.string,
setFilter: PropTypes.func,
tags: PropTypes.object,
};
|
import React, { Component, PropTypes } from 'react';
import { Button, ButtonGroup } from 'react-bootstrap';
export default class ActiveTags extends Component {
removeTag(tag) {
const { filterObject, position, setFilter } = this.props;
const temp = filterObject[position];
temp.delete(tag);
const newFilterObject =
Object.assign({}, filterObject, { [position]: temp });
setFilter(newFilterObject);
}
render() {
const { tags } = this.props;
const buttons = [];
Array.from(tags).sort().map((t, i) => {
buttons.push(
<Button bsSize={'xsmall'}
key={'tag' + i}
onClick={() => { this.removeTag(t); }}
>
× {t}
</Button>);
});
const content = [];
if (buttons.length) {
content.push(<ButtonGroup key={'bg'}>{buttons}</ButtonGroup>);
} else {
content.push(<p key={'p'}><small>No active tags.</small></p>);
}
return (<div>
{content}
</div>);
}
}
ActiveTags.propTypes = {
filterObject: PropTypes.object,
position: PropTypes.string,
setFilter: PropTypes.func,
tags: PropTypes.object,
};
|
Update TestFX test in contacts module to fix compile error
|
package de.saxsys.mvvmfx.contacts;
import static org.testfx.api.FxAssert.verifyThat;
import static org.testfx.matcher.control.TableViewMatchers.hasTableCell;
import org.junit.Before;
import org.junit.Test;
import org.testfx.api.FxRobot;
import org.testfx.api.FxToolkit;
public class AppTestFxIT extends FxRobot {
@Before
public void setupApp() throws Exception {
FxToolkit.registerPrimaryStage();
FxToolkit.setupApplication(App.class);
}
@Test
public void testAddNewContact() {
clickOn("#addNewContactButton");
clickOn("#firstnameInput");
write("luke");
clickOn("#lastnameInput");
write("skywalker");
clickOn("#emailInput");
write("luke.skywalker@example.org");
clickOn("#nextButton");
clickOn("#okButton");
verifyThat("#masterContactTable", hasTableCell("luke"));
verifyThat("#masterContactTable", hasTableCell("skywalker"));
verifyThat("#masterContactTable", hasTableCell("luke.skywalker@example.org"));
}
}
|
package de.saxsys.mvvmfx.contacts;
import javafx.geometry.VerticalDirection;
import javafx.scene.Parent;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.loadui.testfx.Assertions;
import org.loadui.testfx.GuiTest;
import org.testfx.api.FxRobot;
import org.testfx.api.FxToolkit;
import static org.loadui.testfx.Assertions.verifyThat;
import static org.loadui.testfx.controls.TableViews.containsCell;
public class AppTestFxIT extends FxRobot {
@Before
public void setupApp() throws Exception{
FxToolkit.registerPrimaryStage();
FxToolkit.setupApplication(App.class);
}
@Test
public void testAddNewContact(){
clickOn("#addNewContactButton");
clickOn("#firstnameInput");
write("luke");
clickOn("#lastnameInput");
write("skywalker");
clickOn("#emailInput");
write("luke.skywalker@example.org");
clickOn("#nextButton");
clickOn("#okButton");
verifyThat("#masterContactTable", containsCell("luke"));
verifyThat("#masterContactTable", containsCell("skywalker"));
verifyThat("#masterContactTable", containsCell("luke.skywalker@example.org"));
}
}
|
Update magic 8 ball syntax
|
package io.github.skepter.skepbot.modules;
import java.util.concurrent.ThreadLocalRandom;
public class Magic8 extends Module {
String[] responses = { "It is certain", "It is decidedly so", "Without a doubt", "Yes definitely",
"You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Yes", "Signs point to yes",
"Reply hazy try again", "Ask again later", "Better not tell you now", "Cannot predict now",
"Concentrate and ask again", "Don't count on it", "My reply is no", "My sources say no",
"Outlook not so good", "Very doubtful" };
public Magic8() {
super(PatternType.CONTAINS, "magic8", "magic 8");
}
@Override
public boolean extraConditions() {
return input.endsWith("?");
}
@Override
public String output() {
return responses[ThreadLocalRandom.current().nextInt(0, responses.length)];
}
}
|
package io.github.skepter.skepbot.modules;
import java.util.concurrent.ThreadLocalRandom;
public class Magic8 extends Module {
String[] responses = { "It is certain", "It is decidedly so", "Without a doubt", "Yes definitely",
"You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Yes", "Signs point to yes",
"Reply hazy try again", "Ask again later", "Better not tell you now", "Cannot predict now",
"Concentrate and ask again", "Don't count on it", "My reply is no", "My sources say no",
"Outlook not so good", "Very doubtful" };
public Magic8() {
super(PatternType.STARTS_WITH, "magic8");
}
@Override
public boolean extraConditions() {
return input.endsWith("?");
}
@Override
public String output() {
return responses[ThreadLocalRandom.current().nextInt(0, responses.length)];
}
}
|
Fix test to check for the correct version
|
<?php namespace Rollbar;
use \Mockery as m;
use Rollbar\Payload\Notifier;
class NotifierTest extends BaseRollbarTest
{
public function testName()
{
$name = "rollbar-php";
$notifier = new Notifier($name, "0.1");
$this->assertEquals($name, $notifier->getName());
$name2 = "RollbarPHP";
$this->assertEquals($name2, $notifier->setName($name2)->getName());
}
public function testVersion()
{
$version = Notifier::VERSION;
$notifier = new Notifier("PHP-Rollbar", $version);
$this->assertEquals($version, $notifier->getVersion());
$version2 = "0.9";
$this->assertEquals($version2, $notifier->setVersion($version2)->getVersion());
}
public function testEncode()
{
$notifier = Notifier::defaultNotifier();
$encoded = json_encode($notifier->jsonSerialize());
$this->assertEquals('{"name":"rollbar-php","version":"1.3.5"}', $encoded);
}
}
|
<?php namespace Rollbar;
use \Mockery as m;
use Rollbar\Payload\Notifier;
class NotifierTest extends BaseRollbarTest
{
public function testName()
{
$name = "rollbar-php";
$notifier = new Notifier($name, "0.1");
$this->assertEquals($name, $notifier->getName());
$name2 = "RollbarPHP";
$this->assertEquals($name2, $notifier->setName($name2)->getName());
}
public function testVersion()
{
$version = Notifier::VERSION;
$notifier = new Notifier("PHP-Rollbar", $version);
$this->assertEquals($version, $notifier->getVersion());
$version2 = "0.9";
$this->assertEquals($version2, $notifier->setVersion($version2)->getVersion());
}
public function testEncode()
{
$notifier = Notifier::defaultNotifier();
$encoded = json_encode($notifier->jsonSerialize());
$this->assertEquals('{"name":"rollbar-php","version":"1.3.3"}', $encoded);
}
}
|
Put js at the end of the `<body>` tag.`
|
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="/favicon.ico">
<?php foreach($config->styles as $file) echo "\n\t<link type='text/css' href='$file' rel='stylesheet' />"; ?>
<title>GraphiQL</title>
<style>
body {
height: 100%;
margin: 0;
width: 100%;
overflow: hidden;
}
</style>
</head>
<body>
<style>
#graphiql {
height: 100vh;
}
</style>
<div id="graphiql">Loading...</div>
<script>
var config = <?= json_encode($config->js()) ?>;
</script>
<?php foreach($config->scripts as $file) echo "\n\t<script type='text/javascript' src='$file'></script>"; ?>
</body>
</html>
|
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="/favicon.ico">
<?php foreach($config->styles as $file) echo "\n\t<link type='text/css' href='$file' rel='stylesheet' />"; ?>
<?php foreach($config->scripts as $file) echo "\n\t<script type='text/javascript' src='$file'></script>"; ?>
<title>GraphiQL</title>
<style>
body {
height: 100%;
margin: 0;
width: 100%;
overflow: hidden;
}
</style>
<script>
var config = <?= json_encode($config->js()) ?>;
</script>
</head>
<body>
<style>
#graphiql {
height: 100vh;
}
</style>
<div id="graphiql">Loading...</div>
</body>
</html>
|
Add default init for Team Class
|
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import relationship
from scoring_engine.models.base import Base
class Team(Base):
__tablename__ = 'teams'
id = Column(Integer, primary_key=True)
name = Column(String(20), nullable=False)
color = Column(String(10), nullable=False)
services = relationship("Service", back_populates="team")
users = relationship("User", back_populates="team")
def __init__(self, name, color):
self.name = name
self.color = color
def current_score(self):
# todo make this dynamic based on service result
return 2000
@property
def is_red_team(self):
return self.color == 'Red'
@property
def is_white_team(self):
return self.color == 'White'
@property
def is_blue_team(self):
return self.color == 'Blue'
|
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import relationship
from scoring_engine.models.base import Base
class Team(Base):
__tablename__ = 'teams'
id = Column(Integer, primary_key=True)
name = Column(String(20), nullable=False)
color = Column(String(10), nullable=False)
services = relationship("Service", back_populates="team")
users = relationship("User", back_populates="team")
def current_score(self):
# todo make this dynamic based on service result
return 2000
@property
def is_red_team(self):
return self.color == 'Red'
@property
def is_white_team(self):
return self.color == 'White'
@property
def is_blue_team(self):
return self.color == 'Blue'
|
(server): Change request headers to prefer JSON
|
export default {
headers: {
"Host": "a.4cdn.org",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0",
"Accept": "application/json,text/html,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-GB,en;q=0.5",
"Accept-Encoding": "gzip, deflate",
"DNT": "1",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1",
"Pragma": "no-cache",
"Cache-Control": "no-cache"
}
}
|
export default {
headers: {
"Host": "a.4cdn.org",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-GB,en;q=0.5",
"Accept-Encoding": "gzip, deflate",
"DNT": "1",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1",
"Pragma": "no-cache",
"Cache-Control": "no-cache"
}
}
|
Switch encoding to UTF-8 from latin1
This change was originally made in PR #53, but may no longer be required
(and may cause issues with comments in IR that use non-latin1
characters).
|
import atexit
def _encode_string(s):
encoded = s.encode('utf-8')
return encoded
def _decode_string(b):
return b.decode('utf-8')
_encode_string.__doc__ = """Encode a string for use by LLVM."""
_decode_string.__doc__ = """Decode a LLVM character (byte)string."""
_shutting_down = [False]
def _at_shutdown():
_shutting_down[0] = True
atexit.register(_at_shutdown)
def _is_shutting_down(_shutting_down=_shutting_down):
"""
Whether the interpreter is currently shutting down.
For use in finalizers, __del__ methods, and similar; it is advised
to early bind this function rather than look it up when calling it,
since at shutdown module globals may be cleared.
"""
return _shutting_down[0]
|
import atexit
def _encode_string(s):
encoded = s.encode('latin1')
return encoded
def _decode_string(b):
return b.decode('latin1')
_encode_string.__doc__ = """Encode a string for use by LLVM."""
_decode_string.__doc__ = """Decode a LLVM character (byte)string."""
_shutting_down = [False]
def _at_shutdown():
_shutting_down[0] = True
atexit.register(_at_shutdown)
def _is_shutting_down(_shutting_down=_shutting_down):
"""
Whether the interpreter is currently shutting down.
For use in finalizers, __del__ methods, and similar; it is advised
to early bind this function rather than look it up when calling it,
since at shutdown module globals may be cleared.
"""
return _shutting_down[0]
|
Clear the cookie after logout
git-svn-id: 5a74b5304d8e7e474561603514f78b697e5d94c4@981321 13f79535-47bb-0310-9956-ffa450edef68
|
/*
* 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.wicket.examples.library;
import org.apache.wicket.examples.WicketExamplePage;
import org.apache.wicket.request.mapper.parameter.PageParameters;
/**
* Simple logout page.
*
* @author Jonathan Locke
*/
public class SignOut extends WicketExamplePage
{
/**
* Constructor
*
* @param parameters
* Page parameters (ignored since this is the home page)
*/
public SignOut(final PageParameters parameters)
{
getSession().invalidate();
}
/**
* @see org.apache.wicket.Page#onBeforeRender()
*/
@Override
protected void onBeforeRender()
{
super.onBeforeRender();
getApplication().getSecuritySettings().getAuthenticationStrategy().remove();
}
}
|
/*
* 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.wicket.examples.library;
import org.apache.wicket.examples.WicketExamplePage;
import org.apache.wicket.request.mapper.parameter.PageParameters;
/**
* Simple logout page.
*
* @author Jonathan Locke
*/
public class SignOut extends WicketExamplePage
{
/**
* Constructor
*
* @param parameters
* Page parameters (ignored since this is the home page)
*/
public SignOut(final PageParameters parameters)
{
getSession().invalidate();
}
}
|
Use widget and progress component
|
import { Component } from 'react'
import 'isomorphic-fetch'
import Progress from '../../progress'
import Widget from '../../widget'
export default class PageSpeedInsights extends Component {
static defaultProps = {
filter_third_party_resources: true,
locale: 'de_DE',
strategy: 'desktop'
}
state = {
score: 0
}
async componentDidMount () {
const { url, filter_third_party_resources, locale, strategy } = this.props
let requestUrl = 'https://www.googleapis.com/pagespeedonline/v2/runPagespeed'
requestUrl += `?url=${url}`
// eslint-disable-next-line camelcase
requestUrl += `&filter_third_party_resources=${filter_third_party_resources}`
requestUrl += `&locale=${locale}`
requestUrl += `&strategy=${strategy}`
// eslint-disable-next-line no-undef
const res = await fetch(requestUrl)
const json = await res.json()
this.setState({ score: json.ruleGroups.SPEED.score })
}
render () {
const { score } = this.state
return (
<Widget title='PageSpeed Score'>
<Progress value={score} />
</Widget>
)
}
}
|
import { Component } from 'react'
import 'isomorphic-fetch'
export default class PageSpeedInsights extends Component {
static defaultProps = {
filter_third_party_resources: true,
locale: 'de_DE',
strategy: 'desktop'
}
state = {
score: 0
}
async componentDidMount () {
let url = 'https://www.googleapis.com/pagespeedonline/v2/runPagespeed'
url += `?url=${this.props.url}`
url += `&filter_third_party_resources=${this.props.filter_third_party_resources}`
url += `&locale=${this.props.locale}`
url += `&strategy=${this.props.strategy}`
const res = await fetch(url) // eslint-disable-line no-undef
const json = await res.json()
this.setState({ score: json.ruleGroups.SPEED.score })
}
render () {
return (
<div>
<h3>PageSpeed Score</h3>
<p>{this.state.score}</p>
</div>
)
}
}
|
Use ',' to separate style names.
|
/*global define*/
/*jslint unparam:true*/
define(function () {
'use strict';
return {
load: function (name, req, onLoad, config) {
var names = name.match(/([^,]+)/g) || [];
names = names.map(function (n) {
if (n.indexOf('/') === -1) {
n = './styles/' + n;
}
return 'less!' + n;
});
req(names, function () {
onLoad(Array.prototype.slice.call(arguments, 0, arguments.length));
});
}
};
});
|
/*global define*/
/*jslint unparam:true*/
define(function () {
'use strict';
return {
load: function (name, req, onLoad, config) {
var names = name.match(/([\w\-]+)/g) || [];
names = names.map(function (n) {
if (n.indexOf('/') === -1) {
n = './styles/' + n;
}
return 'less!' + n;
});
req(names, function () {
onLoad(Array.prototype.slice.call(arguments, 0, arguments.length));
});
}
};
});
|
Remove features added in last version
|
module.exports = function ({target, store, component, diff, raf}) {
raf = raf != null ? raf : window.requestAnimationFrame
let state = store()
let rafCalled = false
return function (init) {
init({target, dispatch})
}
function dispatch () {
const args = (arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments))
args.unshift(state)
state = store.apply(null, args)
if (!rafCalled) {
rafCalled = true
raf(render)
}
}
function render () {
rafCalled = false
const element = component({state, dispatch, next})
if (element != null) {
diff(target, element)
}
}
function next (callback) {
process.nextTick(callback, {target, dispatch})
}
}
|
module.exports = function ({target, store, component, diff, options, raf}) {
raf = raf != null ? raf : window.requestAnimationFrame
if (options != null) {
options.dispatch = dispatch
options.next = next
} else {
options = {dispatch, next}
}
let stores = !Array.isArray(store) ? [store] : store
let state = stores.reduce((state, store) => store(state))
let rafCalled = false
return function (init) {
init({target, dispatch})
}
function dispatch () {
state = stores.reduce((state, store) => {
const args = (arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments))
args.unshift(state)
return store.apply(null, args)
}, state)
if (!rafCalled) {
rafCalled = true
raf(render)
}
}
function render () {
rafCalled = false
let app = {state}
Object.keys(options).forEach(function (prop) {
app[prop] = options[prop]
})
const element = component(app)
if (element != null) {
diff(target, element)
}
}
function next (callback) {
process.nextTick(callback, {target, dispatch})
}
}
|
Write default config to JSON for Jigsaw, not docs config
|
const argv = require('yargs').argv
const command = require('node-cmd')
const mix = require('laravel-mix')
const OnBuild = require('on-build-webpack')
const Watch = require('webpack-watch')
const tailwind = require('./../lib/index.js')
const config = require('./../defaultConfig.js')
const fs = require('fs')
fs.writeFileSync('./tailwind.json', JSON.stringify(config()))
const env = argv.e || argv.env || 'local'
const plugins = [
new OnBuild(() => {
command.get('./vendor/bin/jigsaw build ' + env, (error, stdout, stderr) => {
if (error) {
console.log(stderr)
process.exit(1)
}
console.log(stdout)
})
}),
new Watch({
paths: ['source/**/*.md', 'source/**/*.php'],
options: { ignoreInitial: true }
}),
]
mix.webpackConfig({ plugins })
mix.setPublicPath('source')
mix
.js('source/_assets/js/nav.js', 'source/js')
.js('source/_assets/js/app.js', 'source/js')
.less('source/_assets/less/main.less', 'source/css')
.options({
postCss: [
tailwind('tailwind.js'),
]
})
.version()
|
const argv = require('yargs').argv
const command = require('node-cmd')
const mix = require('laravel-mix')
const OnBuild = require('on-build-webpack')
const Watch = require('webpack-watch')
const tailwind = require('./../lib/index.js')
const config = require('./../defaultConfig.js')
const fs = require('fs')
fs.writeFileSync('./tailwind.json', JSON.stringify(require('./tailwind.js')))
const env = argv.e || argv.env || 'local'
const plugins = [
new OnBuild(() => {
command.get('./vendor/bin/jigsaw build ' + env, (error, stdout, stderr) => {
if (error) {
console.log(stderr)
process.exit(1)
}
console.log(stdout)
})
}),
new Watch({
paths: ['source/**/*.md', 'source/**/*.php'],
options: { ignoreInitial: true }
}),
]
mix.webpackConfig({ plugins })
mix.setPublicPath('source')
mix
.js('source/_assets/js/nav.js', 'source/js')
.js('source/_assets/js/app.js', 'source/js')
.less('source/_assets/less/main.less', 'source/css')
.options({
postCss: [
tailwind('tailwind.js'),
]
})
.version()
|
Add TODO in Google Provider
|
import google from 'googleapis';
import nconf from '../config';
import User from '../models/user';
const OAuth2 = google.auth.OAuth2;
export default class GoogleProvider {
constructor(token, dce) {
this.dce = dce;
this.authLevel = nconf.get('permissions:levels:high');
this.token = token;
this.client = new OAuth2(nconf.get('auth:google:id'), nconf.get('auth:google:secret'));
}
verify() {
return new Promise((resolve, reject) => {
// TODO: 'clientId' is 'undefined'; should be 'clientId_'
// This may change when upgrading 'googleapis'
this.client.verifyIdToken(this.token, this.client.clientId, (err, ticket) => {
if (err) {
return reject(err);
}
this.payload = ticket.getPayload();
if (this.payload.hd === 'g.rit.edu') {
return resolve();
}
return reject({ message: 'Must login with a g.rit.edu account' });
});
});
}
findOrCreateUser() {
return User
.findOrCreate({ where: { dce: this.dce } })
.spread((user, created) => {
user.firstName = this.payload.given_name;
user.lastName = this.payload.family_name;
return Promise.all([user.save(), created]);
});
}
}
|
import google from 'googleapis';
import nconf from '../config';
import User from '../models/user';
const OAuth2 = google.auth.OAuth2;
export default class GoogleProvider {
constructor(token, dce) {
this.dce = dce;
this.authLevel = nconf.get('permissions:levels:high');
this.token = token;
this.client = new OAuth2(nconf.get('auth:google:id'), nconf.get('auth:google:secret'));
}
verify() {
return new Promise((resolve, reject) => {
this.client.verifyIdToken(this.token, this.client.clientId, (err, ticket) => {
if (err) {
return reject(err);
}
this.payload = ticket.getPayload();
if (this.payload.hd === 'g.rit.edu') {
return resolve();
}
return reject({ message: 'Must login with a g.rit.edu account' });
});
});
}
findOrCreateUser() {
return User
.findOrCreate({ where: { dce: this.dce } })
.spread((user, created) => {
user.firstName = this.payload.given_name;
user.lastName = this.payload.family_name;
return Promise.all([user.save(), created]);
});
}
}
|
Include plot title to plots
|
from flask_restplus import Namespace, Resource, fields, abort
import cea.config
import cea.plots.cache
api = Namespace('Dashboard', description='Dashboard plots')
LAYOUTS = ['row', 'grid', 'map']
CATEGORIES = {c.name: {'label': c.label, 'plots': [{'id': p.id(), 'name': p.name} for p in c.plots]}
for c in cea.plots.categories.list_categories()}
@api.route('/')
class Dashboard(Resource):
def get(self):
"""
Get Dashboards from yaml file
"""
config = cea.config.Configuration()
plot_cache = cea.plots.cache.PlotCache(config)
dashboards = cea.plots.read_dashboards(config, plot_cache)
out = []
for d in dashboards:
dashboard = d.to_dict()
for i, plot in enumerate(dashboard['plots']):
dashboard['plots'][i]['title'] = d.plots[i].title
out.append(dashboard)
return out
|
from flask_restplus import Namespace, Resource, fields, abort
import cea.config
import cea.plots.cache
api = Namespace('Dashboard', description='Dashboard plots')
LAYOUTS = ['row', 'grid', 'map']
CATEGORIES = {c.name: {'label': c.label, 'plots': [{'id': p.id(), 'name': p.name} for p in c.plots]}
for c in cea.plots.categories.list_categories()}
@api.route('/')
class Dashboard(Resource):
def get(self):
"""
Get Dashboards from yaml file
"""
config = cea.config.Configuration()
plot_cache = cea.plots.cache.PlotCache(config)
dashboards = cea.plots.read_dashboards(config, plot_cache)
return [{'name': d.name, 'description': d.description, 'layout': d.layout if d.layout in LAYOUTS else 'row',
'plots': [{'title': plot.title, 'scenario':
plot.parameters['scenario-name'] if 'scenario-name' in plot.parameters.keys() else None}
for plot in d.plots]} for d in dashboards]
|
Create dummy password on null
|
package io.core9.module.auth.standard;
import io.core9.plugin.database.repository.AbstractCrudEntity;
import io.core9.plugin.database.repository.Collection;
import io.core9.plugin.database.repository.CrudEntity;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Set;
import org.apache.shiro.crypto.hash.Sha256Hash;
@Collection("core.users")
public class UserEntity extends AbstractCrudEntity implements CrudEntity {
private String username;
private String password;
private String salt;
private Set<String> roles;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
public Set<String> getRoles() {
return roles;
}
public void setRoles(Set<String> roles) {
this.roles = roles;
}
public void hashPassword(String source) {
if(source == null) {
SecureRandom random = new SecureRandom();
source = new BigInteger(130, random).toString(32);
}
this.password = new Sha256Hash(source, salt).toString();
}
}
|
package io.core9.module.auth.standard;
import io.core9.plugin.database.repository.AbstractCrudEntity;
import io.core9.plugin.database.repository.Collection;
import io.core9.plugin.database.repository.CrudEntity;
import java.util.Set;
import org.apache.shiro.crypto.hash.Sha256Hash;
@Collection("core.users")
public class UserEntity extends AbstractCrudEntity implements CrudEntity {
private String username;
private String password;
private String salt;
private Set<String> roles;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
public Set<String> getRoles() {
return roles;
}
public void setRoles(Set<String> roles) {
this.roles = roles;
}
public void hashPassword(String source) {
this.password = new Sha256Hash(source, salt).toString();
}
}
|
Fix javadoc typo in id factory.
|
// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.cloud.trace.util;
/**
* A factory that generates identifiers.
*
* @param <T> the type of identifier generated by this factory.
*/
public interface IdFactory<T> {
/**
* Generates a new identifier.
*
* @return the new identifier.
*/
T nextId();
/**
* Returns the invalid identifier value for {@code <T>}.
*
* @return the invalid identifier.
*/
T invalid();
}
|
// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.cloud.trace.util;
/**
* A factory that generates identifiers.
*
* @param <T> the type of identifier generated by this factory.
*/
public interface IdFactory<T> {
/**
* Generates a new identifier.
*
* @return the new identifier.
T nextId();
/**
* Returns the invalid identifier value for {@code <T>}.
*
* @return the invalid identifier.
*/
T invalid();
}
|
Fix scope issue, fix project dir.
|
/* globals require */
module.exports = function(gulp) {
'use strict';
const fs = require('fs');
const path = require('path');
const yaml = require('js-yaml');
const _ = require('lodash');
let projectDir = path.join(__dirname, '../../');
let projectConfig = {};
// Load config from project.yml.
try {
projectConfig = yaml.safeLoad(fs.readFileSync(path.join(projectDir, 'project.yml'), 'utf8'));
} catch (e) {}
// Get local project config from local.project.yml and merge.
try {
let localConfig = yaml.safeLoad(fs.readFileSync(path.join(projectDir, 'local.project.yml'), 'utf8'));
projectConfig = _.defaultsDeep(localConfig, projectConfig);
} catch (e) {}
/**
* Sets environment variables defined in project.yml.
*
* @param {Object} projectConfig - Project configuration defined in
* project.yml.
*/
function initEnvVars(projectConfig) {
let defaults = _.get(projectConfig, 'env.default', {});
_.forIn(projectConfig.env, function (vars, env) {
let envVars = _.defaultsDeep(projectConfig.env[env], defaults);
_.forIn(envVars, function (value, key) {
process.env['ENV_' + env.toUpperCase() + '_' + key.toUpperCase()] = value;
});
});
}
// Set environment variables.
initEnvVars(projectConfig);
// Include run task.
require('./gulp-tasks/gulp-run.js')(gulp, projectConfig);
};
|
/* globals require */
function initEnv(projectConfig) {
let defaults = _.get(projectConfig, 'env.default', {});
_.forIn(projectConfig.env, function (vars, env) {
let envVars = _.defaultsDeep(projectConfig.env[env], defaults);
_.forIn(envVars, function (value, key) {
process.env['ENV_' + env.toUpperCase() + '_' + key.toUpperCase()] = value;
});
});
}
module.exports = function(gulp) {
'use strict';
const fs = require('fs');
const path = require('path');
const yaml = require('js-yaml');
const _ = require('lodash');
let projectDir = path.join(__dirname, '../');
let projectConfig = {};
// Load config from project.yml.
try {
projectConfig = yaml.safeLoad(fs.readFileSync(path.join(projectDir, 'project.yml'), 'utf8'));
} catch (e) {}
// Get local project config from local.project.yml and merge.
try {
let localConfig = yaml.safeLoad(fs.readFileSync(path.join(projectDir, 'local.project.yml'), 'utf8'));
projectConfig = _.defaultsDeep(localConfig, projectConfig);
} catch (e) {}
initEnv(projectConfig);
// Include tasks.
require('./gulp-tasks/gulp-run.js')(gulp, projectConfig);
};
|
Fix setting of custom MPI command
|
MPI_COMMAND = 'mpirun -n {n_proc} {executable}'
def set_mpi_command(command):
"""
Set the MPI Command to use.
This should contain {n_proc} to indicate the number of processes, and
{executable} to indicate the name of the executable.
Parameters
----------
command: str
The MPI command for running executables
Examples
--------
Use ``mpirun``:
>>> set_mpi_command('mpirun -n {n_proc} {executable}')
Use ``mpiexec`` with host list:
>>> set_mpi_command('mpiexec -f mpd.hosts -np {n_proc} {executable}')
"""
global MPI_COMMAND
MPI_COMMAND = command
def _get_mpi_command(executable=None, n_proc=None):
return MPI_COMMAND.format(executable=executable, n_proc=n_proc)
|
MPI_COMMAND = 'mpirun -n {n_proc} {executable}'
def set_mpi_command(command):
"""
Set the MPI Command to use.
This should contain {n_proc} to indicate the number of processes, and
{executable} to indicate the name of the executable.
Parameters
----------
command: str
The MPI command for running executables
Examples
--------
Use ``mpirun``:
>>> set_mpi_command('mpirun -n {n_proc} {executable}')
Use ``mpiexec`` with host list:
>>> set_mpi_command('mpiexec -f mpd.hosts -np {n_proc} {executable}')
"""
MPI_COMMAND = command
def _get_mpi_command(executable=None, n_proc=None):
return MPI_COMMAND.format(executable=executable, n_proc=n_proc)
|
Fix resize proportions on window resize
|
document.addEventListener('DOMContentLoaded', onDocumentReady, false);
function onDocumentReady() {
var aside = document.querySelector('aside');
var section = document.querySelector('section');
var resizer = document.querySelector('.vertical-resizer');
resizer.addEventListener('mousedown', startDrag, false);
var startX, startY, startWidth, startHeight;
function startDrag(e) {
startX = e.clientX;
startY = e.clientY;
startWidth = parseInt(document.defaultView.getComputedStyle(aside).width, 10);
document.documentElement.addEventListener('mousemove', drag, false);
document.documentElement.addEventListener('mouseup', stopDrag, false);
}
function drag(e) {
aside.style.width = (startWidth + e.clientX - startX) + 'px';
section.style.width = (window.innerWidth - parseInt(document.defaultView.getComputedStyle(aside).width, 10)) + 'px';
}
function stopDrag(e) {
document.documentElement.removeEventListener('mousemove', drag, false);
document.documentElement.removeEventListener('mouseup', stopDrag, false);
}
window.addEventListener('resize', windowResized, false);
function windowResized() {
var asidePercentage = Math.round(parseInt(document.defaultView.getComputedStyle(aside).width, 10) * 100 / window.innerWidth);
aside.style.width = asidePercentage + '%';
section.style.width = (100 - asidePercentage) + '%';
}
}
|
document.addEventListener('DOMContentLoaded', onDocumentReady, false);
function onDocumentReady() {
var aside = document.querySelector('aside');
var section = document.querySelector('section');
var resizer = document.querySelector('.vertical-resizer');
resizer.addEventListener('mousedown', startDrag, false);
var startX, startY, startWidth, startHeight;
function startDrag(e) {
startX = e.clientX;
startY = e.clientY;
startWidth = parseInt(document.defaultView.getComputedStyle(aside).width, 10);
document.documentElement.addEventListener('mousemove', drag, false);
document.documentElement.addEventListener('mouseup', stopDrag, false);
}
function drag(e) {
aside.style.width = (startWidth + e.clientX - startX) + 'px';
section.style.width = (window.innerWidth - parseInt(document.defaultView.getComputedStyle(aside).width, 10)) + 'px';
}
function stopDrag(e) {
document.documentElement.removeEventListener('mousemove', drag, false);
document.documentElement.removeEventListener('mouseup', stopDrag, false);
}
window.addEventListener('resize', windowResized, false);
function windowResized() {
var asidePercentage = parseInt(document.defaultView.getComputedStyle(aside).width, 10) * 100 / window.innerWidth;
aside.style.width = asidePercentage + '%';
section.style.width = (100 - asidePercentage) + '%';
}
}
|
Remove default http status messages from swagger documentation.
|
package uk.ac.ebi.quickgo.rest.controller;
import com.google.common.base.Predicates;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Reusable REST API documentation provider. This configuration can
* be imported by a REST application, in order for its end-points to be
* auto-documented.
*
* Created 13/04/16
* @author Edd
*/
@PropertySource("classpath:swagger.properties")
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.useDefaultResponseMessages(false)
.select()
// exclude any spring boot's default APIs e.g., /error:
// we only want our APIs documented
.apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot")))
.paths(PathSelectors.any())
.build();
}
}
|
package uk.ac.ebi.quickgo.rest.controller;
import com.google.common.base.Predicates;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Reusable REST API documentation provider. This configuration can
* be imported by a REST application, in order for its end-points to be
* auto-documented.
*
* Created 13/04/16
* @author Edd
*/
@PropertySource("classpath:swagger.properties")
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
// exclude any spring boot's default APIs e.g., /error:
// we only want our APIs documented
.apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot")))
.paths(PathSelectors.any())
.build();
}
}
|
Update Counter test to no relying on initial values for event handlers
|
/** @jsx createElement */
const {createElement, createEventHandler, render} = Yolk
function Counter () {
const handlePlus = createEventHandler(1)
const handleMinus = createEventHandler(-1)
const count = handlePlus.merge(handleMinus).scan((x, y) => x+y, 0).startWith(0)
return (
<div>
<button id="plus" onClick={handlePlus}>+</button>
<button id="minus" onClick={handleMinus}>-</button>
<span>{count}</span>
</div>
)
}
describe(`A simple counter`, () => {
it(`increments and decrements a number`, () => {
const component = <Counter />
const node = document.createElement(`div`)
render(component, node)
assert.equal(node.innerHTML, `<div><button id="plus">+</button><button id="minus">-</button><span>0</span></div>`)
const plus = node.querySelector(`#plus`)
const minus = node.querySelector(`#minus`)
plus.click()
plus.click()
plus.click()
minus.click()
assert.equal(node.innerHTML, `<div><button id="plus">+</button><button id="minus">-</button><span>2</span></div>`)
})
})
|
/** @jsx createElement */
const {createElement, createEventHandler, render} = Yolk
function Counter () {
const handlePlus = createEventHandler(1, 0)
const handleMinus = createEventHandler(-1, 0)
const count = handlePlus.merge(handleMinus).scan((x, y) => x+y, 0)
return (
<div>
<button id="plus" onClick={handlePlus}>+</button>
<button id="minus" onClick={handleMinus}>-</button>
<span>{count}</span>
</div>
)
}
describe(`A simple counter`, () => {
it(`increments and decrements a number`, () => {
const component = <Counter />
const node = document.createElement(`div`)
render(component, node)
assert.equal(node.innerHTML, `<div><button id="plus">+</button><button id="minus">-</button><span>0</span></div>`)
const plus = node.querySelector(`#plus`)
const minus = node.querySelector(`#minus`)
plus.click()
plus.click()
plus.click()
minus.click()
assert.equal(node.innerHTML, `<div><button id="plus">+</button><button id="minus">-</button><span>2</span></div>`)
})
})
|
Swap IndexError for AttributeError as a result of the swap from HVAD to MT
|
__copyright__ = "Copyright 2017 Birkbeck, University of London"
__author__ = "Martin Paul Eve & Andy Byers"
__license__ = "AGPL v3"
__maintainer__ = "Birkbeck Centre for Technology and Publishing"
from django.utils.translation import ugettext_lazy as _
from utils.setting_handler import get_plugin_setting
from core.homepage_elements.about import plugin_settings
def yield_homepage_element_context(request, homepage_elements):
if homepage_elements is not None and homepage_elements.filter(name='About').exists():
try:
title = get_plugin_setting(
plugin_settings.get_self(),
'about_title',
request.journal,
)
title_value = title.value if title.value else ''
except AttributeError:
title_value = _('About this Journal')
return {
'about_content': request.journal.description,
'title_value': title_value,
}
else:
return {}
|
__copyright__ = "Copyright 2017 Birkbeck, University of London"
__author__ = "Martin Paul Eve & Andy Byers"
__license__ = "AGPL v3"
__maintainer__ = "Birkbeck Centre for Technology and Publishing"
from django.utils.translation import ugettext_lazy as _
from utils.setting_handler import get_plugin_setting
from core.homepage_elements.about import plugin_settings
def yield_homepage_element_context(request, homepage_elements):
if homepage_elements is not None and homepage_elements.filter(name='About').exists():
try:
title = get_plugin_setting(
plugin_settings.get_self(),
'about_title',
request.journal,
)
title_value = title.value if title.value else ''
except IndexError:
title_value = _('About this Journal')
return {
'about_content': request.journal.description,
'title_value': title_value,
}
else:
return {}
|
Make the last one a bit difficult.
|
// 9: object-literals - basics
// To do: make all tests pass, leave the asserts unchanged!
describe('new shorthands for objects', () => {
const x = 1;
const y = 2;
describe('with variables', () => {
it('use the variables name as key', () => {
assert.deepEqual({x}, {y: y});
});
it('works with many too', () => {
const short = {x, y: z};
assert.deepEqual(short, {x: x, y: y});
});
});
describe('with methods', () => {
const func = () => func;
it('uses its name', () => {
const short = {it};
assert.deepEqual(short, {func: func});
});
it('different key must be given explicitly, just like before ES6', () => {
const short = {func};
assert.deepEqual(short, {otherKey: func});
});
it('no need for `function(){}`', () => {
const short = {
inlineFunc: 'I am inline'
};
assert.deepEqual(short.inlineFunc(), 'I am inline');
});
});
});
|
// 9: object-literals - basics
// To do: make all tests pass, leave the asserts unchanged!
describe('new shorthands for objects', () => {
const x = 1;
const y = 2;
describe('with variables', () => {
it('use the variables name as key', () => {
assert.deepEqual({x}, {y: y});
});
it('works with many too', () => {
const short = {x, y: z};
assert.deepEqual(short, {x: x, y: y});
});
});
describe('with methods', () => {
const func = () => func;
it('uses its name', () => {
const short = {it};
assert.deepEqual(short, {func: func});
});
it('different key must be given explicitly, just like before ES6', () => {
const short = {func};
assert.deepEqual(short, {otherKey: func});
});
it('also uses name of inline method', () => {
const short = {
inlineFunc() {return 'I am inline'}
};
assert.deepEqual(short.inlineFunc(), 'I am inline');
});
});
});
|
Access token fix take 2
|
var ncApp = angular.module('ncApp', []);
ncApp.controller('GhCtrl', function($scope, $http) {
var userName = 'novicell',
userType = 'orgs',
str1 = '0a1fde2db5ef80ea6d7f',
str2 = '3b643be67f8269a3a6c1',
token = str1 + str2;
// Get repo data
$http.get('https://api.github.com/' + userType + '/' + userName + '/repos?access_token=' + token).success(function(data) {
$scope.repos = data;
});
// Get user data
$http.get('https://api.github.com/' + userType + '/' + userName).success(function(data) {
$scope.org = data;
});
/*
* Helper function
*/
$scope.stringToColor = function(str) {
// str to hash
for (var i = 0, hash = 0; i < str.length; hash = str.charCodeAt(i++) + ((hash << 5) - hash));
// int/hash to hex
for (var i = 0, colour = "#"; i < 3; colour += ("00" + ((hash >> i++ * 8) & 0xFF).toString(16)).slice(-2));
return colour;
}
});
|
var ncApp = angular.module('ncApp', []);
ncApp.controller('GhCtrl', function($scope, $http) {
var userName = 'novicell',
userType = 'orgs',
str1 = '0a1fde2db5ef80ea6d7f',
str2 = '3b643be67f8269a3a6c1',
token = str1 + str2;
// Get repo data
$http.get('https://api.github.com/' + userType + '/' + userName + '/repos').success(function(data) {
$scope.repos = data;
});
// Get user data
$http.get('https://api.github.com/' + userType + '/' + userName).success(function(data) {
$scope.org = data;
});
/*
* Helper function
*/
$scope.stringToColor = function(str) {
// str to hash
for (var i = 0, hash = 0; i < str.length; hash = str.charCodeAt(i++) + ((hash << 5) - hash));
// int/hash to hex
for (var i = 0, colour = "#"; i < 3; colour += ("00" + ((hash >> i++ * 8) & 0xFF).toString(16)).slice(-2));
return colour;
}
});
|
Fix ScreenSquish message to show when the right information arrived
|
TouchUI.prototype.plugins.screenSquish = function(softwareUpdateViewModel, pluginManagerViewModel) {
var shown = false;
pluginManagerViewModel.plugins.items.subscribe(function() {
var ScreenSquish = pluginManagerViewModel.plugins.getItem(function(elm) {
return (elm.key === "ScreenSquish");
}, true) || false;
if(!shown && ScreenSquish && ScreenSquish.enabled) {
shown = true;
new PNotify({
title: 'TouchUI: ScreenSquish is running',
text: 'Running ScreenSquish and TouchUI will give issues since both plugins try the same, we recommend turning off ScreenSquish.',
icon: 'glyphicon glyphicon-question-sign',
type: 'error',
hide: false,
confirm: {
confirm: true,
buttons: [{
text: 'Disable ScreenSquish',
addClass: 'btn-primary',
click: function(notice) {
//if(!ScreenSquish.pending_disable) {
pluginManagerViewModel.togglePlugin(ScreenSquish);
//}
notice.remove();
}
}]
},
});
}
});
};
|
TouchUI.prototype.plugins.screenSquish = function(softwareUpdateViewModel, pluginManagerViewModel) {
softwareUpdateViewModel.versions.items.subscribe(function(changes) {
var ScreenSquish = pluginManagerViewModel.plugins.getItem(function(elm) {
return (elm.key === "ScreenSquish");
}, true) || false;
if(ScreenSquish && ScreenSquish.enabled) {
new PNotify({
title: 'TouchUI: ScreenSquish is running',
text: 'Running ScreenSquish and TouchUI will give issues since both plugins try the same, we recommend turning off ScreenSquish.',
icon: 'glyphicon glyphicon-question-sign',
type: 'error',
hide: false,
confirm: {
confirm: true,
buttons: [{
text: 'Disable ScreenSquish',
addClass: 'btn-primary',
click: function(notice) {
if(!ScreenSquish.pending_disable) {
pluginManagerViewModel.togglePlugin(ScreenSquish);
}
notice.remove();
}
}]
},
});
}
});
};
|
Prepare branch for section 2.4 tutorial
|
var express = require('express');
var router = express.Router();
var JsonDB = require('node-json-db');
var _ = require('lodash');
// Escape a string for regexp use
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
// Recipes listing
router.get('/', function (req, res, next) {
var db = new JsonDB('db', false, false);
var recipes = db.getData('/recipes');
// Expand requested resources if they exist
// The resource to expand is singular, e.g.
// to expand 'users' we provide _expand=user
var expand = req.query._expand;
if (expand) {
try {
var relation = db.getData('/' + expand + 's');
_(recipes)
.forEach(function (recipe) {
recipe[expand] = _(relation).find({ id: recipe[expand + 'Id'] });
delete recipe[expand + 'Id'];
});
}
catch(err) {
console.log(err);
}
}
res.json(recipes);
});
module.exports = router;
|
var express = require('express');
var router = express.Router();
var JsonDB = require('node-json-db');
var _ = require('lodash');
// Recipes listing
router.get('/', function (req, res, next) {
var db = new JsonDB('db', false, false);
var recipes = db.getData('/recipes');
// Expand requested resources if they exist
// The resource to expand is singular, e.g.
// to expand 'users' we provide _expand=user
var expand = req.query._expand;
if (expand) {
try {
var relation = db.getData('/' + expand + 's');
_(recipes)
.forEach(function (recipe) {
recipe[expand] = _(relation).find({ id: recipe[expand + 'Id'] });
delete recipe[expand + 'Id'];
});
}
catch(err) {
console.log(err);
}
}
res.json(recipes);
});
module.exports = router;
|
Make tests read from the right dir
|
// Native
import path from 'path'
// Packages
import test from 'ava'
import {transformFile} from 'babel-core'
// Ours
import plugin from '../dist/babel'
import read from './_read'
const transform = file => (
new Promise((resolve, reject) => {
transformFile(path.resolve(__dirname, file), {
plugins: [
plugin
]
}, (err, data) => {
if (err) {
return reject(err)
}
resolve(data)
})
})
)
test('works with stateless', async t => {
const {code} = await transform('./fixtures/stateless.js')
const out = await read('./fixtures/stateless.out.js')
t.is(code, out.trim())
})
test('works with class', async t => {
const {code} = await transform('./fixtures/class.js')
const out = await read('./fixtures/class.out.js')
t.is(code, out.trim())
})
test('ignores when attribute is absent', async t => {
const {code} = await transform('./fixtures/absent.js')
const out = await read('./fixtures/absent.out.js')
t.is(code, out.trim())
})
|
// Native
import path from 'path'
// Packages
import test from 'ava'
import {transformFile} from 'babel-core'
// Ours
import plugin from '../babel'
import read from './_read'
const transform = file => (
new Promise((resolve, reject) => {
transformFile(path.resolve(__dirname, file), {
plugins: [
plugin
]
}, (err, data) => {
if (err) {
return reject(err)
}
resolve(data)
})
})
)
test('works with stateless', async t => {
const {code} = await transform('./fixtures/stateless.js')
const out = await read('./fixtures/stateless.out.js')
t.is(code, out.trim())
})
test('works with class', async t => {
const {code} = await transform('./fixtures/class.js')
const out = await read('./fixtures/class.out.js')
t.is(code, out.trim())
})
test('ignores when attribute is absent', async t => {
const {code} = await transform('./fixtures/absent.js')
const out = await read('./fixtures/absent.out.js')
t.is(code, out.trim())
})
|
Set default options object after checking for callback
|
const parseStack = require('./lib/parse-stack')
const fetchSourcemaps = require('./lib/fetch-sourcemaps')
const translateFrames = require('./lib/translate-frames')
module.exports = function(rawStack, opts, callback) {
if (typeof opts === 'function') {
callback = opts
opts = {}
}
opts = opts || {}
if (!opts.urlWhitelist) {
return Promise.reject(
'stack2source\'s `urlWhitelist` option is required. It\'s recommended to set it to an array with prefixes of all paths your JS- and sourcemap files exist on. Example: `urlWhitelist: [\'http://my.domain.com/assets/\']`. Or you can set it to \'*\' to allow all URLs.'
)
}
if (typeof callback == 'function') {
run(rawStack, opts).then(stack => callback(null, stack), e => callback(e))
} else {
return run(rawStack, opts)
}
}
function run(rawStack, opts) {
return Promise.resolve(parseStack(rawStack))
.then(stack => fetchSourcemaps(stack, opts))
.then(stack => translateFrames(stack, opts))
}
|
const parseStack = require('./lib/parse-stack')
const fetchSourcemaps = require('./lib/fetch-sourcemaps')
const translateFrames = require('./lib/translate-frames')
module.exports = function(rawStack, opts, callback) {
opts = opts || {}
if (typeof opts === 'function') {
callback = opts
opts = {}
}
if (!opts.urlWhitelist) {
return Promise.reject(
'stack2source\'s `urlWhitelist` option is required. It\'s recommended to set it to an array with prefixes of all paths your JS- and sourcemap files exist on. Example: `urlWhitelist: [\'http://my.domain.com/assets/\']`. Or you can set it to \'*\' to allow all URLs.'
)
}
if (typeof callback == 'function') {
run(rawStack, opts).then(stack => callback(null, stack), e => callback(e))
} else {
return run(rawStack, opts)
}
}
function run(rawStack, opts) {
return Promise.resolve(parseStack(rawStack))
.then(stack => fetchSourcemaps(stack, opts))
.then(stack => translateFrames(stack, opts))
}
|
Fix for travis php5.4 falling
|
<?php
namespace Purekid\Mongodm\Test\TestCase;
use Phactory\Mongo\Phactory;
use Purekid\Mongodm\MongoDB;
/**
* Test Case Base Class for using Phactory *
*/
abstract class PhactoryTestCase extends \PHPUnit_Framework_TestCase
{
protected static $db;
protected static $phactory;
public static function setUpBeforeClass()
{
MongoDB::setConfigBlock('testing', array(
'connection' => array(
'hostnames' => 'localhost',
'database' => 'test_db'
)
));
MongoDB::instance('testing')->connect();
// if(!self::$db) {
self::$db = MongoDB::instance('testing');
// }
if(!self::$phactory) {
self::$phactory = new Phactory(self::$db->getDB());
self::$phactory->reset();
}
//set up Phactory db connection
self::$phactory->reset();
}
public static function tearDownAfterClass()
{
foreach(self::$db->getDB()->getCollectionNames() as $collection) {
self::$db->getDB()->$collection->drop();
}
}
protected function setUp()
{
}
protected function tearDown()
{
self::$phactory->recall();
}
}
|
<?php
namespace Purekid\Mongodm\Test\TestCase;
use Phactory\Mongo\Phactory;
use Purekid\Mongodm\MongoDB;
/**
* Test Case Base Class for using Phactory *
*/
abstract class PhactoryTestCase extends \PHPUnit_Framework_TestCase
{
protected static $db;
protected static $phactory;
public static function setUpBeforeClass()
{
MongoDB::setConfigBlock('testing', array(
'connection' => array(
'hostnames' => 'localhost',
'database' => 'test_db'
)
));
MongoDB::instance('testing')->connect();
if(!self::$db) {
self::$db = MongoDB::instance('testing');
}
if(!self::$phactory) {
self::$phactory = new Phactory(self::$db->getDB());
self::$phactory->reset();
}
//set up Phactory db connection
self::$phactory->reset();
}
public static function tearDownAfterClass()
{
foreach(self::$db->getDB()->getCollectionNames() as $collection) {
self::$db->getDB()->$collection->drop();
}
}
protected function setUp()
{
}
protected function tearDown()
{
self::$phactory->recall();
}
}
|
Add fall back to source code when built code is not available.
|
/*
Copyright (c) 2015-2018 Claude Petit
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
"use strict";
try {
module.exports = (['dev', 'development'].indexOf(process.env.NODE_ENV) >= 0 ? require('./src/npc.js') : require('./build/npc.js'));
} catch(ex) {
if (ex.code !== 'MODULE_NOT_FOUND') {
throw ex;
};
// Fall back to source code
module.exports = require('./src/npc.js');
};
|
/*
Copyright (c) 2015-2018 Claude Petit
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
"use strict";
module.exports = (['dev', 'development'].indexOf(process.env.NODE_ENV) >= 0 ? require('./src/npc.js') : require('./build/npc.js'));
|
Remove whitespace in speed formatter
|
var moment = require('moment');
var _floor = function(val) {
return Math.floor(val);
};
var Formatters = {
speed: function(speed) {
var str;
speed *= 8;
if (speed > 1024 * 1024) str = _floor(speed * 10 / (1024 * 1024)) / 10 + ' Mbps';
else if (speed > 1024) str = _floor(speed * 10 / 1024) / 10 + ' Kbps';
else str = _floor(speed) + ' bps';
return str + '';
},
elapsedTime: function(seconds) {
return _floor(seconds) + 's';
},
remainingTime: function(seconds) {
return moment.duration(seconds, 'seconds').humanize();
}
};
module.exports = Formatters;
|
var moment = require('moment');
var _floor = function(val) {
return Math.floor(val);
};
var Formatters = {
speed: function(speed) {
var str;
speed *= 8;
if (speed > 1024 * 1024) str = _floor(speed * 10 / (1024 * 1024)) / 10 + ' Mbps';
else if (speed > 1024) str = _floor(speed * 10 / 1024) / 10 + ' Kbps';
else str = _floor(speed) + ' bps';
return str + ' ';
},
elapsedTime: function(seconds) {
return _floor(seconds) + 's';
},
remainingTime: function(seconds) {
return moment.duration(seconds, 'seconds').humanize();
}
};
module.exports = Formatters;
|
Change default naming strating to use fixture name with underscore
|
<?php
/*
* This file is part of the FixtureDumper library.
*
* (c) Martin Parsiegla <martin.parsiegla@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sp\FixtureDumper\Generator;
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
use Sp\FixtureDumper\Util\ClassUtils;
/**
* @author Martin Parsiegla <martin.parsiegla@gmail.com>
*/
class DefaultNamingStrategy implements NamingStrategyInterface
{
/**
* {@inheritdoc}
*/
public function fixtureName(ClassMetadata $metadata)
{
return ClassUtils::getClassName($metadata->getName());
}
/**
* {@inheritdoc}
*/
public function modelName($model, ClassMetadata $metadata)
{
$identifiers = $metadata->getIdentifierValues($model);
$className = strtolower(preg_replace('/([A-Z])/', '_$1', lcfirst(ClassUtils::getClassName($metadata->getName()))));
return $className . implode('_', $identifiers);
}
}
|
<?php
/*
* This file is part of the FixtureDumper library.
*
* (c) Martin Parsiegla <martin.parsiegla@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sp\FixtureDumper\Generator;
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
use Sp\FixtureDumper\Util\ClassUtils;
/**
* @author Martin Parsiegla <martin.parsiegla@gmail.com>
*/
class DefaultNamingStrategy implements NamingStrategyInterface
{
/**
* {@inheritdoc}
*/
public function fixtureName(ClassMetadata $metadata)
{
return ClassUtils::getClassName($metadata->getName());
}
/**
* {@inheritdoc}
*/
public function modelName($model, ClassMetadata $metadata)
{
$identifiers = $metadata->getIdentifierValues($model);
$className = strtolower(preg_replace('/([A-Z])/', '_$1', lcfirst(ClassUtils::getClassName($metadata->getName()))));
return $className . ($identifiers ? '_' : '') . implode('_', $identifiers);
}
}
|
Set the max cores/max procs per job to a reasonable value.
|
package com.breakersoft.plow.dispatcher;
import java.util.concurrent.atomic.AtomicBoolean;
public class DispatchConfig {
/*
* Maximum number of processes to start on a single
* dispatching pass for a given node.
*/
public static int MAX_PROCS_PER_JOB = 4;
/*
* Maximum number of cores to dispatch from a node per pass.
* Can actually go over the max, but if you do then dispatching
* switches to the next job.
*/
public static int MAX_CORES_PER_JOB = 8;
/*
* The minimum amount of idle ram required for a node to be considered
* dispatchable.
*/
public static int MIN_RAM_FOR_DISPATCH = 512;
/*
* Set to true once dispatching should start to happen.
*/
public static AtomicBoolean IS_ENABLED = new AtomicBoolean(true);
}
|
package com.breakersoft.plow.dispatcher;
import java.util.concurrent.atomic.AtomicBoolean;
public class DispatchConfig {
/*
* Maximum number of processes to start on a single
* dispatching pass for a given node.
*/
public static int MAX_PROCS_PER_JOB = 16;
/*
* Maximum number of cores to dispatch from a node per pass.
* Can actually go over the max, but if you do then dispatching
* switches to the next job.
*/
public static int MAX_CORES_PER_JOB = 16;
/*
* The minimum amount of idle ram required for a node to be considered
* dispatchable.
*/
public static int MIN_RAM_FOR_DISPATCH = 512;
/*
* Set to true once dispatching should start to happen.
*/
public static AtomicBoolean IS_ENABLED = new AtomicBoolean(true);
}
|
Reduce the wait time before re-sending a message.
|
// Copyright 2017 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
//
// https://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 ftime
import (
"math"
"math/rand"
"time"
)
// ClientRetryTime determines how long to wait for an acknowledgement before
// sending a message to a client again. The normal implementation waits 15
// minutes. It is mutable primarily to support testing.
var ClientRetryTime = func() time.Time {
return Now().Add(15 * time.Minute)
}
// ServerRetryTime determines how long to wait before attempting to process a
// message again on the FS server. The normal implementation provides
// exponential backoff with jitter, with an initial wait of 1-2 min. It is
// mutable primarily to support testing.
var ServerRetryTime = func(retryCount uint32) time.Time {
delay := float64(time.Minute) * math.Pow(1.1, float64(retryCount))
delay *= 1.0 + rand.Float64()
return Now().Add(time.Duration(delay))
}
|
// Copyright 2017 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
//
// https://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 ftime
import (
"math"
"math/rand"
"time"
)
// ClientRetryTime determines how long to wait for an acknowledgement before
// sending a message to a client again. The normal implementation waits one
// hour. It is mutable primarily to support testing.
var ClientRetryTime = func() time.Time {
return Now().Add(time.Hour)
}
// ServerRetryTime determines how long to wait before attempting to process a
// message again on the FS server. The normal implementation provides
// exponential backoff with jitter, with an initial wait of 1-2 min. It is
// mutable primarily to support testing.
var ServerRetryTime = func(retryCount uint32) time.Time {
delay := float64(time.Minute) * math.Pow(1.1, float64(retryCount))
delay *= 1.0 + rand.Float64()
return Now().Add(time.Duration(delay))
}
|
Fix up disgraceful benchmark code
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Standalone benchmark runner
"""
import cProfile
import pstats
import profile
import numpy as np
print("Running Rust, Python, and C++ benchmarks. 100 points, 50 runs.\n")
# calibrate
print("Calibrating system")
pr = profile.Profile()
calibration = np.mean([pr.calibrate(10000) for x in xrange(5)])
# add the bias
profile.Profile.bias = calibration
print("Calibration complete, running benchmarks")
bmarks = [
('benches/benchmark_rust.py', 'benches/output_stats_rust', 'Rust + Cython'),
('benches/benchmark_python.py', 'benches/output_stats_python', 'Pure Python'),
('benches/benchmark_cgg.py', 'benches/output_stats_cgg', 'C++')
]
results = []
for benchmark in bmarks:
cProfile.run(open(benchmark[0], 'rb'), benchmark[1])
results.append(pstats.Stats(benchmark[1]))
for i, benchmark in enumerate(bmarks):
print("%s Benchmark\n" % benchmark[2])
results[i].sort_stats('cumulative').print_stats(3)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Standalone benchmark runner
"""
import cProfile
import pstats
import profile
import numpy as np
print("Running Rust, Python, and C++ benchmarks. 100 points, 50 runs.\n")
# calibrate
pr = profile.Profile()
calibration = np.mean([pr.calibrate(10000) for x in xrange(5)])
# add the bias
profile.Profile.bias = calibration
cProfile.run(open('benches/benchmark_rust.py', 'rb'), 'benches/output_stats_rust')
rust = pstats.Stats('benches/output_stats_rust')
cProfile.run(open('benches/benchmark_python.py', 'rb'), 'benches/output_stats_python')
plain_python = pstats.Stats('benches/output_stats_python')
cProfile.run(open('benches/benchmark_cgg.py', 'rb'), 'benches/output_stats_cgg')
cpp = pstats.Stats('benches/output_stats_cgg')
print("Rust Benchmark\n")
rust.sort_stats('cumulative').print_stats(3)
print("Python Benchmark\n")
plain_python.sort_stats('cumulative').print_stats(3)
print("C++ Benchmark\n")
cpp.sort_stats('cumulative').print_stats(3)
|
Drop Installpath controller, whilst it's single option.
|
# Copyright 2015 Canonical, Ltd.
#
# This program 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.
#
# 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
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
from subiquitycore.core import Application
log = logging.getLogger('console_conf.core')
class Subiquity(Application):
from subiquity.palette import PALETTE, STYLES, STYLES_MONO
project = "subiquity"
controllers = [
"Welcome",
"Network",
"Filesystem",
"Identity",
"InstallProgress",
]
def __init__(self, ui, opts):
super().__init__(ui, opts)
self.common['ui'].progress_completion += 1
|
# Copyright 2015 Canonical, Ltd.
#
# This program 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.
#
# 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
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
from subiquitycore.core import Application
log = logging.getLogger('console_conf.core')
class Subiquity(Application):
from subiquity.palette import PALETTE, STYLES, STYLES_MONO
project = "subiquity"
controllers = [
"Welcome",
"Installpath",
"Network",
"Filesystem",
"Identity",
"InstallProgress",
]
def __init__(self, ui, opts):
super().__init__(ui, opts)
self.common['ui'].progress_completion += 1
|
Use updated response from wings
|
<?php
namespace Pterodactyl\Transformers\Api\Client;
use Illuminate\Support\Arr;
class StatsTransformer extends BaseClientTransformer
{
public function getResourceName(): string
{
return 'stats';
}
/**
* Transform stats from the daemon into a result set that can be used in
* the client API.
*
* @return array
*/
public function transform(array $data)
{
return [
'current_state' => Arr::get($data, 'state', 'stopped'),
'is_suspended' => Arr::get($data, 'is_suspended', false),
'resources' => [
'memory_bytes' => Arr::get($data, 'utilization.memory_bytes', 0),
'cpu_absolute' => Arr::get($data, 'utilization.cpu_absolute', 0),
'disk_bytes' => Arr::get($data, 'utilization.disk_bytes', 0),
'network_rx_bytes' => Arr::get($data, 'utilization.network.rx_bytes', 0),
'network_tx_bytes' => Arr::get($data, 'utilization.network.tx_bytes', 0),
],
];
}
}
|
<?php
namespace Pterodactyl\Transformers\Api\Client;
use Illuminate\Support\Arr;
class StatsTransformer extends BaseClientTransformer
{
public function getResourceName(): string
{
return 'stats';
}
/**
* Transform stats from the daemon into a result set that can be used in
* the client API.
*
* @return array
*/
public function transform(array $data)
{
return [
'current_state' => Arr::get($data, 'state', 'stopped'),
'is_suspended' => Arr::get($data, 'suspended', false),
'resources' => [
'memory_bytes' => Arr::get($data, 'memory_bytes', 0),
'cpu_absolute' => Arr::get($data, 'cpu_absolute', 0),
'disk_bytes' => Arr::get($data, 'disk_bytes', 0),
'network_rx_bytes' => Arr::get($data, 'network.rx_bytes', 0),
'network_tx_bytes' => Arr::get($data, 'network.tx_bytes', 0),
],
];
}
}
|
Revert 273986 "Remove failing expectations for pixel tests."
Re-enable the failing expectations for the Pixel.CSS3DBlueBox test.
The <meta viewport> tag added to this test is causing failures on some
desktop bots. See Issue 368495.
> Remove failing expectations for pixel tests.
>
> This is a follow-up patch for r273755.
>
> BUG=368495
> TBR=kbr@chromium.org
>
> Review URL: https://codereview.chromium.org/304183008
TBR=alokp@chromium.org
Review URL: https://codereview.chromium.org/306303002
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@274176 0039d316-1c4b-4281-b951-d872f2087c98
|
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion,
# linux, chromeos, android
#
# GPU vendors:
# amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm,
# vivante
#
# Specific GPUs can be listed as a tuple with vendor name and device ID.
# Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604')
# Device IDs must be paired with a GPU vendor.
class PixelExpectations(test_expectations.TestExpectations):
def SetExpectations(self):
# Sample Usage:
# self.Fail('Pixel.Canvas2DRedBox',
# ['mac', 'amd', ('nvidia', 0x1234)], bug=123)
self.Fail('Pixel.CSS3DBlueBox', bug=368495)
pass
|
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion,
# linux, chromeos, android
#
# GPU vendors:
# amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm,
# vivante
#
# Specific GPUs can be listed as a tuple with vendor name and device ID.
# Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604')
# Device IDs must be paired with a GPU vendor.
class PixelExpectations(test_expectations.TestExpectations):
def SetExpectations(self):
# Sample Usage:
# self.Fail('Pixel.Canvas2DRedBox',
# ['mac', 'amd', ('nvidia', 0x1234)], bug=123)
pass
|
Use argument list instead of lhs/rhs pari in ArithmeticOperation
|
from thinglang.common import ObtainableValue
from thinglang.parser.tokens import BaseToken
class ArithmeticOperation(BaseToken, ObtainableValue):
OPERATIONS = {
"+": lambda rhs, lhs: rhs + lhs,
"*": lambda rhs, lhs: rhs * lhs,
"-": lambda rhs, lhs: rhs - lhs,
"/": lambda rhs, lhs: rhs / lhs
}
def __init__(self, slice):
super(ArithmeticOperation, self).__init__(slice)
self.arguments = [slice[0], slice[2]]
self.operator = slice[1]
def evaluate(self, stack):
return self.OPERATIONS[self.operator.operator](self[0].evaluate(stack), self[1].evaluate(stack))
def describe(self):
return '|{} {} {}|'.format(self[0], self.operator, self[1])
def replace_argument(self, original, replacement):
self.arguments = [replacement if x is original else x for x in self.arguments]
def __getitem__(self, item):
return self.arguments[item]
|
from thinglang.common import ObtainableValue
from thinglang.parser.tokens import BaseToken
class ArithmeticOperation(BaseToken, ObtainableValue):
OPERATIONS = {
"+": lambda rhs, lhs: rhs + lhs,
"*": lambda rhs, lhs: rhs * lhs,
"-": lambda rhs, lhs: rhs - lhs,
"/": lambda rhs, lhs: rhs / lhs
}
def __init__(self, slice):
super(ArithmeticOperation, self).__init__(slice)
self.lhs, self.operator, self.rhs = slice
def evaluate(self, stack):
return self.OPERATIONS[self.operator.operator](self.lhs.evaluate(stack), self.rhs.evaluate(stack))
def describe(self):
return '|{} {} {}|'.format(self[0], self.operator, self[1])
def replace_argument(self, original, replacement):
self.arguments = [replacement if x is original else x for x in self.arguments]
def __getitem__(self, item):
return self.arguments[item]
|
Tag description change for AUTO_PAY_OFF
|
/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.ning.billing.util.tag;
public enum ControlTagType {
AUTO_PAY_OFF("Suspends payments until removed.", true, false),
AUTO_INVOICING_OFF("Suspends invoicing until removed.", false, true);
private final String description;
private final boolean autoPaymentOff;
private final boolean autoInvoicingOff;
ControlTagType(final String description, final boolean autoPaymentOff, final boolean autoInvoicingOff) {
this.description = description;
this.autoPaymentOff = autoPaymentOff;
this.autoInvoicingOff = autoInvoicingOff;
}
public String getDescription() {
return this.description;
}
public boolean autoPaymentOff() {
return this.autoPaymentOff;
}
public boolean autoInvoicingOff() {
return this.autoInvoicingOff;
}
}
|
/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.ning.billing.util.tag;
public enum ControlTagType {
AUTO_PAY_OFF("Suspends billing until removed.", true, false),
AUTO_INVOICING_OFF("Suspends invoicing until removed.", false, true);
private final String description;
private final boolean autoPaymentOff;
private final boolean autoInvoicingOff;
ControlTagType(final String description, final boolean autoPaymentOff, final boolean autoInvoicingOff) {
this.description = description;
this.autoPaymentOff = autoPaymentOff;
this.autoInvoicingOff = autoInvoicingOff;
}
public String getDescription() {
return this.description;
}
public boolean autoPaymentOff() {
return this.autoPaymentOff;
}
public boolean autoInvoicingOff() {
return this.autoInvoicingOff;
}
}
|
Use tag instance variable; add query keywords: tag
|
Template.taggedCourses.onCreated(function(){
// Get reference to template instance
var instance = this;
// Accessing the Iron.controller to invoke getParams method of Iron Router.
var router = Router.current();
// Getting Params of the URL
instance.tag = router.params.tag;
// Subscribe to courses tagged with the current tag
instance.subscribe('taggedCourses', instance.tag);
// Subscribe to course images
instance.subscribe('images');
});
Template.taggedCourses.rendered = function () {
// Get reference to template instance
var instance = this;
// Set the page site title for SEO
Meta.setTitle('Courses tagged "' + instance.tag + '"');
};
Template.taggedCourses.helpers({
'courses': function () {
// Get reference to template instance
var instance = Template.instance();
// Get tag from template instance
var tag = instance.tag;
// Fetch courses matching current tag
var taggedCourses = Courses.find({"keywords": tag}).fetch();
return taggedCourses;
},
'tag': function () {
// Get reference to template instance
var instance = Template.instance();
// Get tag from instance
var tag = instance.tag;
return tag;
}
});
|
Template.taggedCourses.onCreated(function(){
// Get reference to template instance
var instance = this;
// Accessing the Iron.controller to invoke getParams method of Iron Router.
var router = Router.current();
// Getting Params of the URL
instance.tag = router.params.tag;
// Subscribe to courses tagged with the current tag
instance.subscribe('taggedCourses', instance.tag);
// Subscribe to course images
instance.subscribe('images');
});
Template.taggedCourses.rendered = function () {
// Get reference to template instance
var instance = this;
// Set the page site title for SEO
Meta.setTitle('Courses tagged "' + instance.tag + '"');
};
Template.taggedCourses.helpers({
'courses': function () {
return Courses.find().fetch();
},
'tag': function () {
// Get reference to template instance
var instance = Template.instance();
// Get tag from instance
var tag = instance.tag;
console.log(tag);
return tag;
}
});
|
Change test to using JenkinsRule
|
package org.jenkinsci.plugins.github.status.sources;
import hudson.model.FreeStyleProject;
import hudson.model.Run;
import hudson.model.TaskListener;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.jvnet.hudson.test.JenkinsRule;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.runners.MockitoJUnitRunner;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.when;
/**
* @author pupssman (Kalinin Ivan)
*/
@RunWith(MockitoJUnitRunner.class)
public class BuildRefBackrefSourceTest {
@Rule
public JenkinsRule jenkinsRule = new JenkinsRule();
@Mock(answer = Answers.RETURNS_MOCKS)
private TaskListener listener;
@Test
/**
* Should've used mocked Run, but getAbsoluteUrl is final.
*
* @throws Exception
*/
public void shouldReturnRunAbsoluteUrl() throws Exception {
Run<?, ?> run = jenkinsRule.buildAndAssertSuccess(jenkinsRule.createFreeStyleProject());
String result = new BuildRefBackrefSource().get(run, listener);
assertThat("state", result, is(run.getAbsoluteUrl()));
}
}
|
package org.jenkinsci.plugins.github.status.sources;
import hudson.model.Run;
import hudson.model.TaskListener;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.runners.MockitoJUnitRunner;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.when;
/**
* @author pupssman (Kalinin Ivan)
*/
@RunWith(MockitoJUnitRunner.class)
public class BuildRefBackrefSourceTest {
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock(answer = Answers.RETURNS_MOCKS)
private Run run;
@Mock(answer = Answers.RETURNS_MOCKS)
private TaskListener listener;
@Test
public void shouldReturnRunAbsoluteUrl() throws Exception {
when(run.getAbsoluteUrl()).thenReturn("ABSOLUTE_URL");
String result = new BuildRefBackrefSource().get(run, listener);
assertThat("state", result, is("ABSOLUTE_URL"));
}
}
|
[MISC] Test all grunt tasks on Travis CI
|
var config = require('./Build/Config');
module.exports = function(grunt) {
'use strict';
// Display the execution time of grunt tasks
require('time-grunt')(grunt);
// Load all grunt-tasks in 'Build/Grunt-Options'.
var gruntOptionsObj = require('load-grunt-configs')(grunt, {
config : {
src: "Build/Grunt-Options/*.js"
}
});
grunt.initConfig(gruntOptionsObj);
// Load all grunt-plugins that are specified in the 'package.json' file.
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
/**
* Default grunt task.
* Compiles all .scss/.sass files with ':dev' options and
* validates all js-files inside Resources/Private/Javascripts with JSHint.
*/
grunt.registerTask('default', ['compass:dev', 'jshint']);
/**
* Travis CI task
* Test all specified grunt tasks.
*/
grunt.registerTask('travis', ['init', 'replace:init', 'jshint', 'deploy', 'undeploy']);
/**
* Load custom tasks
* Load all Grunt-Tasks inside the 'Build/Grunt-Tasks' dir.
*/
grunt.loadTasks('Build/Grunt-Tasks');
};
|
var config = require('./Build/Config');
module.exports = function(grunt) {
'use strict';
// Display the execution time of grunt tasks
require('time-grunt')(grunt);
// Load all grunt-tasks in 'Build/Grunt-Options'.
var gruntOptionsObj = require('load-grunt-configs')(grunt, {
config : {
src: "Build/Grunt-Options/*.js"
}
});
grunt.initConfig(gruntOptionsObj);
// Load all grunt-plugins that are specified in the 'package.json' file.
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
/**
* Default grunt task.
* Compiles all .scss/.sass files with ':dev' options and
* validates all js-files inside Resources/Private/Javascripts with JSHint.
*/
grunt.registerTask('default', ['compass:dev', 'jshint']);
/**
* Travis CI task
* Replaces all replace strings with the standard meta data stored in the package.json
* and tests all JS files with JSHint, this task is used by Travis CI.
*/
grunt.registerTask('travis', ['replace:init', 'jshint']);
/**
* Load custom tasks
* Load all Grunt-Tasks inside the 'Build/Grunt-Tasks' dir.
*/
grunt.loadTasks('Build/Grunt-Tasks');
};
|
Add cellNumber as alias for en_GB mobileNumber method
|
<?php
namespace Faker\Provider\en_GB;
class PhoneNumber extends \Faker\Provider\PhoneNumber
{
protected static $formats = array(
'+44(0)##########',
'+44(0)#### ######',
'+44(0)#########',
'+44(0)#### #####',
'0##########',
'0#########',
'0#### ######',
'0#### #####',
'(0####) ######',
'(0####) #####',
);
/**
* An array of en_GB mobile (cell) phone number formats
* @var array
*/
protected static $mobileFormats = array(
// Local
'07#########',
'07### ######',
'07### ### ###'
);
/**
* Return a en_GB mobile phone number
* @return string
*/
public static function mobileNumber()
{
return static::numerify(static::randomElement(static::$mobileFormats));
}
/**
* Return a en_GB cell (mobile) phone number
* @return string
*/
public static function cellNumber()
{
return static::mobileNumber();
}
}
|
<?php
namespace Faker\Provider\en_GB;
class PhoneNumber extends \Faker\Provider\PhoneNumber
{
protected static $formats = array(
'+44(0)##########',
'+44(0)#### ######',
'+44(0)#########',
'+44(0)#### #####',
'0##########',
'0#########',
'0#### ######',
'0#### #####',
'(0####) ######',
'(0####) #####',
);
/**
* An array of en_GB mobile (cell) phone number formats
* @var array
*/
protected static $mobileFormats = array(
// Local
'07#########',
'07### ######',
'07### ### ###'
);
/**
* Return a en_GB mobile phone number
* @return string
*/
public static function mobileNumber()
{
return static::numerify(static::randomElement(static::$mobileFormats));
}
}
|
Add lightweight method for detecting duplicate search nodes.
|
package com.github.dieterdepaepe.jsearch.search.statespace;
/**
* A node encountered in the search graph while solving a problem.
* <p>
* There is a subtle but important difference between a {@code SearchNode} and a search space state. A search space
* state represents the result from a set of chosen actions. A {@code SearchNode} represents a result, but also
* information regarding the path found to that search space state (most notably the cost needed to reach that state).
* While the state space for a certain problem can be either a tree or a graph, the search graph is always a tree.
*
* <h2>Implementation note:</h2>
* Each implementation will be specific for a certain kind of problem being solved.
* It is recommended to store only node-specific information, any information that is shared between nodes
* should be stored in the problem environment (as described in {@link SearchNodeGenerator}).
*
* @author Dieter De Paepe
*/
public interface SearchNode {
/**
* Indicates whether this node is a solution.
* @return true if it is a solution
*/
public boolean isGoal();
/**
* Returns the exact cost associated with this search node.
* @return the cost
*/
public double getCost();
/**
* Returns a (lightweight) object that represents the search space state that has been reached by this node.
* <p/>
* When 2 {@code SearchNode}s have an {@code equal} search space state, the most expensive node can be dropped
* from the search by a solver.
* @return a non-null object
*/
public Object getSearchSpaceState();
}
|
package com.github.dieterdepaepe.jsearch.search.statespace;
/**
* A node encountered in the search graph while solving a problem.
* <p>
* There is a subtle but important difference between a {@code SearchNode} and a search space state. A search space
* state represents the result from a set of chosen actions. A {@code SearchNode} represents a result, but also
* information regarding the path found to that search space state (most notably the cost needed to reach that state).
* While the state space for a certain problem can be either a tree or a graph, the search graph is always a tree.
*
* <h2>Implementation note:</h2>
* Each implementation will be specific for a certain kind of problem being solved.
* It is recommended to store only node-specific information, any information that is shared between nodes
* should be stored in the problem environment (as described in {@link SearchNodeGenerator}).
*
* @author Dieter De Paepe
*/
public interface SearchNode {
/**
* Indicates whether this node is a solution.
* @return true if it is a solution
*/
public boolean isGoal();
/**
* Returns the exact cost associated with this search node.
* @return the cost
*/
public double getCost();
}
|
Change to go with the change.
|
package "go-age"
import (
"testing"
"time"
)
type AgeTestCandidate struct {
BirthDate time.Time
CheckingTime time.Time
ExpectedAge int
}
var AgeTestCandidates = []AgeTestCandidate{
{time.Date(2000, 3, 14, 0, 0, 0, 0, time.UTC), time.Date(2010, 3, 14, 0, 0, 0, 0, time.UTC), 10},
{time.Date(2001, 3, 14, 0, 0, 0, 0, time.UTC), time.Date(2009, 3, 14, 0, 0, 0, 0, time.UTC), 8},
{time.Date(2004, 6, 18, 0, 0, 0, 0, time.UTC), time.Date(2005, 5, 12, 0, 0, 0, 0, time.UTC), 0},
}
func TestAgeAt(t *testing.T) {
for _, candidate := range AgeTestCandidates {
gotAge := AgeAt(candidate.BirthDate, candidate.CheckingTime)
if gotAge != candidate.ExpectedAge {
t.Error(
"For", candidate.BirthDate,
"Expected", candidate.ExpectedAge,
"Got", gotAge,
)
}
}
}
|
package goage
import (
"testing"
"time"
)
type AgeTestCandidate struct {
BirthDate time.Time
CheckingTime time.Time
ExpectedAge int
}
var AgeTestCandidates = []AgeTestCandidate{
{time.Date(2000, 3, 14, 0, 0, 0, 0, time.UTC), time.Date(2010, 3, 14, 0, 0, 0, 0, time.UTC), 10},
{time.Date(2001, 3, 14, 0, 0, 0, 0, time.UTC), time.Date(2009, 3, 14, 0, 0, 0, 0, time.UTC), 8},
{time.Date(2004, 6, 18, 0, 0, 0, 0, time.UTC), time.Date(2005, 5, 12, 0, 0, 0, 0, time.UTC), 0},
}
func TestAgeAt(t *testing.T) {
for _, candidate := range AgeTestCandidates {
gotAge := AgeAt(candidate.BirthDate, candidate.CheckingTime)
if gotAge != candidate.ExpectedAge {
t.Error(
"For", candidate.BirthDate,
"Expected", candidate.ExpectedAge,
"Got", gotAge,
)
}
}
}
|
Add explicit visibility for method getOrder
Add explicit visibility following PSR-2
|
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\Common\DataFixtures;
/**
* Ordered Fixture interface needs to be implemented
* by fixtures, which needs to have a specific order
* when being loaded by directory scan for example
*
* @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
interface OrderedFixtureInterface
{
/**
* Get the order of this fixture
*
* @return integer
*/
public function getOrder();
}
|
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\Common\DataFixtures;
/**
* Ordered Fixture interface needs to be implemented
* by fixtures, which needs to have a specific order
* when being loaded by directory scan for example
*
* @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
interface OrderedFixtureInterface
{
/**
* Get the order of this fixture
*
* @return integer
*/
function getOrder();
}
|
Use relative href on 503 font path
|
<html>
<head>
<link href='//fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'>
<style>
body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
color: #B0BEC5;
display: table;
font-weight: 100;
font-family: 'Lato';
}
.container {
text-align: center;
display: table-cell;
vertical-align: middle;
}
.content {
text-align: center;
display: inline-block;
}
.title {
font-size: 72px;
margin-bottom: 40px;
}
</style>
</head>
<body>
<div class="container">
<div class="content">
<div class="title">Be right back.</div>
</div>
</div>
</body>
</html>
|
<html>
<head>
<link href='http://fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'>
<style>
body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
color: #B0BEC5;
display: table;
font-weight: 100;
font-family: 'Lato';
}
.container {
text-align: center;
display: table-cell;
vertical-align: middle;
}
.content {
text-align: center;
display: inline-block;
}
.title {
font-size: 72px;
margin-bottom: 40px;
}
</style>
</head>
<body>
<div class="container">
<div class="content">
<div class="title">Be right back.</div>
</div>
</div>
</body>
</html>
|
Fix ./activator dist for the scaladoc
|
package controllers;
import play.mvc.Controller;
import services.configuration.ConfigurationService;
import utils.json.JsonHelper;
import com.google.inject.Singleton;
@Singleton
public class AbstractController extends Controller {
protected static final String _TITLE = "Reactive AngularApp's - Elasticsearch 1.4.1";
protected final ConfigurationService configurationService;
protected final String hostName;
protected AbstractController(ConfigurationService configurationService) {
this.configurationService = configurationService;
this.hostName = configurationService.getHostName();
}
protected static Status _internalServerError(String key) {
return internalServerError(
JsonHelper.toResultExceptionModel(key));
}
protected static Status _preconditionFailed(String key) {
return status(PRECONDITION_FAILED,
JsonHelper.toResultExceptionModel(key));
}
protected void clearSession() {
session().clear();
}
protected void flashSuccess(String message) {
flash("success", message);
}
}
|
package controllers;
import play.mvc.Controller;
import services.configuration.ConfigurationService;
import utils.json.JsonHelper;
import com.google.inject.Singleton;
@Singleton
public class AbstractController extends Controller {
protected static final String _TITLE = "Reactive AngularApp's - Elasticsearch 1.4.1";
protected final ConfigurationService configurationService;
protected final String hostName;
protected AbstractController(ConfigurationService configurationService) {
this.configurationService = configurationService;
this.hostName = configurationService.getHostName();
}
protected Status _internalServerError(String key) {
return internalServerError(
JsonHelper.toResultExceptionModel(key));
}
protected Status _preconditionFailed(String key) {
return status(PRECONDITION_FAILED,
JsonHelper.toResultExceptionModel(key));
}
protected void clearSession() {
session().clear();
}
protected void flashSuccess(String message) {
flash("success", message);
}
}
|
Allow app.json without templateType key
The v2 app.json should not have a templateType key in it. MeshInteraction
does require that it is constructed with that key, at least until we
refactor it, so pass a blank string when the app.json does not contain
a templateType key.
https://phabricator.endlessm.com/T11064
|
const EvinceDocument = imports.gi.EvinceDocument;
const Gio = imports.gi.Gio;
const ModuleFactory = imports.app.moduleFactory;
const Utils = imports.app.utils;
let create_interaction = function (application, resource_path) {
// Initialize libraries
EvinceDocument.init();
let app_resource = Gio.Resource.load(resource_path);
app_resource._register();
let appname = app_resource.enumerate_children('/com/endlessm', Gio.FileQueryInfoFlags.NONE, null)[0];
let resource_file = Gio.File.new_for_uri('resource:///com/endlessm/' + appname);
let app_json_file = resource_file.get_child('app.json');
let app_json = Utils.parse_object_from_file(app_json_file);
let overrides_css_file = resource_file.get_child('overrides.css');
let factory = new ModuleFactory.ModuleFactory({
app_json: app_json,
});
let css = '';
if (overrides_css_file.query_exists(null)) {
let [success, data] = overrides_css_file.load_contents(null);
css = data.toString();
}
application.image_attribution_file = resource_file.get_child('credits.json');
return factory.create_named_module('interaction', {
// v2 app.jsons have no templateType key
template_type: app_json['templateType'] || '',
css: css,
application: application,
});
};
|
const EvinceDocument = imports.gi.EvinceDocument;
const Gio = imports.gi.Gio;
const ModuleFactory = imports.app.moduleFactory;
const Utils = imports.app.utils;
let create_interaction = function (application, resource_path) {
// Initialize libraries
EvinceDocument.init();
let app_resource = Gio.Resource.load(resource_path);
app_resource._register();
let appname = app_resource.enumerate_children('/com/endlessm', Gio.FileQueryInfoFlags.NONE, null)[0];
let resource_file = Gio.File.new_for_uri('resource:///com/endlessm/' + appname);
let app_json_file = resource_file.get_child('app.json');
let app_json = Utils.parse_object_from_file(app_json_file);
let overrides_css_file = resource_file.get_child('overrides.css');
let factory = new ModuleFactory.ModuleFactory({
app_json: app_json,
});
let css = '';
if (overrides_css_file.query_exists(null)) {
let [success, data] = overrides_css_file.load_contents(null);
css = data.toString();
}
application.image_attribution_file = resource_file.get_child('credits.json');
return factory.create_named_module('interaction', {
template_type: app_json['templateType'],
css: css,
application: application,
});
};
|
Introduce cache clear logic through GoogleDrive webhook endpoint.
|
# -*- encoding:utf8 -*-
import httplib2
from flask import Blueprint, redirect, request, Response, abort
from model.cache import Cache
from model.oauth import OAuth
from model.utils import Utils
drive = Blueprint('drive', __name__, url_prefix='/drive')
@drive.route("/auth", methods=['GET'])
def hookauth():
flow = OAuth().get_flow()
if not flow:
abort(500)
auth_uri = flow.step1_get_authorize_url()
return redirect(auth_uri)
@drive.route("/callback", methods=['GET'])
def callback():
try:
code = request.args['code']
except:
abort(400)
flow = OAuth().get_flow()
credentials = flow.step2_exchange(code)
http = httplib2.Http()
credentials.authorize(http)
dic = {"response": "success"}
return Response(Utils().dump_json(dic), mimetype='application/json')
@drive.route("/webhook", methods=['POST'])
def webhook():
document_id = request.json.get('id')
if not document_id:
abort(400)
return
Cache().clear(document_id)
dic = {"response": "success", "document_id": document_id}
return Response(Utils().dump_json(dic), mimetype='application/json')
|
# -*- encoding:utf8 -*-
import httplib2
from flask import Blueprint, redirect, request, Response, abort
from model.oauth import OAuth
from model.utils import Utils
drive = Blueprint('drive', __name__, url_prefix='/drive')
@drive.route("/auth", methods=['GET'])
def hookauth():
flow = OAuth().get_flow()
if not flow:
abort(500)
auth_uri = flow.step1_get_authorize_url()
return redirect(auth_uri)
@drive.route("/callback", methods=['GET'])
def callback():
try:
code = request.args['code']
except:
abort(400)
flow = OAuth().get_flow()
credentials = flow.step2_exchange(code)
http = httplib2.Http()
credentials.authorize(http)
dic = {"response": "success"}
return Response(Utils().dump_json(dic), mimetype='application/json')
|
Fix test run failures with double-registration on ICEkitURLField
Use the new `ICEkitURLField.register_model_once` method available in
django-icekit to safely register base events for `ICEkitURLField`
without the risk that they will be re-registered (and therefore fail)
because of the way the unit tests reload this app.
|
"""
App configuration for ``icekit_events`` app.
"""
# Register signal handlers, but avoid interacting with the database.
# See: https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.AppConfig.ready
from django.apps import AppConfig
from django.utils.module_loading import autodiscover_modules
from any_urlfield.forms import SimpleRawIdWidget
from icekit.fields import ICEkitURLField
class AppConfig(AppConfig):
name = '_'.join(__name__.split('.')[:-1])
label = 'icekit_events'
verbose_name = "Events"
def ready(self):
# look through installed apps to see what event types are registered
autodiscover_modules('event_type_plugins')
from .models import EventBase
ICEkitURLField.register_model_once(
EventBase, widget=SimpleRawIdWidget(EventBase), title='Event')
|
"""
App configuration for ``icekit_events`` app.
"""
# Register signal handlers, but avoid interacting with the database.
# See: https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.AppConfig.ready
from django.apps import AppConfig
from django.utils.module_loading import autodiscover_modules
from any_urlfield.forms import SimpleRawIdWidget
from icekit.fields import ICEkitURLField
class AppConfig(AppConfig):
name = '_'.join(__name__.split('.')[:-1])
label = 'icekit_events'
verbose_name = "Events"
def ready(self):
# look through installed apps to see what event types are registered
autodiscover_modules('event_type_plugins')
from .models import EventBase
ICEkitURLField.register_model(
EventBase, widget=SimpleRawIdWidget(EventBase), title='Event')
|
Print end as "nothing" instead of "no any object"
|
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var common = require('./common.js');
var pexprs = require('./pexprs.js');
var awlib = require('awlib');
var printString = awlib.stringUtils.printString;
var makeStringBuffer = awlib.objectUtils.stringBuffer;
// --------------------------------------------------------------------
// Operations
// --------------------------------------------------------------------
pexprs.PExpr.prototype.toExpected = function(ruleDict) {
return undefined;
};
pexprs.anything.toExpected = function(ruleDict) {
return "any object";
};
pexprs.end.toExpected = function(ruleDict) {
return "end of input";
};
pexprs.Prim.prototype.toExpected = function(ruleDict) {
return printString(this.obj);
};
pexprs.Not.prototype.toExpected = function(ruleDict) {
if (this.expr === pexprs.anything) {
return "nothing";
} else {
return "no " + this.expr.toExpected();
}
};
// TODO: think about Listy and Obj
pexprs.Apply.prototype.toExpected = function(ruleDict) {
var description = ruleDict[this.ruleName].description;
if (description) {
return description;
} else {
var article = /^[aeiouAEIOU]/.test(this.ruleName) ? "an" : "a";
return article + " " + this.ruleName;
}
};
|
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var common = require('./common.js');
var pexprs = require('./pexprs.js');
var awlib = require('awlib');
var printString = awlib.stringUtils.printString;
var makeStringBuffer = awlib.objectUtils.stringBuffer;
// --------------------------------------------------------------------
// Operations
// --------------------------------------------------------------------
pexprs.PExpr.prototype.toExpected = function(ruleDict) {
return undefined;
};
pexprs.anything.toExpected = function(ruleDict) {
return "any object";
};
pexprs.end.toExpected = function(ruleDict) {
return "end of input";
};
pexprs.Prim.prototype.toExpected = function(ruleDict) {
return printString(this.obj);
};
pexprs.Not.prototype.toExpected = function(ruleDict) {
return "no " + this.expr.toExpected();
};
// TODO: think about Listy and Obj
pexprs.Apply.prototype.toExpected = function(ruleDict) {
var description = ruleDict[this.ruleName].description;
if (description) {
return description;
} else {
var article = /^[aeiouAEIOU]/.test(this.ruleName) ? "an" : "a";
return article + " " + this.ruleName;
}
};
|
Change to filters now that can-has prebaked
|
$(document).ready(function() {
function NavBarModel() {
var self = this;
self.filters = ko.observableArray();
};
var nbm = new NavBarModel();
ko.applyBindings(nbm);
/* TODO: Figure out how to stuff filters into a
computed observable so this function gets called
on filter updates. Possibly using HTTP long-polling
*/
$.getJSON('/api/filters/', function(data) {
nbm.filters(data.filters);
// Activate first navbar item
$('.navbar * ul.nav li').first().addClass('active');
});
// Activate first nav-list item
$('ul.nav-list li a').parent().first().addClass('active');
});
|
$(document).ready(function() {
function NavBarModel() {
var self = this;
self.filters = ko.observableArray();
};
var nbm = new NavBarModel();
ko.applyBindings(nbm);
/* TODO: Figure out how to stuff filters into a
computed observable so this function gets called
on filter updates. Possibly using HTTP long-polling
*/
// FIXME: Add some filters, change this to /filters/, .filters
$.getJSON('/api/clusters/', function(data) {
nbm.filters(data.clusters);
// Activate first navbar item
$('.navbar * ul.nav li').first().addClass('active');
});
// Activate first nav-list item
$('ul.nav-list li a').parent().first().addClass('active');
});
|
Fix wrong import from UploadHandler
|
import os
from src.data.Track import UploadHandler
from src.data.Track.Tracks import YoutubeTrack
class YoutubeUploadHandler(UploadHandler):
def __init__(self, workingDir):
super().__init__(workingDir)
self.attributes.update({
"URL": ["string", "required", "url"]
})
def trackFromUploadedAttributes(self, attributes):
track = YoutubeTrack(
attributes["Artist"],
attributes["Album"],
attributes["Title"]
)
del attributes["Artist"]
del attributes["Album"]
del attributes["Title"]
super().autoImportAttributes(track, attributes)
super().writeTrackRecord(track)
artistPath = os.path.join(self.workingDir, track.artistName)
albumPath = os.path.join(artistPath, track.albumTitle)
recordPath = os.path.join(albumPath, track.title) + ".rec"
localFilePath = os.path.join(recordPath, "muzak.yturl")
fileToWrite = open(localFilePath, 'w+')
fileToWrite.write(track.url)
fileToWrite.close()
return track
|
import os
from data.Track.UploadHandler import UploadHandler
from src.data.Track.Tracks import YoutubeTrack
class YoutubeUploadHandler(UploadHandler):
def __init__(self, workingDir):
super().__init__(workingDir)
self.attributes.update({
"URL": ["string", "required", "url"]
})
def trackFromUploadedAttributes(self, attributes):
track = YoutubeTrack(
attributes["Artist"],
attributes["Album"],
attributes["Title"]
)
del attributes["Artist"]
del attributes["Album"]
del attributes["Title"]
super().autoImportAttributes(track, attributes)
super().writeTrackRecord(track)
artistPath = os.path.join(self.workingDir, track.artistName)
albumPath = os.path.join(artistPath, track.albumTitle)
recordPath = os.path.join(albumPath, track.title) + ".rec"
localFilePath = os.path.join(recordPath, "muzak.yturl")
fileToWrite = open(localFilePath, 'w+')
fileToWrite.write(track.url)
fileToWrite.close()
return track
|
[Bitbay] Use compact JSON instead of replacing whitespaces in String
|
package org.knowm.xchange.bitbay.v3.service;
import java.io.IOException;
import java.util.UUID;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.bitbay.v3.dto.trade.BitbayUserTrades;
import org.knowm.xchange.bitbay.v3.dto.trade.BitbayUserTradesQuery;
import org.knowm.xchange.exceptions.ExchangeException;
import org.knowm.xchange.utils.ObjectMapperHelper;
/** @author walec51 */
public class BitbayTradeServiceRaw extends BitbayBaseService {
BitbayTradeServiceRaw(Exchange exchange) {
super(exchange);
}
public BitbayUserTrades getBitbayTransactions(BitbayUserTradesQuery query)
throws IOException, ExchangeException {
final String jsonQuery = ObjectMapperHelper.toCompactJSON(query);
final BitbayUserTrades response =
bitbayAuthenticated.getTransactionHistory(
apiKey, sign, exchange.getNonceFactory(), UUID.randomUUID(), jsonQuery);
checkError(response);
return response;
}
}
|
package org.knowm.xchange.bitbay.v3.service;
import java.io.IOException;
import java.util.UUID;
import java.util.regex.Pattern;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.bitbay.v3.dto.trade.BitbayUserTrades;
import org.knowm.xchange.bitbay.v3.dto.trade.BitbayUserTradesQuery;
import org.knowm.xchange.exceptions.ExchangeException;
import org.knowm.xchange.utils.ObjectMapperHelper;
/** @author walec51 */
public class BitbayTradeServiceRaw extends BitbayBaseService {
private static final Pattern WHITESPACES = Pattern.compile("\\s\\s");
BitbayTradeServiceRaw(Exchange exchange) {
super(exchange);
}
public BitbayUserTrades getBitbayTransactions(BitbayUserTradesQuery query)
throws IOException, ExchangeException {
String jsonQuery = ObjectMapperHelper.toJSON(query);
jsonQuery = WHITESPACES.matcher(jsonQuery).replaceAll("");
BitbayUserTrades response =
bitbayAuthenticated.getTransactionHistory(
apiKey, sign, exchange.getNonceFactory(), UUID.randomUUID(), jsonQuery);
checkError(response);
return response;
}
}
|
Use UTF-8 as default encoding.
|
# -*- coding: utf-8 -*-
# Copyright (c) 2013-2015, Sebastian Linke
# Released under the Simplified BSD license
# (see LICENSE file for details).
"""
Constants that are used by `shcol` in many places. This is meant to modified (if
needed) only *before* running `shcol`, since most of these constants are only
read during initialization of the `shcol`-package.
"""
import logging
import os
import sys
ENCODING = 'utf-8'
ERROR_STREAM = sys.stderr
INPUT_STREAM = sys.stdin
LINE_WIDTH = None
LINESEP = '\n'
LOGGER = logging.getLogger('shol')
MAKE_UNIQUE = False
ON_WINDOWS = 'windows' in os.getenv('os', '').lower()
PY_VERSION = sys.version_info[:2]
SORT_ITEMS = False
SPACING = 2
STARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else ''))
TERMINAL_STREAM = sys.stdout
UNICODE_TYPE = type(u'')
|
# -*- coding: utf-8 -*-
# Copyright (c) 2013-2015, Sebastian Linke
# Released under the Simplified BSD license
# (see LICENSE file for details).
"""
Constants that are used by `shcol` in many places. This is meant to modified (if
needed) only *before* running `shcol`, since most of these constants are only
read during initialization of the `shcol`-package.
"""
from __future__ import unicode_literals
import logging
import os
import sys
ERROR_STREAM = sys.stderr
INPUT_STREAM = sys.stdin
LINE_WIDTH = None
LINESEP = '\n'
LOGGER = logging.getLogger('shol')
MAKE_UNIQUE = False
ON_WINDOWS = 'windows' in os.getenv('os', '').lower()
PY_VERSION = sys.version_info[:2]
SORT_ITEMS = False
SPACING = 2
STARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else ''))
TERMINAL_STREAM = sys.stdout
if PY_VERSION >= (3, 0):
ENCODING = sys.getdefaultencoding()
UNICODE_TYPE = type('')
else:
ENCODING = TERMINAL_STREAM.encoding or sys.getdefaultencoding()
UNICODE_TYPE = type(u'')
|
Stop the socket from warning (for now)
It was constantly giving an "Ignoring unmatched topic "authorized:lobby"
warning to the console.
|
/* This javascript was taken from the PhoenixGuardian Project */
/*
import {Socket} from "deps/phoenix/web/static/js/phoenix";
const authSocket = new Socket("/socket");
authSocket.connect();
const token = $('meta[name="guardian_token"]').attr('content');
const channel = authSocket.channel("authorized:lobby", {guardian_token: token});
channel.join()
.receive("ok", resp => {
socketTalk(resp.message)
})
.receive("error", resp => {
socketTalk(resp.error)
});
channel.on("shout", data => { socketTalk(data.body, data.from); });
const socketTalk = (message, from) => {
var out = '<li>'
if (from) {
out += `<span class='chat-from'>${from}: </span>`
}
out += message
out += '</li>'
$('#socket-talk').append(out);
}
const sendMessage = (e) => {
e.preventDefault();
let message = e.target.message.value;
e.target.message.value = "";
channel.push("shout", {body: message});
}
export default sendMessage;
*/
|
/* This javascript was taken from the PhoenixGuardian Project */
import {Socket} from "deps/phoenix/web/static/js/phoenix";
const authSocket = new Socket("/socket");
authSocket.connect();
const token = $('meta[name="guardian_token"]').attr('content');
const channel = authSocket.channel("authorized:lobby", {guardian_token: token});
channel.join()
.receive("ok", resp => {
socketTalk(resp.message)
})
.receive("error", resp => {
socketTalk(resp.error)
});
channel.on("shout", data => { socketTalk(data.body, data.from); });
const socketTalk = (message, from) => {
var out = '<li>'
if (from) {
out += `<span class='chat-from'>${from}: </span>`
}
out += message
out += '</li>'
$('#socket-talk').append(out);
}
const sendMessage = (e) => {
e.preventDefault();
let message = e.target.message.value;
e.target.message.value = "";
channel.push("shout", {body: message});
}
export default sendMessage;
|
Make sure we pass in the segments if this is not instanceof Message
|
var _ = require('underscore')
, utils = require('./utils')
module.exports = Message
function Message(segments) {
if (!(this instanceof Message))
return new Message(segments)
if (segments && Array.isArray(segments)) {
this.segments = segments
this.segmentTypes = _.unique(
_.pluck(this.segments, 'SegmentType')
)
} else {
this.segments = []
this.segmentTypes = []
}
}
Message.prototype.addSegment = function(segment) {
this.segments.push(segment)
var t = segment.SegmentType
if (!(~this.segmentTypes.indexOf(t))) {
this.segmentTypes.push(t)
}
if (utils.segmentTypeIsHeader(t)) {
this.header = segment
}
}
Message.prototype.getHeader = function() {
return this.header
}
Message.prototype.getDelims = function() {
if (!this.header) return {
segment: '\r',
field: '|',
component: '^',
subcomponent: '&',
repetition: '~',
escape: '\\'
}
var chars = this.header.EncodingCharacters
return {
segment: '\r',
field: chars[0],
component: chars[1],
subcomponent: chars[2],
repetition: chars[3],
escape: chars[4]
}
}
|
var _ = require('underscore')
, utils = require('./utils')
module.exports = Message
function Message(segments) {
if (!(this instanceof Message))
return new Message()
if (segments && Array.isArray(segments)) {
this.segments = segments
this.segmentTypes = _.unique(
_.pluck(this.segments, 'SegmentType')
)
} else {
this.segments = []
this.segmentTypes = []
}
}
Message.prototype.addSegment = function(segment) {
this.segments.push(segment)
var t = segment.SegmentType
if (!(~this.segmentTypes.indexOf(t))) {
this.segmentTypes.push(t)
}
if (utils.segmentTypeIsHeader(t)) {
this.header = segment
}
}
Message.prototype.getHeader = function() {
return this.header
}
Message.prototype.getDelims = function() {
if (!this.header) return {
segment: '\r',
field: '|',
component: '^',
subcomponent: '&',
repetition: '~',
escape: '\\'
}
var chars = this.header.EncodingCharacters
return {
segment: '\r',
field: chars[0],
component: chars[1],
subcomponent: chars[2],
repetition: chars[3],
escape: chars[4]
}
}
|
Change letter from capitalize to lowercase
|
<?php
/*
* BlueCloud PHP MVC
* Bluecloud is a simple PHP MVC app made using PHP
* MIT Licensed Project
* Copyright (c) 2017 Kel Novi
* github.com/novhex
*/
use Router\Router;
use Routes\Routes;
class Bootstrap {
public function __construct(){
self::loadControllers();
self::loadGenericFunctions();
self::loadHTMLPurifier();
}
private static function loadControllers(){
foreach(glob(ROOT_DIR.'controllers/*.php') as $controllers){
require_once $controllers;
}
}
private static function loadGenericFunctions(){
foreach(glob(ROOT_DIR.'generic_functions/*.php') as $gen_func){
require_once $gen_func;
}
}
private static function loadHTMLPurifier(){
require_once ROOT_DIR.'core/HTMLpurifier/HTMLPurifier.auto.php';
}
public static function runApp(){
$url = '';
$method ='';
$callback ='';
foreach(Routes::routeList() as $route_rules):
$method = explode('|',$route_rules)[0];
$url = explode('|', $route_rules)[1];
$callback = explode('|', $route_rules)[2];
if($method === "GET"){
Router::get($url,$callback);
}else if($method === "POST"){
Router::post($url,$callback);
}
endforeach;
Router::dispatch();
}
}
|
<?php
/*
* BlueCloud PHP MVC
* Bluecloud is a simple PHP MVC app made using PHP
* MIT Licensed Project
* Copyright (c) 2017 Kel Novi
* github.com/novhex
*/
use Router\Router;
use Routes\Routes;
class Bootstrap {
public function __construct(){
self::loadControllers();
self::loadGenericFunctions();
self::loadHTMLPurifier();
}
private static function loadControllers(){
foreach(glob(ROOT_DIR.'controllers/*.php') as $controllers){
require_once $controllers;
}
}
private static function loadGenericFunctions(){
foreach(glob(ROOT_DIR.'generic_functions/*.php') as $gen_func){
require_once $gen_func;
}
}
private static function loadHTMLPurifier(){
require_once ROOT_DIR.'core/HTMLPurifier/HTMLPurifier.auto.php';
}
public static function runApp(){
$url = '';
$method ='';
$callback ='';
foreach(Routes::routeList() as $route_rules):
$method = explode('|',$route_rules)[0];
$url = explode('|', $route_rules)[1];
$callback = explode('|', $route_rules)[2];
if($method === "GET"){
Router::get($url,$callback);
}else if($method === "POST"){
Router::post($url,$callback);
}
endforeach;
Router::dispatch();
}
}
|
Change of variables of Estatisitca
|
package br.com.MDSGPP.ChamadaParlamentar.model;
import java.util.ArrayList;
public class Estatistica {
private String name;
private String numberOfSession;
private String totalSessao;
private String percentage;
private ArrayList<String> lista = new ArrayList<String>();
public Estatistica(){
}
public String getNumeroSessao() {
return numberOfSession;
}
public void setNumeroSessao(String numberOfSession) {
this.numberOfSession = numberOfSession;
}
public String getTotalSessao() {
return totalSessao;
}
public void setTotalSessao(String totalSessao) {
this.totalSessao = totalSessao;
}
public String getNome() {
return name;
}
public void setNome(String name) {
this.name = name;
}
public String getPorcentagem() {
return percentage;
}
public void setPorcentagem(String percentage) {
this.percentage = percentage;
}
public ArrayList<String> getLista() {
return list;
}
public void setLista(ArrayList<String> list) {
this.list = list;
}
}
|
package br.com.MDSGPP.ChamadaParlamentar.model;
import java.util.ArrayList;
public class Estatistica {
private String nome;
private String numeroSessao;
private String totalSessao;
private String porcentagem;
private ArrayList<String> lista = new ArrayList<String>();
public Estatistica(){
}
public String getNumeroSessao() {
return numeroSessao;
}
public void setNumeroSessao(String numeroSessao) {
this.numeroSessao = numeroSessao;
}
public String getTotalSessao() {
return totalSessao;
}
public void setTotalSessao(String totalSessao) {
this.totalSessao = totalSessao;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getPorcentagem() {
return porcentagem;
}
public void setPorcentagem(String porcentagem) {
this.porcentagem = porcentagem;
}
public ArrayList<String> getLista() {
return lista;
}
public void setLista(ArrayList<String> lista) {
this.lista = lista;
}
}
|
Correct the class name.
[ci skip]
|
import Ember from 'ember';
/**
* @module ivy-tree
*/
/**
* @class IvyTreeGroupComponent
* @namespace IvyTree
* @extends Ember.Component
*/
export default Ember.Component.extend({
attributeBindings: ['aria-hidden', 'role'],
classNames: ['ivy-tree-group'],
tagName: 'ul',
init: function() {
this._super();
Ember.run.once(this, this._registerWithTreeItemContainer);
},
willDestroy: function() {
this._super();
Ember.run.once(this, this._unregisterWithTreeItemContainer);
},
'aria-hidden': Ember.computed(function() {
return (!this.get("treeItemContainer.isExpanded")) + ''; // coerce to 'true' or 'false'
}).property("treeItemContainer.isExpanded"),
role: 'group',
/**
* The `ivy-tree-item` component in which the group is defined.
*
* @property treeItemContainer
* @type IvyTree.IvyTreeItemComponent
* @readOnly
*/
treeItemContainer: Ember.computed.alias('parentView').readOnly(),
_registerWithTreeItemContainer: function() {
this.get('treeItemContainer').registerTreeGroup(this);
},
_unregisterWithTreeItemContainer: function() {
this.get('treeItemContainer').unregisterTreeGroup(this);
}
});
|
import Ember from 'ember';
/**
* @module ivy-tree
*/
/**
* @class IvyTreeComponent
* @namespace IvyTree
* @extends Ember.Component
*/
export default Ember.Component.extend({
attributeBindings: ['aria-hidden', 'role'],
classNames: ['ivy-tree-group'],
tagName: 'ul',
init: function() {
this._super();
Ember.run.once(this, this._registerWithTreeItemContainer);
},
willDestroy: function() {
this._super();
Ember.run.once(this, this._unregisterWithTreeItemContainer);
},
'aria-hidden': Ember.computed(function() {
return (!this.get("treeItemContainer.isExpanded")) + ''; // coerce to 'true' or 'false'
}).property("treeItemContainer.isExpanded"),
role: 'group',
/**
* The `ivy-tree-item` component in which the group is defined.
*
* @property treeItemContainer
* @type IvyTree.IvyTreeItemComponent
* @readOnly
*/
treeItemContainer: Ember.computed.alias('parentView').readOnly(),
_registerWithTreeItemContainer: function() {
this.get('treeItemContainer').registerTreeGroup(this);
},
_unregisterWithTreeItemContainer: function() {
this.get('treeItemContainer').unregisterTreeGroup(this);
}
});
|
Fix method name to conform to tests
|
class CheckBrackets:
OPENERS = {'{': '}',
'[': ']',
'(': ')'}
CLOSERS = set(OPENERS.values())
def __init__(self, inp):
self.check_brackets = self.build_stack(inp)
def build_stack(self, inp):
stack = []
for char in list(inp):
if char in self.OPENERS:
stack.append(char)
elif (char in self.CLOSERS and stack and
self.corresponding_brackets(stack[-1], char)):
stack.pop()
else:
return False
return not bool(stack)
@classmethod
def corresponding_brackets(cls, opener, closer):
return cls.OPENERS[opener] == closer
def is_paired(inp):
return CheckBrackets(inp).check_brackets
|
class CheckBrackets:
OPENERS = {'{': '}',
'[': ']',
'(': ')'}
CLOSERS = set(OPENERS.values())
def __init__(self, inp):
self.check_brackets = self.build_stack(inp)
def build_stack(self, inp):
stack = []
for char in list(inp):
if char in self.OPENERS:
stack.append(char)
elif (char in self.CLOSERS and stack and
self.corresponding_brackets(stack[-1], char)):
stack.pop()
else:
return False
return not bool(stack)
@classmethod
def corresponding_brackets(cls, opener, closer):
return cls.OPENERS[opener] == closer
def check_brackets(inp):
return CheckBrackets(inp).check_brackets
|
:new: Set tabindex on panel messages to allow text selection
|
'use babel'
/* @flow */
/** @jsx React.h */
import { CompositeDisposable } from 'atom'
import React from 'preact'
import Message from './message'
import { sortMessages } from '../helpers'
import type { Linter$Message } from '../types'
type Messages$State = { messages: Array<Linter$Message>, showProviderName: boolean }
export default class Messages extends React.Component {
state: Messages$State;
subscriptions: CompositeDisposable;
getInitialState(): Messages$State {
this.subscriptions = new CompositeDisposable()
this.subscriptions.add(atom.config.onDidChange('linter-ui-default.showProviderName', ({ newValue }) => {
this.setState({ showProviderName: newValue })
}))
return {
messages: [],
showProviderName: atom.config.get('linter-ui-default.showProviderName')
}
}
componentDidMount() {
const { panel } = this.props
this.subscriptions.add(panel.observeMessages(messages => {
this.setState({ messages })
}))
}
componentWillUnmount() {
this.subscriptions.dispose()
}
render() {
const messageStyle = {
maxHeight: '95px'
}
return (<linter-panel-messages style={messageStyle} tabindex="-1">
{ sortMessages(this.state.messages).map(message =>
<Message message={message} key={message.key} includeLink={true} includeProvider={this.state.showProviderName} />
) }
</linter-panel-messages>)
}
}
|
'use babel'
/* @flow */
/** @jsx React.h */
import { CompositeDisposable } from 'atom'
import React from 'preact'
import Message from './message'
import { sortMessages } from '../helpers'
import type { Linter$Message } from '../types'
type Messages$State = { messages: Array<Linter$Message>, showProviderName: boolean }
export default class Messages extends React.Component {
state: Messages$State;
subscriptions: CompositeDisposable;
getInitialState(): Messages$State {
this.subscriptions = new CompositeDisposable()
this.subscriptions.add(atom.config.onDidChange('linter-ui-default.showProviderName', ({ newValue }) => {
this.setState({ showProviderName: newValue })
}))
return {
messages: [],
showProviderName: atom.config.get('linter-ui-default.showProviderName')
}
}
componentDidMount() {
const { panel } = this.props
this.subscriptions.add(panel.observeMessages(messages => {
this.setState({ messages })
}))
}
componentWillUnmount() {
this.subscriptions.dispose()
}
render() {
const messageStyle = {
maxHeight: '95px'
}
return (<linter-panel-messages style={messageStyle}>
{ sortMessages(this.state.messages).map(message =>
<Message message={message} key={message.key} includeLink={true} includeProvider={this.state.showProviderName} />
) }
</linter-panel-messages>)
}
}
|
Fix not execution flash object
In Chrome 60 -, removed the final exception for PPS(Plugin Power Saver).
Ref: https://www.chromium.org/flash-roadmap (PPS Tiny - No Same
Origin Exceptions (Target: Chrome 60 - Aug 2017))
|
import swfobject from 'swfobject';
const TIMEOUT = 1000;
const ID = '__flash_detector';
const CALLBACK = `${ID}_call`;
function clear(el) {
document.body.removeChild(el);
delete window[CALLBACK];
}
/**
* Detects if Adobe Flash is actually alive in a browser
* @param {string} swfPath - The path to FlashDetector.swf
* @param {number} [timeout=TIMEOUT(1000)] The milliseconds of your detection timeout
* @returns {Promise} Returns a Promise object which is resolved only when Flash plugin is alive
*/
export function detectFlash(swfPath, timeout = TIMEOUT) {
return new Promise((resolve, reject) => {
if (!navigator.plugins['Shockwave Flash']) {
reject();
return;
}
const el = document.createElement('DIV');
const wrapper = el.cloneNode();
el.id = ID;
wrapper.appendChild(el);
document.body.appendChild(wrapper);
const timeoutId = setTimeout(() => {
clear(wrapper, el.id);
reject();
}, timeout);
window[CALLBACK] = function callbackFromFlashDetector() {
clearTimeout(timeoutId);
setTimeout(() => clear(wrapper), 0);
resolve();
};
swfobject.embedSWF(swfPath, el.id, '10', '10', '10.0.0');
});
}
export default detectFlash;
|
import swfobject from 'swfobject';
const TIMEOUT = 1000;
const ID = '__flash_detector';
const CALLBACK = `${ID}_call`;
function clear(el) {
document.body.removeChild(el);
delete window[CALLBACK];
}
/**
* Detects if Adobe Flash is actually alive in a browser
* @param {string} swfPath - The path to FlashDetector.swf
* @param {number} [timeout=TIMEOUT(1000)] The milliseconds of your detection timeout
* @returns {Promise} Returns a Promise object which is resolved only when Flash plugin is alive
*/
export function detectFlash(swfPath, timeout = TIMEOUT) {
return new Promise((resolve, reject) => {
if (!navigator.plugins['Shockwave Flash']) {
reject();
return;
}
const el = document.createElement('DIV');
const wrapper = el.cloneNode();
el.id = ID;
wrapper.appendChild(el);
document.body.appendChild(wrapper);
const timeoutId = setTimeout(() => {
clear(wrapper, el.id);
reject();
}, timeout);
window[CALLBACK] = function callbackFromFlashDetector() {
clearTimeout(timeoutId);
setTimeout(() => clear(wrapper), 0);
resolve();
};
swfobject.embedSWF(swfPath, el.id, '0', '0', '10.0.0');
});
}
export default detectFlash;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.