text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Remove commented out dev server
|
const webpack = require('webpack'),
webpackMerge = require('webpack-merge'),
ExtractTextPlugin = require('extract-text-webpack-plugin'),
commonConfig = require('./webpack.common.js'),
path = require('path'),
rootDir = path.resolve(__dirname, '..');
const env = process.env.NODE_ENV;
module.exports = webpackMerge(commonConfig, {
devtool: 'source-map',
output: {
path: path.resolve(rootDir, 'src/devDist'),
sourceMapFilename: '[name].map',
publicPath: '/devDist/',
filename: '[name].js',
chunkFilename: '[id].chunk.js'
},
module: {
loaders: [
{
test: /\.ts$/,
exclude: /node_modules/,
loaders: ['awesome-typescript-loader', 'angular-router-loader', 'angular2-template-loader']
}]
}
});
|
const webpack = require('webpack'),
webpackMerge = require('webpack-merge'),
ExtractTextPlugin = require('extract-text-webpack-plugin'),
commonConfig = require('./webpack.common.js'),
path = require('path'),
rootDir = path.resolve(__dirname, '..');
const env = process.env.NODE_ENV;
module.exports = webpackMerge(commonConfig, {
devtool: 'source-map',
output: {
path: path.resolve(rootDir, 'src/devDist'),
sourceMapFilename: '[name].map',
publicPath: '/devDist/',
filename: '[name].js',
chunkFilename: '[id].chunk.js'
},
module: {
loaders: [
{
test: /\.ts$/,
exclude: /node_modules/,
loaders: ['awesome-typescript-loader', 'angular-router-loader', 'angular2-template-loader']
}]
}
//Example of a dev server. Not needed in this app since it uses Node/Express for the server.
// devServer: {
// contentBase: './src',
// historyApiFallback: true,
// watchOptions: { aggregateTimeout: 300, poll: 1000 },
// quiet: true,
// stats: 'minimal'
// }
});
|
Use more sane global for a non-bundled environment
|
import rootImport from 'rollup-plugin-root-import'
import nodeResolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
import buble from 'rollup-plugin-buble'
import filesize from 'rollup-plugin-filesize'
module.exports = {
entry : 'index.js',
dest : 'mithril-bootstrap.js',
format : 'umd',
moduleId : 'mithril-bootstrap',
moduleName : 'mbs',
external : ['mithril'],
globals : { mithril : 'm' },
plugins : [
rootImport({ extensions: ['.js', '/index.js'] }),
nodeResolve({ jsnext: true, main: true, browser: true }),
commonjs(),
buble(),
filesize()
]
};
|
import rootImport from 'rollup-plugin-root-import'
import nodeResolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
import buble from 'rollup-plugin-buble'
import filesize from 'rollup-plugin-filesize'
module.exports = {
entry : 'index.js',
dest : 'mithril-bootstrap.js',
format : 'umd',
moduleId : 'mithril-bootstrap',
moduleName : 'mithril-bootstrap',
external : ['mithril'],
globals : { mithril : 'm' },
plugins : [
rootImport({ extensions: ['.js', '/index.js'] }),
nodeResolve({ jsnext: true, main: true, browser: true }),
commonjs(),
buble(),
filesize()
]
};
|
UPDATE - Took out admin pass
|
<?php
global $project;
$project = 'mysite';
global $databaseConfig;
$databaseConfig = array(
"type" => 'MySQLDatabase',
"server" => 'localhost',
"username" => 'root',
"password" => 'Redrooster8',
"database" => 'sitesprocket24',
"path" => '',
);
MySQLDatabase::set_connection_charset('utf8');
// This line set's the current theme. More themes can be
// downloaded from http://www.silverstripe.org/themes/
SSViewer::set_theme('sitesprocket');
// Set the site locale
i18n::set_locale('en_US');
// enable nested URLs for this site (e.g. page/sub-page/)
SiteTree::enable_nested_urls();
// Force WWW
//Director::forceWWW();
// Force environment to Dev
Director::set_environment_type('dev');
// Temporary fix for Cookie Issue
Cookie::set_report_errors(false);
// Set default Login
//Security::setDefaultAdmin('admin','pass');
|
<?php
global $project;
$project = 'mysite';
global $databaseConfig;
$databaseConfig = array(
"type" => 'MySQLDatabase',
"server" => 'localhost',
"username" => 'root',
"password" => 'Redrooster8',
"database" => 'sitesprocket24',
"path" => '',
);
MySQLDatabase::set_connection_charset('utf8');
// This line set's the current theme. More themes can be
// downloaded from http://www.silverstripe.org/themes/
SSViewer::set_theme('sitesprocket');
// Set the site locale
i18n::set_locale('en_US');
// enable nested URLs for this site (e.g. page/sub-page/)
SiteTree::enable_nested_urls();
// Force WWW
//Director::forceWWW();
// Force environment to Dev
Director::set_environment_type('dev');
// Temporary fix for Cookie Issue
Cookie::set_report_errors(false);
// Set default Login
Security::setDefaultAdmin('admin','pass');
|
Exclude State component from the propTypes information table
|
import { configure, addDecorator } from '@storybook/react';
import { setDefaults } from '@storybook/addon-info';
import { setOptions } from '@storybook/addon-options';
import backgroundColor from 'react-storybook-decorator-background';
import { State } from '@sambego/storybook-state';
// addon-info
setDefaults({
header: true,
inline: true,
source: true,
propTablesExclude: [State],
});
setOptions({
name: `Version ${process.env.__VERSION__}`,
url: 'https://teamleader.design'
});
addDecorator(backgroundColor(['#ffffff', '#e6f2ff', '#ffeecc', '#d3f3f3', '#ffe3d9', '#e1edfa', '#f1f0ff', '#2a3b4d']));
const req = require.context('../stories', true, /\.js$/);
configure(() => {
req.keys().forEach(filename => req(filename));
}, module);
|
import { configure, addDecorator } from '@storybook/react';
import { setDefaults } from '@storybook/addon-info';
import { setOptions } from '@storybook/addon-options';
import backgroundColor from 'react-storybook-decorator-background';
// addon-info
setDefaults({
header: true,
inline: true,
source: true,
propTablesExclude: [],
});
setOptions({
name: `Version ${process.env.__VERSION__}`,
url: 'https://teamleader.design'
});
addDecorator(backgroundColor(['#ffffff', '#e6f2ff', '#ffeecc', '#d3f3f3', '#ffe3d9', '#e1edfa', '#f1f0ff', '#2a3b4d']));
const req = require.context('../stories', true, /\.js$/);
configure(() => {
req.keys().forEach(filename => req(filename));
}, module);
|
Fix after an API modification
|
<?php
$vca_page_title = _('Server Virtual Control Admin');
$paquet = new Paquet();
if(!empty($_GET['server'])) {
if(!empty($_POST['name'])) {
$para = array('name', 'address', 'key','description');
if(!empty($_POST['name'])) {
$para['name'] = $_POST['name'];
}
if(!empty($_POST['address'])) {
$para['address'] = $_POST['address'];
}
if(!empty($_POST['key'])) {
$para['key'] = $_POST['key'];
}
if(!empty($_POST['description'])) {
$para['description'] = $_POST['description'];
}
$paquet -> add_action('serverUpdate', array($_GET['server'], $para));
}
$paquet -> add_action('getServerInfo', array($_GET['server']));
}
else {
redirect();
}
$paquet -> send_actions();
$smarty->assign('serverInfo', $paquet->getAnswer('serverList')->list->$_GET['server']);
?>
|
<?php
$vca_page_title = _('Server Virtual Control Admin');
$paquet = new Paquet();
if(!empty($_GET['server'])) {
if(!empty($_POST['name'])) {
$para = array('name', 'address', 'key','description');
if(!empty($_POST['name'])) {
$para['name'] = $_POST['name'];
}
if(!empty($_POST['address'])) {
$para['address'] = $_POST['address'];
}
if(!empty($_POST['key'])) {
$para['key'] = $_POST['key'];
}
if(!empty($_POST['description'])) {
$para['description'] = $_POST['description'];
}
$paquet -> add_action('setServerInfo', array($_GET['server'], $para));
}
$paquet -> add_action('getServerInfo', array($_GET['server']));
}
else {
redirect();
}
$paquet -> send_actions();
$smarty->assign('serverInfo', $paquet->getAnswer('getServerInfo'));
?>
|
Add correct call of taxonomy node repo
|
<?php
namespace AppBundle\API\Listing;
use AppBundle\Entity\TaxonomyNode;
use AppBundle\Service\DBVersion;
use \PDO as PDO;
/**
* Web Service.
* Returns Taxonomy information for a given organism_id
*/
class Taxonomy
{
private $manager;
/**
* Taxonomy constructor.
* @param $dbversion
*/
public function __construct(DBVersion $dbversion)
{
$this->manager = $dbversion->getEntityManager();
}
/**
* @param $fennec_id
* @returns array of taxonomy information for a given organism id
* array('lineage' => [grandgrandparent, grandparent, parent])
*/
public function execute($fennec_id)
{
$result = array();
$taxonomy_databases = $this->manager->getRepository(TaxonomyNode::class)->getDatabases($fennec_id);
foreach($taxonomy_databases as $name => $taxonomy_node_id){
$result[$name] = $this->manager->getRepository(TaxonomyNode::class)->getLineage($taxonomy_node_id);
}
return $result;
}
}
|
<?php
namespace AppBundle\API\Listing;
use AppBundle\Entity\TaxonomyNode;
use AppBundle\Service\DBVersion;
use \PDO as PDO;
/**
* Web Service.
* Returns Taxonomy information for a given organism_id
*/
class Taxonomy
{
private $manager;
/**
* Taxonomy constructor.
* @param $dbversion
*/
public function __construct(DBVersion $dbversion)
{
$this->manager = $dbversion->getEntityManager();
}
/**
* @param $fennec_id
* @returns array of taxonomy information for a given organism id
* array('lineage' => [grandgrandparent, grandparent, parent])
*/
public function execute($fennec_id)
{
$result = array();
$taxonomy_databases = $this->manager->getRepository(TaxonomyNode::class)->getDatabases($fennec_id);
foreach($taxonomy_databases as $name => $taxonomy_node_id){
$result[$name] = $this->getLineage($taxonomy_node_id);
}
return $result;
}
}
|
Make sure menu code doesn't error out on 404
|
// Highlight active navigation menu item
(function() {
var fullPath = window.location.pathname.substring(1);
var parentPath = fullPath.split('/')[0];
var path = fullPath.replace(/\//g, '');
if (path) {
if (/404/.test(path) || /success/.test(path)) {
return;
}
// For blog post pages.
if (/blog/.test(path)) {
parentPath = parentPath +'/';
}
document.querySelector("[data-fx='main-nav'] a[href='/"+parentPath+"']").classList.add('active');
} else {
return;
}
})();
// Helper function to set bloglist classes to be used for backgrounds
(function() {
var pathname = window.location.pathname;
if (pathname === '/blog/') {
var pageNum = parseInt(pathname.split('/')[3], 10);
if (!pageNum) {
pageNum = 1;
}
if (pageNum <= 4) {
pageNum = pageNum;
}
if (pageNum > 4) {
if (pageNum % 4 === 0) {
pageNum = 4;
} else {
pageNum = pageNum % 4;
}
}
document.querySelector("[data-fx='blog-list']").classList.add('page' + pageNum);
}
})();
|
// Highlight active navigation menu item
(function() {
var fullPath = window.location.pathname.substring(1);
var parentPath = fullPath.split('/')[0];
var path = fullPath.replace(/\//g, '');
if (path) {
// For blog post pages.
if (/blog/.test(path)) {
parentPath = parentPath +'/';
}
document.querySelector("[data-fx='main-nav'] a[href='/"+parentPath+"']").classList.add('active');
} else {
return;
}
})();
// Helper function to set bloglist classes to be used for backgrounds
(function() {
var pathname = window.location.pathname;
if (/blog/.test(pathname)) {
var pageNum = parseInt(pathname.split('/')[3], 10);
if (!pageNum) {
pageNum = 1;
}
if (pageNum <= 4) {
pageNum = pageNum;
}
if (pageNum > 4) {
if (pageNum % 4 === 0) {
pageNum = 4;
} else {
pageNum = pageNum % 4;
}
}
document.querySelector("[data-fx='blog-list']").classList.add('page' + pageNum);
}
})();
|
Add addSelect function on query builder and start to make add function
|
let _where,
_select,
_from,
_orderBy,
_groupBy,
_limit,
_skip,
_join,
_insert,
_delete,
_update,
_command,
_table,
_option,
_params
module.exports = {
select: function (columns) {
if (Array.isArray(columns)) {
_select = `SELECT ${columns.join(', ')}`
} else if (columns.length > 0) {
_select = `SELECT ${columns}`
} else {
throw new Error('The columns is not available in correct format!')
}
_option = 'select'
return this
},
from: function (table) {
if (table.length > 0) {
_table = ` FROM ${table}`
} else {
throw new Error('The table variable is required to be string!')
}
return this
},
addSelect: function (columns) {
if (!_select) {
throw new Error('Please first use SELECT method before add new column on select method!')
} else if (Array.isArray(columns)) {
_select += ` ${columns.join(', ')}`
} else if (columns.length > 0) {
_select += ` ${columns}`
} else {
throw new Error('The columns is not available in correct format!')
}
return this
},
add: function (columns) {
return this
}
}
|
let _where,
_select,
_from,
_orderBy,
_groupBy,
_limit,
_skip,
_join,
_insert,
_delete,
_update,
_command,
_table,
_option,
_params
module.exports = {
select: function (columns) {
if (Array.isArray(columns)) {
_select = `SELECT ${columns.join(', ')}`
} else if (columns.length > 0) {
_select = `SELECT ${columns}`
} else {
throw new Error('The columns is not available in correct format!')
}
_option = 'select'
return this
},
from: function (table) {
if (table.length > 0) {
_table = ` FROM ${table}`
} else {
throw new Error('The table variable is required to be string!')
}
return this
},
addSelect: function (columns) {
}
}
|
Update to include actions in Create
|
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
# Provide actions for the new task
joke_actions = {
'actions': [
{'say': 'I was going to look for my missing watch, but I could never find the time.'}
]
}
# Create a new task named 'tell_a_joke'
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
task = client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks \
.create(
unique_name='tell-a-joke',
task_actions=joke_actions)
print(task.sid)
|
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
# Create a new task named 'tell_a_joke'
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
task = client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks \
.create(unique_name='tell-a-joke')
# Provide actions for the new task
joke_actions = {
'actions': [
{'say': 'I was going to look for my missing watch, but I could never find the time.'}
]
}
# Update the tell-a-joke task to use this 'say' action.
client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks(task.sid) \
.task_actions().update(joke_actions)
print(task.sid)
|
Add direct forward to admin
|
# Django
# Third-Party
from rest_framework.documentation import include_docs_urls
from rest_framework.schemas import get_schema_view
# from django.views.generic import TemplateView
# from api.views import variance, ann
from django.conf import settings
from django.conf.urls import (
include,
url,
)
from django.contrib import admin
from django.http import HttpResponse, HttpResponseRedirect
schema_view = get_schema_view(
title='Barberscore API',
)
urlpatterns = [
url(r'^$', lambda r: HttpResponseRedirect('admin/')),
url(r'^admin/', admin.site.urls),
# url(r'^variance/$', variance),
# url(r'^ann/$', ann),
url(r'^api/', include('api.urls')),
url(r'^api-auth/', include('rest_framework.urls')),
url(r'^schema/', schema_view),
url(r'^docs/', include_docs_urls(title='Foobar', description='foo to the bar')),
url(r'^robots.txt$', lambda r: HttpResponse("User-agent: *\nDisallow: /", content_type="text/plain")),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns += [
url(r'^__debug__/', include(debug_toolbar.urls)),
]
|
# Django
# Third-Party
from rest_framework.documentation import include_docs_urls
from rest_framework.schemas import get_schema_view
# from django.views.generic import TemplateView
# from api.views import variance, ann
from django.conf import settings
from django.conf.urls import (
include,
url,
)
from django.contrib import admin
from django.http import HttpResponse
schema_view = get_schema_view(
title='Barberscore API',
)
urlpatterns = [
url(r'^admin/', admin.site.urls),
# url(r'^variance/$', variance),
# url(r'^ann/$', ann),
url(r'^api/', include('api.urls')),
url(r'^api-auth/', include('rest_framework.urls')),
url(r'^schema/', schema_view),
url(r'^docs/', include_docs_urls(title='Foobar', description='foo to the bar')),
url(r'^robots.txt$', lambda r: HttpResponse("User-agent: *\nDisallow: /", content_type="text/plain")),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns += [
url(r'^__debug__/', include(debug_toolbar.urls)),
]
|
Fix minor bug in docs
|
package io.github.lionell.lab1;
import com.google.common.base.Joiner;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import io.github.lionell.lab1.io.WordReader;
/**
* Usage example: $ bazel run //java/io/github/lionell/lab1 --
* /home/lionell/dev/labs/volohov/res/in.txt
* /home/lionell/dev/labs/volohov/res/out.txt
*
* @author lionell
*/
public class Runner {
public static void main(String[] args) throws IOException {
WordReader reader = new WordReader(args[0]);
System.out.println(args[0]);
List<String> words = new ArrayList<>();
while (reader.hasNext()) {
words.add(reader.next());
}
reader.close();
// FrequencySorter.sort(words);
// System.out.println(Joiner.on(", ").join(words));
Set<Set<String>> sets = new CliquesFinder(words).findCliques();
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(args[1])));
for (Set<String> set : sets) {
writer.println("{" + Joiner.on(", ").join(set) + "}");
}
writer.close();
}
}
|
package io.github.lionell.lab1;
import com.google.common.base.Joiner;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import io.github.lionell.lab1.io.WordReader;
/**
* Usage example: $ bazel run //java/util/github/lionell/lab1 --
* /home/lionell/dev/labs/volohov/res/in.txt
* /home/lionell/dev/labs/volohov/res/out.txt
*
* @author lionell
*/
public class Runner {
public static void main(String[] args) throws IOException {
WordReader reader = new WordReader(args[0]);
System.out.println(args[0]);
List<String> words = new ArrayList<>();
while (reader.hasNext()) {
words.add(reader.next());
}
reader.close();
// FrequencySorter.sort(words);
// System.out.println(Joiner.on(", ").join(words));
Set<Set<String>> sets = new CliquesFinder(words).findCliques();
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(args[1])));
for (Set<String> set : sets) {
writer.println("{" + Joiner.on(", ").join(set) + "}");
}
writer.close();
}
}
|
Update image filter used by integration tests
Signed-off-by: Matthew Sykes <89c6e4c9c1046731a9c37abefc223a83de36a5d9@us.ibm.com>
|
/*
Copyright IBM Corp All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package helpers
import (
"encoding/base32"
"fmt"
"strings"
docker "github.com/fsouza/go-dockerclient"
"github.com/hyperledger/fabric/common/util"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
func AssertImagesExist(imageNames ...string) {
dockerClient, err := docker.NewClientFromEnv()
Expect(err).NotTo(HaveOccurred())
for _, imageName := range imageNames {
images, err := dockerClient.ListImages(docker.ListImagesOptions{
Filters: map[string][]string{"reference": {imageName}},
})
ExpectWithOffset(1, err).NotTo(HaveOccurred())
if len(images) != 1 {
Fail(fmt.Sprintf("missing required image: %s", imageName), 1)
}
}
}
// UniqueName generates base-32 enocded UUIDs for container names.
func UniqueName() string {
name := base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(util.GenerateBytesUUID())
return strings.ToLower(name)
}
|
/*
Copyright IBM Corp All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package helpers
import (
"encoding/base32"
"fmt"
"strings"
docker "github.com/fsouza/go-dockerclient"
"github.com/hyperledger/fabric/common/util"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
func AssertImagesExist(imageNames ...string) {
dockerClient, err := docker.NewClientFromEnv()
Expect(err).NotTo(HaveOccurred())
for _, imageName := range imageNames {
images, err := dockerClient.ListImages(docker.ListImagesOptions{
Filter: imageName,
})
ExpectWithOffset(1, err).NotTo(HaveOccurred())
if len(images) != 1 {
Fail(fmt.Sprintf("missing required image: %s", imageName), 1)
}
}
}
// UniqueName generates base-32 enocded UUIDs for container names.
func UniqueName() string {
name := base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(util.GenerateBytesUUID())
return strings.ToLower(name)
}
|
FIX: Remove brain example [skip azp] [skip actions]
|
"""
.. _ex-eeg-on-scalp:
=================================
Plotting EEG sensors on the scalp
=================================
In this example, digitized EEG sensor locations are shown on the scalp.
"""
# Author: Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD-3-Clause
# %%
import mne
from mne.viz import plot_alignment, set_3d_view
print(__doc__)
data_path = mne.datasets.sample.data_path()
subjects_dir = data_path + '/subjects'
trans = mne.read_trans(data_path + '/MEG/sample/sample_audvis_raw-trans.fif')
raw = mne.io.read_raw_fif(data_path + '/MEG/sample/sample_audvis_raw.fif')
# Plot electrode locations on scalp
fig = plot_alignment(raw.info, trans, subject='sample', dig=False,
eeg=['original', 'projected'], meg=[],
coord_frame='head', subjects_dir=subjects_dir)
# Set viewing angle
set_3d_view(figure=fig, azimuth=135, elevation=80)
|
"""
.. _ex-eeg-on-scalp:
=================================
Plotting EEG sensors on the scalp
=================================
In this example, digitized EEG sensor locations are shown on the scalp.
"""
# Author: Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD-3-Clause
# %%
import mne
from mne.viz import plot_alignment, set_3d_view
print(__doc__)
data_path = mne.datasets.sample.data_path()
subjects_dir = data_path + '/subjects'
trans = mne.read_trans(data_path + '/MEG/sample/sample_audvis_raw-trans.fif')
raw = mne.io.read_raw_fif(data_path + '/MEG/sample/sample_audvis_raw.fif')
# Plot electrode locations on scalp
fig = plot_alignment(raw.info, trans, subject='sample', dig=False,
eeg=['original', 'projected'], meg=[],
coord_frame='head', subjects_dir=subjects_dir)
# Set viewing angle
set_3d_view(figure=fig, azimuth=135, elevation=80)
# %%
# A similar effect can be achieved using :class:`mne.viz.Brain`:
brain = mne.viz.Brain(
'sample', 'both', 'pial', 'frontal', background='w',
subjects_dir=subjects_dir)
brain.add_head()
brain.add_sensors(raw.info, trans, meg=False, eeg=('original', 'projected'))
|
Change single job view model binding.
|
var app = app || {};
(function($) {
'use strict';
app.JobSingleView = app.JobAbstractView.extend({
template: _.template($('#job-template').html()),
events: {
'click .kill': 'killJob'
},
initialize: function() {
this.listenTo(this.model, 'change:status change:output', function() {
this.render();
window.scrollTo(0, document.body.scrollHeight);
});
},
render: function() {
var job = this.model;
job.set('statusColor', this.getStatusColor(job.get('status')));
this.$el.html(this.template(job.toJSON())).find('.timeago').timeago();
},
killJob: function() {
if (window.confirm("Kill this job?")) {
$.post('/job/' + this.model.id + '/kill');
}
},
close: function() {
this.unbind();
this.model.unbind('change:status change:output');
this.remove();
}
});
})(jQuery);
|
var app = app || {};
(function($) {
'use strict';
app.JobSingleView = app.JobAbstractView.extend({
template: _.template($('#job-template').html()),
events: {
'click .kill': 'killJob'
},
initialize: function() {
this.listenTo(this.model, 'change', this._modelChanged);
},
_modelChanged: function() {
this.render();
window.scrollTo(0, document.body.scrollHeight);
},
render: function() {
var job = this.model;
job.set('statusColor', this.getStatusColor(job.get('status')));
this.$el.html(this.template(job.toJSON())).find('.timeago').timeago();
},
killJob: function() {
if (window.confirm("Kill this job?")) {
$.post('/job/' + this.model.id + '/kill');
}
},
close: function() {
this.unbind();
this.model.unbind("change", this._modelChanged);
this.remove();
}
});
})(jQuery);
|
api/views: Move blueprint imports into register() function
|
from flask import request
from werkzeug.exceptions import Forbidden
from werkzeug.useragents import UserAgent
def register(app):
"""
:param flask.Flask app: a Flask app
"""
from .errors import register as register_error_handlers
from .airports import airports_blueprint
from .airspace import airspace_blueprint
from .mapitems import mapitems_blueprint
from .waves import waves_blueprint
@app.before_request
def require_user_agent():
"""
API requests require a ``User-Agent`` header
"""
user_agent = request.user_agent
assert isinstance(user_agent, UserAgent)
if not user_agent.string:
description = 'You don\'t have the permission to access the API with a User-Agent header.'
raise Forbidden(description)
register_error_handlers(app)
app.register_blueprint(airports_blueprint, url_prefix='/airports')
app.register_blueprint(airspace_blueprint, url_prefix='/airspace')
app.register_blueprint(mapitems_blueprint, url_prefix='/mapitems')
app.register_blueprint(waves_blueprint, url_prefix='/mountain_wave_project')
|
from flask import request
from werkzeug.exceptions import Forbidden
from werkzeug.useragents import UserAgent
from .errors import register as register_error_handlers
from .airports import airports_blueprint
from .airspace import airspace_blueprint
from .mapitems import mapitems_blueprint
from .waves import waves_blueprint
def register(app):
"""
:param flask.Flask app: a Flask app
"""
@app.before_request
def require_user_agent():
"""
API requests require a ``User-Agent`` header
"""
user_agent = request.user_agent
assert isinstance(user_agent, UserAgent)
if not user_agent.string:
description = 'You don\'t have the permission to access the API with a User-Agent header.'
raise Forbidden(description)
register_error_handlers(app)
app.register_blueprint(airports_blueprint, url_prefix='/airports')
app.register_blueprint(airspace_blueprint, url_prefix='/airspace')
app.register_blueprint(mapitems_blueprint, url_prefix='/mapitems')
app.register_blueprint(waves_blueprint, url_prefix='/mountain_wave_project')
|
Remove unnecessary self parameter from static method
|
import requests
import json
from ..scraper import Scraper
class LayersScraper(Scraper):
"""A superclass for scraping Layers of the UofT Map.
Map is located at http://map.utoronto.ca
"""
def __init__(self, name, output_location='.'):
super().__init__(name, output_location)
self.host = 'http://map.utoronto.ca/'
self.s = requests.Session()
def get_layers_json(self, campus):
"""Retrieve the JSON structure from host."""
self.logger.info('Scraping map layers %s.' % campus)
headers = {
'Referer': self.host
}
html = self.s.get('%s%s%s' % (self.host, 'data/map/', campus),
headers=headers).text
data = json.loads(html)
return data['layers']
@staticmethod
def get_value(entry, val, number=False):
"""Retrieve the desired value from the parsed response dictionary."""
if val in entry.keys():
return entry[val]
else:
return 0 if number else ''
|
import requests
import json
from ..scraper import Scraper
class LayersScraper(Scraper):
"""A superclass for scraping Layers of the UofT Map.
Map is located at http://map.utoronto.ca
"""
def __init__(self, name, output_location='.'):
super().__init__(name, output_location)
self.host = 'http://map.utoronto.ca/'
self.s = requests.Session()
def get_layers_json(self, campus):
"""Retrieve the JSON structure from host."""
self.logger.info('Scraping map layers %s.' % campus)
headers = {
'Referer': self.host
}
html = self.s.get('%s%s%s' % (self.host, 'data/map/', campus),
headers=headers).text
data = json.loads(html)
return data['layers']
@staticmethod
def get_value(self, entry, val, number=False):
"""Retrieve the desired value from the parsed response dictionary."""
if val in entry.keys():
return entry[val]
else:
return 0 if number else ''
|
Fix for missing parenthesis causing syntax error.
Reviewed by me.
|
/*
* bootstrap.js
* Objective-J
*
* Created by Francisco Tolmasky.
* Copyright 2008, 280 North, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
if (window.OBJJ_MAIN_FILE)
{
var addOnload = function(handler)
{
if (window.addEventListener)
window.addEventListener("load", handler, false);
else if (window.attachEvent)
window.attachEvent("onload", handler);
}
var documentLoaded = NO;
var defaultHandler = function()
{
documentLoaded = YES;
}
addOnload(defaultHandler);
objj_import(OBJJ_MAIN_FILE, YES, function()
{
if (documentLoaded)
main();
else
addOnload(main);
});
}
|
/*
* bootstrap.js
* Objective-J
*
* Created by Francisco Tolmasky.
* Copyright 2008, 280 North, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
if (window.OBJJ_MAIN_FILE)
{
var addOnload = function(handler
{
if (window.addEventListener)
window.addEventListener("load", handler, false);
else if (window.attachEvent)
window.attachEvent("onload", handler);
}
var documentLoaded = NO;
var defaultHandler = function()
{
documentLoaded = YES;
}
addOnload(defaultHandler);
objj_import(OBJJ_MAIN_FILE, YES, function()
{
if (documentLoaded)
main();
else
addOnload(main);
});
}
|
Configure deploy to copy dist as well
|
//upload to s3 task
module.exports = {
options: {
accessKeyId: '<%= AWS_ACCESS_KEY_ID %>',
secretAccessKey: '<%= AWS_SECRET_KEY %>',
region: '<%= AWS_REGION %>'
},
staging: {
options: {
bucket: '<%= AWS_BUCKET %>'
},
files: [{
expand: true,
cwd: '',
src: ['preview/**/*','dist/**/*'],
dest: '<%= AWS_SUBFOLDER %>' + '/<%= (process.env.TRAVIS_BRANCH || gitinfo.local.branch.current.name) %>/'
}]
}
};
|
//upload to s3 task
module.exports = {
options: {
accessKeyId: '<%= AWS_ACCESS_KEY_ID %>',
secretAccessKey: '<%= AWS_SECRET_KEY %>',
region: '<%= AWS_REGION %>'
},
staging: {
options: {
bucket: '<%= AWS_BUCKET %>'
},
files: [{
expand: true,
cwd: 'preview/',
src: ['**'],
dest: '<%= AWS_SUBFOLDER %>' + '/<%= (process.env.TRAVIS_BRANCH || gitinfo.local.branch.current.name) %>/'
}]
}
};
|
Add empty onUnload to pass test
|
const core = require("sdk/view/core");
const hotkeys = require("sdk/hotkeys");
const tabs = require("sdk/tabs");
const windows = require("sdk/windows").browserWindows;
const helpers = require("./lib/helpers");
const state = require("./lib/state");
function registerListeners(window) {
let lowLevelWindow = core.viewFor(window);
lowLevelWindow.addEventListener("click", helpers.maybeDisableIfNewTabButtonClick, true);
lowLevelWindow.addEventListener("SSWindowStateBusy", function() { state.disableUntilEnabled(); });
lowLevelWindow.addEventListener("SSWindowStateReady", function() { state.enable(); });
}
exports.main = function(options) {
console.log("Starting up with reason ", options.loadReason);
hotkeys.Hotkey({
combo: "accel-alt-t",
onPress: helpers.openNewTabAtDefaultPosition,
});
tabs.on("open", helpers.maybeMoveTab);
for (let window of windows) {
registerListeners(window);
}
windows.on("open", registerListeners);
};
exports.onUnload = function(reason) {
console.log("Closing down with reason ", reason);
};
|
const core = require("sdk/view/core");
const hotkeys = require("sdk/hotkeys");
const tabs = require("sdk/tabs");
const windows = require("sdk/windows").browserWindows;
const helpers = require("./lib/helpers");
const state = require("./lib/state");
function registerListeners(window) {
let lowLevelWindow = core.viewFor(window);
lowLevelWindow.addEventListener("click", helpers.maybeDisableIfNewTabButtonClick, true);
lowLevelWindow.addEventListener("SSWindowStateBusy", function() { state.disableUntilEnabled(); });
lowLevelWindow.addEventListener("SSWindowStateReady", function() { state.enable(); });
}
exports.main = function(options) {
console.log("Starting up with reason ", options.loadReason);
hotkeys.Hotkey({
combo: "accel-alt-t",
onPress: helpers.openNewTabAtDefaultPosition,
});
tabs.on("open", helpers.maybeMoveTab);
for (let window of windows) {
registerListeners(window);
}
windows.on("open", registerListeners);
};
|
Remove print statements from TwistedCircuitBreaker
|
# Copyright 2012 Edgeware AB.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from circuit.breaker import CircuitBreaker, CircuitBreakerSet
try:
from twisted.internet import defer
except ImportError:
pass
class TwistedCircuitBreaker(CircuitBreaker):
"""Circuit breaker that know that L{defer.inlineCallbacks} use
exceptions in its internal workings.
"""
def __exit__(self, exc_type, exc_val, tb):
if exc_type is defer._DefGen_Return:
exc_type, exc_val, tb = None, None, None
return CircuitBreaker.__exit__(self, exc_type, exc_val, tb)
class TwistedCircuitBreakerSet(CircuitBreakerSet):
"""Circuit breaker that supports twisted."""
def __init__(self, reactor, logger, **kwargs):
kwargs.update({'factory': TwistedCircuitBreaker})
CircuitBreakerSet.__init__(self, reactor.seconds, logger,
**kwargs)
|
# Copyright 2012 Edgeware AB.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from circuit.breaker import CircuitBreaker, CircuitBreakerSet
try:
from twisted.internet import defer
except ImportError:
pass
class TwistedCircuitBreaker(CircuitBreaker):
"""Circuit breaker that know that L{defer.inlineCallbacks} use
exceptions in its internal workings.
"""
def __exit__(self, exc_type, exc_val, tb):
print "EXIT"
if exc_type is defer._DefGen_Return:
print "GOT IT"
exc_type, exc_val, tb = None, None, None
return CircuitBreaker.__exit__(self, exc_type, exc_val, tb)
class TwistedCircuitBreakerSet(CircuitBreakerSet):
"""Circuit breaker that supports twisted."""
def __init__(self, reactor, logger, **kwargs):
kwargs.update({'factory': TwistedCircuitBreaker})
CircuitBreakerSet.__init__(self, reactor.seconds, logger,
**kwargs)
|
Test that self-repair endpoint does not set cookies
|
from django.core.urlresolvers import reverse
from django.db import connection
from django.test.utils import CaptureQueriesContext
import pytest
class TestSelfRepair:
def test_url_is_right(self):
url = reverse('selfrepair:index', args=['en-US'])
assert url == '/en-US/repair'
@pytest.mark.django_db
def test_makes_no_db_queries(self, client):
queries = CaptureQueriesContext(connection)
with queries:
url = reverse('selfrepair:index', args=['en-US'])
res = client.get(url)
assert res.status_code == 200
assert len(queries) == 0
@pytest.mark.django_db
def test_doesnt_redirect(self, client):
url = '/en-US/repair'
assert client.get(url).status_code == 200
url += '/'
assert client.get(url).status_code == 200
def test_sets_no_cookies(self, client):
res = client.get('/en-US/repair')
assert res.status_code == 200
assert res.client.cookies == {}
|
from django.core.urlresolvers import reverse
from django.db import connection
from django.test.utils import CaptureQueriesContext
import pytest
class TestSelfRepair:
def test_url_is_right(self):
url = reverse('selfrepair:index', args=['en-US'])
assert url == '/en-US/repair'
@pytest.mark.django_db
def test_makes_no_db_queries(self, client):
queries = CaptureQueriesContext(connection)
with queries:
url = reverse('selfrepair:index', args=['en-US'])
res = client.get(url)
assert res.status_code == 200
assert len(queries) == 0
@pytest.mark.django_db
def test_doesnt_redirect(self, client):
url = '/en-US/repair'
assert client.get(url).status_code == 200
url += '/'
assert client.get(url).status_code == 200
|
Use the RouterState mixin in GameNav
|
import * as React from 'react'
import {State} from 'react-router'
import {Octicon as OcticonClass} from './octicon'
import {Link as LinkClass} from 'react-router'
let Link = React.createFactory(LinkClass);
let Octicon = React.createFactory(OcticonClass);
let GameNavbar = React.createClass({
mixins: [State],
render() {
return React.createElement('ul', {id: 'game-nav', className: 'menu'},
React.createElement('li', null,
Link({to: 'game', params: this.getParams(), query: {section: 'board'}}, Octicon({icon: 'globe'}
))),
React.createElement('li', null,
Link({to: 'game', params: this.getParams(), query: {section: 'chat'}}, Octicon({icon: 'comment-discussion'}
))),
React.createElement('li', null,
Link({to: 'game', params: this.getParams(), query: {section: 'history'}}, Octicon({icon: 'clock'}
))),
React.createElement('li', null,
Link({to: 'game', params: this.getParams(), query: {section: 'info'}}, Octicon({icon: 'gear'}
)))
)
},
})
export default GameNavbar
|
import * as React from 'react'
import {Octicon as OcticonClass} from './octicon'
import {Link} from 'react-router'
let Octicon = React.createFactory(OcticonClass);
let GameNavbar = React.createClass({
render() {
return React.createElement('ul', {id: 'game-nav', className: 'menu'},
React.createElement('li', {key: 'board'},
React.createElement(Link, {to: 'game', params: {gameId: this.props.params.gameId}, query: {section: 'board'}}, Octicon({icon: 'globe'}
))),
React.createElement('li', {key: 'chat'},
React.createElement(Link, {to: 'game', params: {gameId: this.props.params.gameId}, query: {section: 'chat'}}, Octicon({icon: 'comment-discussion'}
))),
React.createElement('li', {key: 'history'},
React.createElement(Link, {to: 'game', params: {gameId: this.props.params.gameId}, query: {section: 'history'}}, Octicon({icon: 'clock'}
))),
React.createElement('li', {key: 'info'},
React.createElement(Link, {to: 'game', params: {gameId: this.props.params.gameId}, query: {section: 'info'}}, Octicon({icon: 'gear'}
)))
)
},
})
export default GameNavbar
|
Revise 009, add test cases
|
"""
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the
restriction of using extra space.
You could also try reversing an integer. However, if you have solved the
problem "Reverse Integer", you know that the reversed integer might
overflow. How would you handle such case?
There is a more generic way of solving this problem.
"""
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
elif x < 10:
return True
elif x % 10 == 0:
return False
revx = 0
tmpx = x
while tmpx > 0:
revx = revx * 10 + tmpx % 10
tmpx //= 10
return revx == x
a = Solution()
print(a.isPalindrome(-1) == False)
print(a.isPalindrome(1) == True)
print(a.isPalindrome(121) == True)
print(a.isPalindrome(1221) == True)
print(a.isPalindrome(10021) == False)
|
"""
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the
restriction of using extra space.
You could also try reversing an integer. However, if you have solved the
problem "Reverse Integer", you know that the reversed integer might
overflow. How would you handle such case?
There is a more generic way of solving this problem.
"""
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x<0:
return False
elif x<10:
return True
elif x%10==0:
return False
revx=0
tmpx=x
while tmpx>0:
revx=revx*10+tmpx%10
tmpx//=10
return revx==x
|
Switch to use String.prototype.indexOf instead of String.prototype.includes to support IE
|
// Shim to avoid requiring Velocity in Node environments, since it
// requires window. Note that this just no-ops the components so
// that they'll render, rather than doing something clever like
// statically rendering the end state of any provided animations.
//
// TODO(finneganh): Circle back on jsdom to see if we can run full
// Velocity with it in place. This come up in:
// https://github.com/twitter-fabric/velocity-react/issues/119
// but there may have been different loading issues in that case,
// not a global incompatibility with jsdom.
if (typeof window === 'undefined' || navigator.userAgent.indexOf("Node.js") !== -1 || navigator.userAgent.indexOf("jsdom") !== -1) {
var Velocity = function() {};
Velocity.Utilities = {};
Velocity.Utilities.removeData = function() {};
Velocity.velocityReactServerShim = true;
module.exports = Velocity;
} else {
// this is how velocity-ui finds the Velocity instance, so lets make sure we find the right instance
var g = (window.jQuery || window.Zepto || window);
// require Velocity if it doesn't already exist
module.exports = g.Velocity ? g.Velocity : require('velocity-animate');
}
|
// Shim to avoid requiring Velocity in Node environments, since it
// requires window. Note that this just no-ops the components so
// that they'll render, rather than doing something clever like
// statically rendering the end state of any provided animations.
//
// TODO(finneganh): Circle back on jsdom to see if we can run full
// Velocity with it in place. This come up in:
// https://github.com/twitter-fabric/velocity-react/issues/119
// but there may have been different loading issues in that case,
// not a global incompatibility with jsdom.
if (typeof window === 'undefined' || navigator.userAgent.includes("Node.js") || navigator.userAgent.includes("jsdom")) {
var Velocity = function() {};
Velocity.Utilities = {};
Velocity.Utilities.removeData = function() {};
Velocity.velocityReactServerShim = true;
module.exports = Velocity;
} else {
// this is how velocity-ui finds the Velocity instance, so lets make sure we find the right instance
var g = (window.jQuery || window.Zepto || window);
// require Velocity if it doesn't already exist
module.exports = g.Velocity ? g.Velocity : require('velocity-animate');
}
|
Improve Rust function parser (Use correct identifier)
|
var DocsParser = require("../docsparser");
var xregexp = require('../xregexp').XRegExp;
function RustParser(settings) {
DocsParser.call(this, settings);
}
RustParser.prototype = Object.create(DocsParser.prototype);
RustParser.prototype.setup_settings = function() {
this.settings = {
'curlyTypes': false,
'typeInfo': false,
'typeTag': false,
'varIdentifier': '.*',
'fnIdentifier': '[a-zA-Z_][a-zA-Z_0-9]*',
'fnOpener': '^\\s*fn',
'commentCloser': ' */',
'bool': 'Boolean',
'function': 'Function'
};
};
RustParser.prototype.parse_function = function(line) {
// TODO: add regexp for closures syntax
// TODO: parse params
var regex = xregexp('\\s*fn\\s+(?P<name>' + this.settings.fnIdentifier + ')');
var matches = xregexp.exec(line, regex);
if(matches === null || matches.name === undefined) {
return null;
}
var name = matches.name;
return [name, null];
};
RustParser.prototype.parse_var = function(line) {
return null;
};
RustParser.prototype.format_function = function(name, args) {
return name;
};
module.exports = RustParser;
|
var DocsParser = require("../docsparser");
var xregexp = require('../xregexp').XRegExp;
function RustParser(settings) {
DocsParser.call(this, settings);
}
RustParser.prototype = Object.create(DocsParser.prototype);
RustParser.prototype.setup_settings = function() {
this.settings = {
'curlyTypes': false,
'typeInfo': false,
'typeTag': false,
'varIdentifier': '.*',
'fnIdentifier': '.*',
'fnOpener': '^\\s*fn',
'commentCloser': ' */',
'bool': 'Boolean',
'function': 'Function'
};
};
RustParser.prototype.parse_function = function(line) {
var regex = xregexp('\\s*fn\\s+(?P<name>\\S+)');
var matches = xregexp.exec(line, regex);
if(matches === null)
return null;
var name = matches.name || '';
return [ name, []];
};
RustParser.prototype.parse_var = function(line) {
return null;
};
RustParser.prototype.format_function = function(name, args) {
return name;
};
module.exports = RustParser;
|
Make sure we invoke the response processors even for app content.
|
from django.contrib.auth.decorators import permission_required
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from feincms.module.page.models import Page
def _build_page_response(page, request):
response = page.setup_request(request)
if response is None:
extra_context = request._feincms_extra_context
response = render_to_response(page.template.path, {
'feincms_page': page,
}, context_instance=RequestContext(request, extra_context))
return response
def build_page_response(page, request):
response = _build_page_response(page, request)
page.finalize_response(request, response)
return response
def handler(request, path=None):
"""
This is the default handler for feincms page content.
"""
if path is None:
path = request.path
page = Page.objects.page_for_path_or_404(path)
response = build_page_response(page, request)
return response
@permission_required('page.change_page')
def preview_handler(request, page_id):
"""
This handler is for previewing site content; it takes a page_id so
the page is uniquely identified and does not care whether the page
is active or expired. To balance that, it requires a logged in user.
"""
page = get_object_or_404(Page, pk=page_id)
return _build_page_response(page, request)
|
from django.contrib.auth.decorators import permission_required
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from feincms.module.page.models import Page
def build_page_response(page, request):
response = page.setup_request(request)
if response is None:
extra_context = request._feincms_extra_context
response = render_to_response(page.template.path, {
'feincms_page': page,
}, context_instance=RequestContext(request, extra_context))
return response
def handler(request, path=None):
"""
This is the default handler for feincms page content.
"""
if path is None:
path = request.path
page = Page.objects.page_for_path_or_404(path)
response = build_page_response(page, request)
page.finalize_response(request, response)
return response
@permission_required('page.change_page')
def preview_handler(request, page_id):
"""
This handler is for previewing site content; it takes a page_id so
the page is uniquely identified and does not care whether the page
is active or expired. To balance that, it requires a logged in user.
"""
page = get_object_or_404(Page, pk=page_id)
return build_page_response(page, request)
|
Add teardown of integration test
|
from kitten.server import KittenServer
from gevent.pool import Group
from mock import MagicMock
class TestPropagation(object):
def setup_method(self, method):
self.servers = Group()
for port in range(4):
ns = MagicMock()
ns.port = 9812 + port
server = KittenServer(ns)
self.servers.spawn(server.listen_forever)
def teardown_method(self, method):
self.servers.kill(timeout=1)
def test_node_propagation(self):
"""
Tests that check node propagation
1) Spin up four servers.
2) Make the first one send a sync request to all three others.
3) Count the numbers of requests made.
4) Check databases to see that they all know each other.
"""
pass
|
from kitten.server import KittenServer
from gevent.pool import Group
from mock import MagicMock
class TestPropagation(object):
def setup_method(self, method):
self.servers = Group()
for port in range(4):
ns = MagicMock()
ns.port = 9812 + port
server = KittenServer(ns)
self.servers.spawn(server.listen_forever)
def test_node_propagation(self):
"""
Tests that check node propagation
1) Spin up four servers.
2) Make the first one send a sync request to all three others.
3) Count the numbers of requests made.
4) Check databases to see that they all know each other.
"""
pass
|
Remove last_page not needed anymore.
|
import math
from django import template
from ..conf import settings
register = template.Library()
@register.inclusion_tag('googlesearch/_pagination.html', takes_context=True)
def show_pagination(context, pages_to_show=10):
max_pages = int(math.ceil(context['total_results'] /
settings.GOOGLE_SEARCH_RESULTS_PER_PAGE))
prev_page = context['current_page'] - 1
next_page = context['current_page'] + 1
context.update({
'pages': range(1, max_pages + 1),
'prev_page': prev_page if context['current_page'] - 1 > 0 else None,
'next_page': next_page if next_page < max_pages else None,
})
return context
|
import math
from django import template
from ..conf import settings
register = template.Library()
@register.inclusion_tag('googlesearch/_pagination.html', takes_context=True)
def show_pagination(context, pages_to_show=10):
max_pages = int(math.ceil(context['total_results'] /
settings.GOOGLE_SEARCH_RESULTS_PER_PAGE))
last_page = int(context['current_page']) + pages_to_show - 1
last_page = max_pages if last_page > max_pages else last_page
prev_page = context['current_page'] - 1
next_page = context['current_page'] + 1
context.update({
'pages': range(1, max_pages + 1),
'prev_page': prev_page if context['current_page'] - 1 > 0 else None,
'next_page': next_page if next_page < max_pages else None,
})
return context
|
Add function for generating random id
|
''' Helper methods for tests '''
import string
import random
from ckan.tests import factories
def create_mock_data(**kwargs):
mock_data = {}
mock_data['organization'] = factories.Organization()
mock_data['organization_name'] = mock_data['organization']['name']
mock_data['organization_id'] = mock_data['organization']['id']
mock_data['dataset'] = factories.Dataset(owner_org=mock_data['organization_id'])
mock_data['dataset_name'] = mock_data['dataset']['name']
mock_data['package_id'] = mock_data['dataset']['id']
mock_data['resource'] = factories.Resource(package_id=mock_data['package_id'])
mock_data['resource_name'] = mock_data['resource']['name']
mock_data['resource_id'] = mock_data['resource']['id']
mock_data['resource_view'] = factories.ResourceView(
resource_id=mock_data['resource_id'])
mock_data['resource_view_title'] = mock_data['resource_view']['title']
mock_data['context'] = {
'user': factories._get_action_user_name(kwargs)
}
return mock_data
def id_generator(size=6, chars=string.ascii_lowercase + string.digits):
''' Create random id which is a combination of letters and numbers '''
return ''.join(random.choice(chars) for _ in range(size))
|
from ckan.tests import factories
def create_mock_data(**kwargs):
mock_data = {}
mock_data['organization'] = factories.Organization()
mock_data['organization_name'] = mock_data['organization']['name']
mock_data['organization_id'] = mock_data['organization']['id']
mock_data['dataset'] = factories.Dataset(owner_org=mock_data['organization_id'])
mock_data['dataset_name'] = mock_data['dataset']['name']
mock_data['package_id'] = mock_data['dataset']['id']
mock_data['resource'] = factories.Resource(package_id=mock_data['package_id'])
mock_data['resource_name'] = mock_data['resource']['name']
mock_data['resource_id'] = mock_data['resource']['id']
mock_data['resource_view'] = factories.ResourceView(
resource_id=mock_data['resource_id'])
mock_data['resource_view_title'] = mock_data['resource_view']['title']
mock_data['context'] = {
'user': factories._get_action_user_name(kwargs)
}
return mock_data
|
Remove unused container in instance initializer
|
import ActiveModelAdapter from 'active-model-adapter';
import ActiveModelSerializer from 'active-model-adapter/active-model-serializer';
export default {
name: 'active-model-adapter',
initialize: function(applicationOrRegistry) {
var registry;
if (applicationOrRegistry.registry) {
// initializeStoreService was registered with an
// instanceInitializer. The first argument is the application
// instance.
registry = applicationOrRegistry.registry;
} else {
// initializeStoreService was called by an initializer instead of
// an instanceInitializer. The first argument is a registy. This
// case allows ED to support Ember pre 1.12
registry = applicationOrRegistry;
}
registry.register('adapter:-active-model', ActiveModelAdapter);
registry.register('serializer:-active-model', ActiveModelSerializer.extend({ isNewSerializerAPI: true }));
}
};
|
import ActiveModelAdapter from 'active-model-adapter';
import ActiveModelSerializer from 'active-model-adapter/active-model-serializer';
export default {
name: 'active-model-adapter',
initialize: function(applicationOrRegistry) {
var registry, container;
if (applicationOrRegistry.registry && applicationOrRegistry.container) {
// initializeStoreService was registered with an
// instanceInitializer. The first argument is the application
// instance.
registry = applicationOrRegistry.registry;
container = applicationOrRegistry.container;
} else {
// initializeStoreService was called by an initializer instead of
// an instanceInitializer. The first argument is a registy. This
// case allows ED to support Ember pre 1.12
registry = applicationOrRegistry;
if (registry.container) { // Support Ember 1.10 - 1.11
container = registry.container();
} else { // Support Ember 1.9
container = registry;
}
}
registry.register('adapter:-active-model', ActiveModelAdapter);
registry.register('serializer:-active-model', ActiveModelSerializer.extend({ isNewSerializerAPI: true }));
}
};
|
Update Development Status from Planning to Alpha
|
from setuptools import find_packages, setup
setup(
name='incuna-pigeon',
version='0.0.0',
description='Notification management',
url='https://github.com/incuna/incuna-pigeon',
author='Incuna',
author_email='admin@incuna.com',
license='BSD',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Communications',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.4',
],
keywords='notifications',
packages=find_packages(),
)
|
from setuptools import find_packages, setup
setup(
name='incuna-pigeon',
version='0.0.0',
description='Notification management',
url='https://github.com/incuna/incuna-pigeon',
author='Incuna',
author_email='admin@incuna.com',
license='BSD',
classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Developers',
'Topic :: Communications',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.4',
],
keywords='notifications',
packages=find_packages(),
)
|
8: Create documentation of DataSource Settings
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8
|
######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"
# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dsidlist = []
# remove unwanted databases
for db in dbs:
dbname = db.split('(')
n = 0
for i in dbname:
# i is only the name of the DataSource, db is DataSource ID!
if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
dsidlist.append(str(db).replace('"',''))
n += 1
dsidlist.sort()
for dsid in dsidlist:
propertySet = AdminConfig.showAttribute(dsid,"propertySet")
propertyList = AdminConfig.list("J2EEResourceProperty", propertySet).splitlines()
|
######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"
# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dsidlist = []
# remove unwanted databases
for db in dbs:
dbname = db.split('(')
n = 0
for i in dbname:
# i is only the name of the DataSource, db is DataSource ID!
if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
dsidlist.append(str(db).replace('"',''))
n += 1
dsidlist.sort()
for dsid in dsidlist:
print "AdminConfig.list( dsid ): "
AdminConfig.showAttribute(dsid,"propertySet")
|
Set full commit message as tooltip
Resolves: #880
|
import React from 'react';
import Relay from 'react-relay';
import PropTypes from 'prop-types';
import Octicon from '../../views/octicon';
export class Commit extends React.Component {
static propTypes = {
item: PropTypes.object.isRequired,
}
render() {
const commit = this.props.item;
return (
<div className="commit">
<Octicon className="pre-timeline-item-icon" icon="git-commit" />
<img
className="author-avatar" src={commit.author.avatarUrl}
title={commit.author.user ? commit.author.user.login : commit.author.name}
/>
<span
className="commit-message-headline"
title={commit.message}
dangerouslySetInnerHTML={{__html: commit.messageHeadlineHTML}}
/>
<span className="commit-sha">{commit.oid.slice(0, 8)}</span>
</div>
);
}
}
export default Relay.createContainer(Commit, {
fragments: {
item: () => Relay.QL`
fragment on Commit {
author {
name avatarUrl
user {
login
}
}
oid message messageHeadlineHTML
}
`,
},
});
|
import React from 'react';
import Relay from 'react-relay';
import PropTypes from 'prop-types';
import Octicon from '../../views/octicon';
export class Commit extends React.Component {
static propTypes = {
item: PropTypes.object.isRequired,
}
render() {
const commit = this.props.item;
return (
<div className="commit">
<Octicon className="pre-timeline-item-icon" icon="git-commit" />
<img
className="author-avatar" src={commit.author.avatarUrl}
title={commit.author.user ? commit.author.user.login : commit.author.name}
/>
<span
className="commit-message-headline"
title={commit.messageHeadline}
dangerouslySetInnerHTML={{__html: commit.messageHeadlineHTML}}
/>
<span className="commit-sha">{commit.oid.slice(0, 8)}</span>
</div>
);
}
}
export default Relay.createContainer(Commit, {
fragments: {
item: () => Relay.QL`
fragment on Commit {
author {
name avatarUrl
user {
login
}
}
oid messageHeadline messageHeadlineHTML
}
`,
},
});
|
Use JpaRepository instead of CrudRepository.
|
/*
* Copyright 2016 SEARCH-The National Consortium for Justice Information and Statistics
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.search.nibrs.stagingdata.repository;
import org.search.nibrs.stagingdata.model.UcrOffenseCodeType;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UcrOffenseCodeTypeRepository extends JpaRepository<UcrOffenseCodeType, Integer>{
public UcrOffenseCodeType findFirstByStateCode( String stateCode );
}
|
/*
* Copyright 2016 SEARCH-The National Consortium for Justice Information and Statistics
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.search.nibrs.stagingdata.repository;
import org.search.nibrs.stagingdata.model.UcrOffenseCodeType;
import org.springframework.data.repository.CrudRepository;
public interface UcrOffenseCodeTypeRepository extends CrudRepository<UcrOffenseCodeType, Integer>{
public UcrOffenseCodeType findFirstByStateCode( String stateCode );
public Iterable<UcrOffenseCodeType> findByOrderByStateDescription();
}
|
Copy zlib.dll into Windows h5py installed from source
|
import distutils.sysconfig
from glob import glob
import os
from os.path import join as pjoin, basename
from shutil import copy
from sys import platform
def main():
"""
Copy HDF5 DLLs into installed h5py package
"""
# This is the function Tox also uses to locate site-packages (Apr 2019)
sitepackagesdir = distutils.sysconfig.get_python_lib(plat_specific=True)
print("site packages dir:", sitepackagesdir)
hdf5_path = os.environ.get("HDF5_DIR")
print("HDF5_DIR", hdf5_path)
# HDF5_DIR is not set when we're testing wheels; these should already have
# the necessary libraries bundled in.
if platform.startswith('win') and hdf5_path is not None:
for f in glob(pjoin(hdf5_path, 'lib/*.dll')):
copy(f, pjoin(sitepackagesdir, 'h5py', basename(f)))
print("Copied", f)
zlib_root = os.environ.get("ZLIB_ROOT")
if zlib_root:
f = pjoin(zlib_root, 'bin_release', 'zlib.dll')
copy(f, pjoin(sitepackagesdir, 'h5py', 'zlib.dll'))
print("Copied", f)
print("In installed h5py:", os.listdir(pjoin(sitepackagesdir, 'h5py')))
if __name__ == '__main__':
main()
|
import distutils.sysconfig
from glob import glob
import os
from os.path import join as pjoin, basename
from shutil import copy
from sys import platform
def main():
"""
Copy HDF5 DLLs into installed h5py package
"""
# This is the function Tox also uses to locate site-packages (Apr 2019)
sitepackagesdir = distutils.sysconfig.get_python_lib(plat_specific=True)
print("site packages dir:", sitepackagesdir)
hdf5_path = os.environ.get("HDF5_DIR")
print("HDF5_DIR", hdf5_path)
# HDF5_DIR is not set when we're testing wheels; these should already have
# the necessary libraries bundled in.
if platform.startswith('win') and hdf5_path is not None:
for f in glob(pjoin(hdf5_path, 'lib/*.dll')):
copy(f, pjoin(sitepackagesdir, 'h5py', basename(f)))
print("Copied", f)
print("In installed h5py:", os.listdir(pjoin(sitepackagesdir, 'h5py')))
if __name__ == '__main__':
main()
|
Apply proposals by tut2 feedback
|
var lastField = null;
var currentFillColor = ''; // ???
var changeCounter = 0; // ???
function setField(element) {
// element contains the current html element
if (element.style.backgroundColor !== currentFillColor) {
element.style.backgroundColor = currentFillColor;
} else {
element.style.backgroundColor = '#eee';
}
++changeCounter;
if (changeCounter === 10) {
alert('You have clicked 10 times on the field!');
changeCounter = 0;
}
}
function setFillColor(color) {
// color should be a string
var logEntry = document.createElement('p');
logEntry.innerHTML = 'Color changed';
logEntry.style.color = currentFillColor = color;
document.getElementById('Log').appendChild(logEntry);
}
|
var lastField = null;
var currentFillColor = ''; // ???
var changeCounter = 0; // ???
function setField(element) {
// element contains the current html element
if (element.style.backgroundColor !== currentFillColor) {
element.style.backgroundColor = currentFillColor;
} else {
element.style.backgroundColor = '#eee';
}
if (lastField === element) {
++changeCounter;
} else {
changeCounter = 0;
}
if (changeCounter === 10) {
alert('You have clicked 10 times on the field!');
changeCounter = 0;
}
lastField = element;
}
function setFillColor(color) {
// color should be a string
var logEntry = document.createElement('p');
logEntry.innerHTML = 'Color changed';
logEntry.style.color = currentFillColor = color;
document.getElementById('Log').appendChild(logEntry);
}
|
Update with reference to global nav partial
|
var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-font-family/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-font-family/tachyons-font-family.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_font-family.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var template = fs.readFileSync('./templates/docs/font-family/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs
})
fs.writeFileSync('./docs/typography/font-family/index.html', html)
|
var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-font-family/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-font-family/tachyons-font-family.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_font-family.css', 'utf8')
var template = fs.readFileSync('./templates/docs/font-family/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS
})
fs.writeFileSync('./docs/typography/font-family/index.html', html)
|
Use regular require, when given context is same as current context
|
'use strict';
var Module = require('module')
, wrap = Module.wrap
, readFile = require('fs').readFileSync
, dirname = require('path').dirname
, vm = require('vm')
, createContext = vm.createContext
, runInContext = vm.runInContext
, errorMsg = require('./is-module-not-found-error')
, props = ['require', 'module', 'exports']
, modRequire = Module.prototype.require || function (path) {
return Module._load(path, this);
};
module.exports = function (path, context) {
var fmodule, r, content, dirpath;
if ((context === global)
|| (context.process && (context.process.title === 'node')
&& (context.pid === global.pid))) {
return require(path);
} else {
dirpath = dirname(path);
fmodule = new Module(path, module);
fmodule.filename = path;
fmodule.paths = Module._nodeModulePaths(dirpath);
fmodule.require = modRequire;
try {
content = readFile(path, 'utf8');
} catch (e) {
throw new Error(errorMsg.pattern.replace(errorMsg.token, path));
}
vm.runInContext(wrap(content), context).call(fmodule.exports, fmodule.exports,
fmodule.require.bind(fmodule), fmodule, path, dirpath);
fmodule.loaded = true;
return fmodule.exports;
}
};
|
'use strict';
var Module = require('module')
, wrap = Module.wrap
, readFile = require('fs').readFileSync
, dirname = require('path').dirname
, vm = require('vm')
, createContext = vm.createContext
, runInContext = vm.runInContext
, errorMsg = require('./is-module-not-found-error')
, props = ['require', 'module', 'exports'];
module.exports = function (path, context) {
var fmodule, r, content, dirpath;
console.log(context === global, path);
if (context === global) {
return require(path);
} else {
dirpath = dirname(path);
fmodule = new Module(path, module);
fmodule.filename = path;
fmodule.paths = Module._nodeModulePaths(dirpath);
try {
content = readFile(path, 'utf8');
} catch (e) {
throw new Error(errorMsg.pattern.replace(errorMsg.token, path));
}
vm.runInContext(wrap(content), context).call(fmodule.exports, fmodule.exports,
fmodule.require.bind(fmodule), fmodule, path, dirpath);
fmodule.loaded = true;
return fmodule.exports;
}
};
|
Make test models self contained specific defining Model classes
|
from pysagec import models
def test_field():
f = models.Field('tag')
assert f.__get__(None, None) is f
assert 'Field' in repr(f)
def test_model_as_dict():
class MyModel(models.Model):
root_tag = 'root'
prop1 = models.Field('tag1')
prop2 = models.Field('tag2')
model = MyModel(prop1=42)
model.prop2 = 'foo'
assert model.prop1 == 42
assert {'root': [{'tag1': 42}, {'tag2': 'foo'}]} == model.as_dict()
def test_model_default():
class MyModel(models.Model):
root_tag = 'root'
prop = models.Field('tag')
model = MyModel()
assert model.prop is None
|
from pysagec import models
def test_auth_info():
values = [
('mrw:CodigoFranquicia', 'franchise_code', '123456'),
('mrw:CodigoAbonado', 'subscriber_code', 'subscriber_code'),
('mrw:CodigoDepartamento', 'departament_code', 'departament_code'),
('mrw:UserName', 'username', 'username'),
('mrw:Password', 'password', 'password'),
]
kwargs = {}
expected = {'mrw:AuthInfo': []}
for tag, prop, value in values:
kwargs[prop] = value
expected['mrw:AuthInfo'].append({tag: value})
auth_info = models.AuthInfo(**kwargs)
data = auth_info.as_dict()
assert expected == data
|
Add more logging and asserts to script
|
import logging
import time
from website.app import init_app
from website.identifiers.utils import get_or_create_identifiers, get_subdomain
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def add_identifiers_to_preprints():
from osf.models import PreprintService
preprints_without_identifiers = PreprintService.objects.filter(identifiers__isnull=True)
logger.info('About to add identifiers to {} preprints.'.format(preprints_without_identifiers.count()))
for preprint in preprints_without_identifiers:
new_identifiers = get_or_create_identifiers(preprint)
logger.info('Saving identifier for preprint {} from source {}'.format(preprint.node.title, preprint.provider.name))
preprint.set_preprint_identifiers(new_identifiers)
preprint.save()
doi = preprint.get_identifier('doi')
subdomain = get_subdomain(preprint)
assert subdomain.upper() in doi.value
assert preprint._id.upper() in doi.value
logger.info('Created DOI {} for Preprint from service {}'.format(doi.value, preprint.provider.name))
time.sleep(1)
logger.info('Finished Adding identifiers to {} preprints.'.format(preprints_without_identifiers.count()))
if __name__ == '__main__':
init_app(routes=False)
add_identifiers_to_preprints()
|
import logging
import time
from website.app import init_app
from website.identifiers.utils import get_or_create_identifiers
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def add_identifiers_to_preprints():
from osf.models import PreprintService
preprints_without_identifiers = PreprintService.objects.filter(identifiers__isnull=True)
logger.info('About to add identifiers to {} preprints.'.format(preprints_without_identifiers.count()))
for preprint in preprints_without_identifiers:
new_identifiers = get_or_create_identifiers(preprint)
logger.info('Saving identifier for preprint {}'.format(preprint.node.title))
preprint.set_preprint_identifiers(new_identifiers)
preprint.save()
time.sleep(1)
logger.info('Finished Adding identifiers to {} preprints.'.format(preprints_without_identifiers.count()))
if __name__ == '__main__':
init_app(routes=False)
add_identifiers_to_preprints()
|
Make the under construction page less horrible
|
<?php
require_once('config.php');
global $config;
require_once('page_template_dash_head.php');
require_once('page_template_dash_sidebar.php');
$election_id = $_GET['id'];
$election_name = get_election_name($election_id);
?>
<div class="content-wrapper">
<section class="content-header">
<h1 id="election_name">
<?php echo $election_name; ?>
</h1>
<ol class="breadcrumb">
<li><i class="fa fa-th-list"></i> Elections</li>
<li><?php echo $election_name; ?></li>
<li class="active">Dashboard</li>
</ol>
</section>
<section class="content">
<div class="row">
<div class="col-xs-12">
<div class="alert alert-info">
<h4><i class="icon fa fa-info"></i> Under Construction</h4>
We are still working on this page. Please work on your questions and we will email you when this page is ready.
</div>
</div>
</div>
</section>
</div>
<?php
require_once('page_template_dash_foot.php');
?>
|
<?php
require_once('config.php');
global $config;
require_once('page_template_dash_head.php');
require_once('page_template_dash_sidebar.php');
$election_id = $_GET['id'];
$election_name = get_election_name($election_id);
?>
<div class="content-wrapper">
<section class="content-header">
<h1 id="election_name">
<?php echo $election_name; ?>
</h1>
<ol class="breadcrumb">
<li><i class="fa fa-th-list"></i> Elections</li>
<li><?php echo $election_name; ?></li>
<li class="active">Dashboard</li>
</ol>
</section>
<section class="content">
<div class="row">
<h3>We are still working on this page. Please work on your questions and we will email you when this page is ready.</h3>
</div>
</section>
</div>
<?php
require_once('page_template_dash_foot.php');
?>
|
Add midpoint interpolation to stepped line
|
/**
Copyright 2017 Andrea "Stock" Stocchero
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.pepstock.charba.client.enums;
import org.pepstock.charba.client.commons.Key;
/**
* Property to set if the line is shown as a stepped line.
*
* @author Andrea "Stock" Stocchero
*/
public enum SteppedLine implements Key
{
/**
* Step-before Interpolation
*/
before,
/**
* Step-after Interpolation
*/
after,
/**
* Step-middle Interpolation
*/
middle,
/**
* No Step Interpolation (default)
*/
nosteppedline;
}
|
/**
Copyright 2017 Andrea "Stock" Stocchero
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.pepstock.charba.client.enums;
import org.pepstock.charba.client.commons.Key;
/**
* Property to set if the line is shown as a stepped line.
*
* @author Andrea "Stock" Stocchero
*/
public enum SteppedLine implements Key
{
/**
* Step-before Interpolation
*/
before,
/**
* Step-after Interpolation
*/
after,
/**
* No Step Interpolation (default)
*/
nosteppedline;
}
|
Allow non-authservice to offer anonymous
|
/*
* Copyright 2017 Red Hat Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var container = require('rhea');
function authenticate(username, password) {
console.log('Authenticating as ' + username);
return true;
}
container.sasl_server_mechanisms.enable_plain(authenticate);
container.sasl_server_mechanisms.enable_anonymous();
var server = container.listen({'port':process.env.LISTENPORT, 'require_sasl': true});
console.log('Listening on port ' + process.env.LISTENPORT);
container.on('connection_open', function (context) {
var authenticatedIdentity = { 'sub' : context.connection.sasl_transport.username || 'anonymous' };
var properties = context.connection.local.open.properties || {};
properties["authenticated-identity"] = authenticatedIdentity;
context.connection.local.open.properties = properties;
context.connection.close();
});
container.on('disconnected', function (context) {
});
|
/*
* Copyright 2017 Red Hat Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var container = require('rhea');
function authenticate(username, password) {
console.log('Authenticating as ' + username);
return true;
}
container.sasl_server_mechanisms.enable_plain(authenticate);
var server = container.listen({'port':process.env.LISTENPORT, 'require_sasl': true});
console.log('Listening on port ' + process.env.LISTENPORT);
container.on('connection_open', function (context) {
var authenticatedIdentity = { 'sub' : context.connection.sasl_transport.username };
var properties = context.connection.local.open.properties || {};
properties["authenticated-identity"] = authenticatedIdentity;
context.connection.local.open.properties = properties;
context.connection.close();
});
container.on('disconnected', function (context) {
});
|
Fix typo is -> as
|
#!/usr/bin/env python
import os
import sys
import subprocess
from importlib import import_module
if __name__ == '__main__':
# Test using django.test.runner.DiscoverRunner
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
# We need to use subprocess.call instead of django's execute_from_command_line
# because we can only setup django's settings once, and it's bad
# practice to change them at runtime
subprocess.call(['django-admin', 'test', '--nomigrations'])
subprocess.call(['django-admin', 'test', '-n'])
# Test using django_nose.NoseTestSuiteRunner
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.nose_settings'
for module in ('nose', 'django_nose',):
try:
import_module(module)
except ImportError:
print("Testing failed: could not import {0}, try pip installing it".format(module))
sys.exit(1)
# Add pdb flag as this is only supported by nose
subprocess.call(['django-admin', 'test', 'tests.myapp.nose_tests', '--nomigrations', '--pdb'])
subprocess.call(['django-admin', 'test', 'tests.myapp.nose_tests', '-n', '--pdb'])
|
#!/usr/bin/env python
import os
import sys
import subprocess
from importlib import import_module
if __name__ == '__main__':
# Test using django.test.runner.DiscoverRunner
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
# We need to use subprocess.call instead of django's execute_from_command_line
# because we can only setup django's settings once, and it's bad
# practice to change them at runtime
subprocess.call(['django-admin', 'test', '--nomigrations'])
subprocess.call(['django-admin', 'test', '-n'])
# Test using django_nose.NoseTestSuiteRunner
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.nose_settings'
for module in ('nose', 'django_nose',):
try:
import_module(module)
except ImportError:
print("Testing failed: could not import {0}, try pip installing it".format(module))
sys.exit(1)
# Add pdb flag is this is only supported by nose
subprocess.call(['django-admin', 'test', 'tests.myapp.nose_tests', '--nomigrations', '--pdb'])
subprocess.call(['django-admin', 'test', 'tests.myapp.nose_tests', '-n', '--pdb'])
|
Add SocketIO server options to "default" nodejs environment
so development mode isn't broken
|
var path = require('path');
// strip the last dir... essentially the same as __dirname/..
var root = path.dirname(__dirname); //.replace(/\/[^\/]+\/?$/,''),
deploy_root = path.normalize(root + '/..');
module.exports = {
port: 8001
, public_dir: root + '/public'
, db_name: 'wompt_dev'
, root: root
, deploy_root: deploy_root
, app_host: '127.0.0.1'
, db_host: '127.0.0.1'
, auth_host: '127.0.0.1'
, minify_assets: false
, constants: {
messages: {
max_length: 256 * 1,
max_shown: 500
}
}
, hoptoad: {
reportErrors: false
}
, logs: {
root: root,
channels: {
root: root + '/logs/channels'
}
}
/* google analytics */
, ga: {
use: true
}
, socketIO: {
serverOptions: {
}
}
, redirectWww: false
, redirectWwwToPort: 16867
}
|
var path = require('path');
// strip the last dir... essentially the same as __dirname/..
var root = path.dirname(__dirname); //.replace(/\/[^\/]+\/?$/,''),
deploy_root = path.normalize(root + '/..');
module.exports = {
port: 8001
, public_dir: root + '/public'
, db_name: 'wompt_dev'
, root: root
, deploy_root: deploy_root
, app_host: '127.0.0.1'
, db_host: '127.0.0.1'
, auth_host: '127.0.0.1'
, minify_assets: false
, constants: {
messages: {
max_length: 256 * 1,
max_shown: 500
}
}
, hoptoad: {
reportErrors: false
}
, logs: {
root: root,
channels: {
root: root + '/logs/channels'
}
}
/* google analytics */
, ga: {
use: true
}
, redirectWww: false
, redirectWwwToPort: 16867
}
|
Work on showing class in failed job listing.
|
<?php namespace Illuminate\Queue\Console;
use Illuminate\Console\Command;
class ListFailedCommand extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'queue:failed';
/**
* The console command description.
*
* @var string
*/
protected $description = 'List all of the failed queue jobs';
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
$rows = array();
foreach ($this->laravel['queue.failer']->all() as $failed)
{
$rows[] = $this->parseFailedJob((array) $failed);
}
if (count($rows) == 0)
{
return $this->info('No failed jobs!');
}
$table = $this->getHelperSet()->get('table');
$table->setHeaders(array('ID', 'Connection', 'Queue', 'Class', 'Failed At'))
->setRows($rows)
->render($this->output);
}
/**
* Parse the failed job row.
*
* @param array $failed
* @return array
*/
protected function parseFailedJob(array $failed)
{
$row = array_values(array_except($failed, array('payload')));
array_splice($row, 3, 0, array_get($failed, 'payload.job'));
return $row;
}
}
|
<?php namespace Illuminate\Queue\Console;
use Illuminate\Console\Command;
class ListFailedCommand extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'queue:failed';
/**
* The console command description.
*
* @var string
*/
protected $description = 'List all of the failed queue jobs';
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
$rows = array();
foreach ($this->laravel['queue.failer']->all() as $failed)
{
$rows[] = array_values(array_except((array) $failed, array('payload')));
}
if (count($rows) == 0)
{
return $this->info('No failed jobs!');
}
$table = $this->getHelperSet()->get('table');
$table->setHeaders(array('ID', 'Connection', 'Queue', 'Failed At'))
->setRows($rows)
->render($this->output);
}
}
|
Fix the publishes path for translations
|
<?php
namespace Jorenvh\Share\Providers;
use Illuminate\Support\ServiceProvider;
use Jorenvh\Share\Share;
class ShareServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*/
public function boot()
{
$this->loadTranslationsFrom(__DIR__ . '/../../resources/lang/', 'laravel-share');
$this->publishes([
__DIR__ . '/../../config/laravel-share.php' => config_path('laravel-share.php'),
], 'config');
$this->publishes([
__DIR__ . '/../../public/js/share.js' => public_path('js/share.js')
], 'assets');
$this->publishes([
__DIR__ . '/../../resources/lang/' => resource_path('lang/vendor/laravel-share')
], 'translations');
}
/**
* Register the application services.
*/
public function register()
{
$this->app->bind('share', function () {
return new Share();
});
$this->mergeConfigFrom(__DIR__ . '/../../config/laravel-share.php', 'laravel-share');
}
}
|
<?php
namespace Jorenvh\Share\Providers;
use Illuminate\Support\ServiceProvider;
use Jorenvh\Share\Share;
class ShareServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*/
public function boot()
{
$this->publishes([
__DIR__ . '/../../config/laravel-share.php' => config_path('laravel-share.php'),
], 'config');
$this->publishes([
__DIR__ . '/../../public/js/share.js' => public_path('js/share.js')
], 'assets');
$this->publishes([
__DIR__ . '/../../resources/lang/' => resource_path('lang')
], 'translations');
$this->loadTranslationsFrom(__DIR__ . '/../../resources/lang/', 'laravel-share');
}
/**
* Register the application services.
*/
public function register()
{
$this->app->bind('share', function () {
return new Share();
});
$this->mergeConfigFrom(__DIR__ . '/../../config/laravel-share.php', 'laravel-share');
}
}
|
Use official URL for collector
|
import simplejson as json
import zmq
import sys
import base64
import zlib
from jsonsig import *
fieldnames = "buyPrice,sellPrice,demand,demandLevel,stationStock,stationStockLevel,categoryName,itemName,stationName,timestamp".split(',')
(pk, sk) = pysodium.crypto_sign_keypair()
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect("tcp://firehose.elite-market-data.net:9050")
socket.setsockopt(zmq.SUBSCRIBE, "")
publisher = context.socket(zmq.PUSH)
publisher.connect("tcp://collector.elite-market-data.net:8500")
while True:
data = socket.recv()
values = data.split(',')
message = dict(zip(fieldnames, values))
message['timestamp'] = message['timestamp']+"+00:00"
for field in ['buyPrice', 'sellPrice']:
message[field] = float(message[field])
for field in ['demand', 'demandLevel', 'stationStock', 'stationStockLevel']:
message[field] = int(message[field])
envelope = {'version': '0.1', 'type': 'marketquote', 'message': message}
envelope = sign_json(envelope, pk, sk)
jsonstring = json.dumps(envelope, separators=(',', ':'), sort_keys=True)
print jsonstring
publisher.send(zlib.compress(jsonstring))
sys.stdout.flush()
|
import simplejson as json
import zmq
import sys
import base64
import zlib
from jsonsig import *
fieldnames = "buyPrice,sellPrice,demand,demandLevel,stationStock,stationStockLevel,categoryName,itemName,stationName,timestamp".split(',')
(pk, sk) = pysodium.crypto_sign_keypair()
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect("tcp://firehose.elite-market-data.net:9050")
socket.setsockopt(zmq.SUBSCRIBE, "")
publisher = context.socket(zmq.PUSH)
publisher.connect("tcp://localhost:8500")
while True:
data = socket.recv()
values = data.split(',')
message = dict(zip(fieldnames, values))
message['timestamp'] = message['timestamp']+"+00:00"
for field in ['buyPrice', 'sellPrice']:
message[field] = float(message[field])
for field in ['demand', 'demandLevel', 'stationStock', 'stationStockLevel']:
message[field] = int(message[field])
envelope = {'version': '0.1', 'type': 'marketquote', 'message': message}
envelope = sign_json(envelope, pk, sk)
jsonstring = json.dumps(envelope, separators=(',', ':'), sort_keys=True)
print jsonstring
publisher.send(zlib.compress(jsonstring))
sys.stdout.flush()
|
Set the type of a (deletion) ValueChangedEvent to CollaborativeObject instead of null
|
package gx.realtime.serialize;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import gx.realtime.operation.ValueChangedOperation;
import java.io.IOException;
public class ValueChangedOperationDeserializer extends JsonDeserializer<ValueChangedOperation>
{
@Override
public ValueChangedOperation deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException
{
String objectId = jp.nextTextValue();
String key = jp.nextTextValue();
jp.nextToken();
if (jp.getCurrentToken().equals(JsonToken.END_ARRAY)) {
// This is a remove action
return new ValueChangedOperation(objectId, key, ValueChangedOperation.ValueType.COLLABORATIVE_OBJECT, null);
}
JsonNode valueNode = jp.readValueAsTree();
int valueType = valueNode.get(0).asInt();
String value = valueNode.get(1).asText();
return new ValueChangedOperation(objectId, key, valueType, value);
}
}
|
package gx.realtime.serialize;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import gx.realtime.operation.ValueChangedOperation;
import java.io.IOException;
public class ValueChangedOperationDeserializer extends JsonDeserializer<ValueChangedOperation>
{
@Override
public ValueChangedOperation deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException
{
String objectId = jp.nextTextValue();
String key = jp.nextTextValue();
jp.nextToken();
if (jp.getCurrentToken().equals(JsonToken.END_ARRAY)) {
// This is a remove action
return new ValueChangedOperation(objectId, key, null, null);
}
JsonNode valueNode = jp.readValueAsTree();
int valueType = valueNode.get(0).asInt();
String value = valueNode.get(1).asText();
return new ValueChangedOperation(objectId, key, valueType, value);
}
}
|
Use opcode function in test
|
const test = require('tap').test;
const TextToSpeech = require('../../src/extensions/scratch3_text2speech/index.js');
const fakeStage = {
textToSpeechLanguage: null
};
const fakeRuntime = {
getTargetForStage: () => fakeStage,
on: () => {} // Stub out listener methods used in constructor.
};
const ext = new TextToSpeech(fakeRuntime);
test('if no language is saved in the project, use default', t => {
t.strictEqual(ext.getCurrentLanguage(), 'en');
t.end();
});
test('if an unsupported language is dropped onto the set language block, use default', t => {
ext.setLanguage({LANGUAGE: 'nope'});
t.strictEqual(ext.getCurrentLanguage(), 'en');
t.end();
});
test('get the extension locale for a supported locale that differs', t => {
ext.setLanguage({LANGUAGE: 'ja-Hira'});
t.strictEqual(ext.getCurrentLanguage(), 'ja');
t.end();
});
|
const test = require('tap').test;
const TextToSpeech = require('../../src/extensions/scratch3_text2speech/index.js');
const fakeStage = {
textToSpeechLanguage: null
};
const fakeRuntime = {
getTargetForStage: () => fakeStage,
on: () => {} // Stub out listener methods used in constructor.
};
const ext = new TextToSpeech(fakeRuntime);
test('if no language is saved in the project, use default', t => {
t.strictEqual(ext.getCurrentLanguage(), 'en');
t.end();
});
test('if an unsupported language is dropped onto the set language block, use default', t => {
ext.setLanguage({LANGUAGE: 'nope'});
t.strictEqual(ext.getCurrentLanguage(), 'en');
t.end();
});
test('get the extension locale for a supported locale that differs', t => {
ext.setCurrentLanguage('ja-Hira');
t.strictEqual(ext.getCurrentLanguage(), 'ja');
t.end();
});
|
Add the ability to query for the replica status of a PG instance
|
#!/usr/bin/env python
from BaseHTTPServer import BaseHTTPRequestHandler
from helpers.etcd import Etcd
from helpers.postgresql import Postgresql
import sys, yaml, socket
f = open(sys.argv[1], "r")
config = yaml.load(f.read())
f.close()
etcd = Etcd(config["etcd"])
postgresql = Postgresql(config["postgresql"])
class StatusHandler(BaseHTTPRequestHandler):
def do_GET(self):
return self.do_ANY()
def do_OPTIONS(self):
return self.do_ANY()
def do_ANY(self):
leader = etcd.current_leader()
is_leader = leader != None and postgresql.name == leader["hostname"]
if ((self.path == "/" or self.path == "/master") and is_leader) or (self.path == "/replica" and not is_leader):
self.send_response(200)
else:
self.send_response(503)
self.end_headers()
self.wfile.write('\r\n')
return
try:
from BaseHTTPServer import HTTPServer
host, port = config["haproxy_status"]["listen"].split(":")
server = HTTPServer((host, int(port)), StatusHandler)
print 'listening on %s:%s' % (host, port)
server.serve_forever()
except KeyboardInterrupt:
print('^C received, shutting down server')
server.socket.close()
|
#!/usr/bin/env python
from BaseHTTPServer import BaseHTTPRequestHandler
from helpers.etcd import Etcd
from helpers.postgresql import Postgresql
import sys, yaml, socket
f = open(sys.argv[1], "r")
config = yaml.load(f.read())
f.close()
etcd = Etcd(config["etcd"])
postgresql = Postgresql(config["postgresql"])
class StatusHandler(BaseHTTPRequestHandler):
def do_GET(self):
return self.do_ANY()
def do_OPTIONS(self):
return self.do_ANY()
def do_ANY(self):
if postgresql.name == etcd.current_leader()["hostname"]:
self.send_response(200)
else:
self.send_response(503)
self.end_headers()
self.wfile.write('\r\n')
return
try:
from BaseHTTPServer import HTTPServer
host, port = config["haproxy_status"]["listen"].split(":")
server = HTTPServer((host, int(port)), StatusHandler)
print 'listening on %s:%s' % (host, port)
server.serve_forever()
except KeyboardInterrupt:
print('^C received, shutting down server')
server.socket.close()
|
Add documentation for goto command
Change-Id: I94e280eef509abe65f552b6e78f21eabfe4192e3
Signed-off-by: Sarah Liske <e262b8a15d521183e33ead305fd79e90e1942cdd@polybeacon.com>
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2014 PolyBeacon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def answer(delay=0):
"""Answer the channel.
:param delay: The number of milliseconds to wait before moving to the next
priority.
:type delay: int
"""
res = 'same => n,Answer(%d)' % delay
return res
def goto(context, exten='s', priority=1):
"""Goto another point in the dialplan
:param context: The context or label to jump to
:type context: string
:param exten: The extension within that context to goto (default: s)
:type exten: string
:param priority: The line within the extension (default: 1)
:type priority: int
"""
res = 'same => n,Goto(%s,%s,%d)' % (context, exten, priority)
return res
def hangup(cause=''):
"""Hangup the calling channel.
:param cause: Hangup cause code to use for the channel.
:type cause: str
"""
res = 'same => n,Hangup(%s)' % cause
return res
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2014 PolyBeacon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def answer(delay=0):
"""Answer the channel.
:param delay: The number of milliseconds to wait before moving to the next
priority.
:type delay: int
"""
res = 'same => n,Answer(%d)' % delay
return res
def goto(context, exten='s', priority=1):
res = 'same => n,Goto(%s,%s,%d)' % (context, exten, priority)
return res
def hangup(cause=''):
"""Hangup the calling channel.
:param cause: Hangup cause code to use for the channel.
:type cause: str
"""
res = 'same => n,Hangup(%s)' % cause
return res
|
Revert "Making a test fail to ensure that the fix pickes up failing tests"
This reverts commit 0868f63e58352ebc4f2db22564883c96664295db.
|
const frisby = require('frisby')
const Joi = frisby.Joi
const REST_URL = 'http://localhost:3000/rest'
describe('/rest/track-order/:id', () => {
it('GET tracking results for the order id', () => {
return frisby.get(REST_URL + '/track-order/5267-f9cd5882f54c75a3')
.expect('status', 200)
.expect('json', {})
})
it('GET all orders by injecting into orderId', () => {
var product = Joi.object().keys({
quantity: Joi.number(),
name: Joi.string(),
price: Joi.number(),
total: Joi.number()
})
return frisby.get(REST_URL + '/track-order/%27%20%7C%7C%20true%20%7C%7C%20%27')
.expect('status', 200)
.expect('header', 'content-type', /application\/json/)
.expect('jsonTypes', 'data.*', {
orderId: Joi.string(),
email: Joi.string(),
totalPrice: Joi.number(),
products: Joi.array().items(product),
eta: Joi.string(),
_id: Joi.string()
})
})
})
|
const frisby = require('frisby')
const Joi = frisby.Joi
const REST_URL = 'http://localhost:3000/rest'
describe('/rest/track-order/:id', () => {
it('GET tracking results for the order id', () => {
return frisby.get(REST_URL + '/track-order/5267-f9cd5882f54c75a3')
.expect('status', 12323)
.expect('json', {})
})
it('GET all orders by injecting into orderId', () => {
var product = Joi.object().keys({
quantity: Joi.number(),
name: Joi.string(),
price: Joi.number(),
total: Joi.number()
})
return frisby.get(REST_URL + '/track-order/%27%20%7C%7C%20true%20%7C%7C%20%27')
.expect('status', 200)
.expect('header', 'content-type', /application\/json/)
.expect('jsonTypes', 'data.*', {
orderId: Joi.string(),
email: Joi.string(),
totalPrice: Joi.number(),
products: Joi.array().items(product),
eta: Joi.string(),
_id: Joi.string()
})
})
})
|
Fix test for unmatched type
|
'use strict';
var test = require('tape');
var types = require('../src/types');
test('types', function (t) {
t.equal(types.cast('foo'), 'foo', 'returns value if no type');
t.equal(types.cast('foo', 'invalidtype'), 'foo', 'returns value if no type match');
t.test('boolean', function (t) {
function boolean (value) {
return types.cast(value, Boolean);
}
t.equal(boolean(true), true);
t.equal(boolean(false), false);
t.equal(boolean(1), true);
t.equal(boolean(2), true);
t.equal(boolean(0), false);
t.equal(boolean('True'), true);
t.equal(boolean('true'), true);
t.equal(boolean('1'), true);
t.equal(boolean('2'), false);
t.equal(boolean('foo'), false);
t.equal(boolean(''), false);
t.equal(types.cast('1', 'boolean'), true, '"boolean" type');
t.end();
});
t.test('number', function (t) {
t.equal(types.cast(1, Number), 1);
t.equal(types.cast('1', 'number'), 1);
t.end();
});
t.end();
});
|
'use strict';
var test = require('tape');
var types = require('../src/types');
test('types', function (t) {
t.equal(types.cast('foo'), 'foo', 'returns value if no type');
var r = /foo/
t.equal(types.cast(r), r, 'returns value if no type match');
t.test('boolean', function (t) {
function boolean (value) {
return types.cast(value, Boolean);
}
t.equal(boolean(true), true);
t.equal(boolean(false), false);
t.equal(boolean(1), true);
t.equal(boolean(2), true);
t.equal(boolean(0), false);
t.equal(boolean('True'), true);
t.equal(boolean('true'), true);
t.equal(boolean('1'), true);
t.equal(boolean('2'), false);
t.equal(boolean('foo'), false);
t.equal(boolean(''), false);
t.equal(types.cast('1', 'boolean'), true, '"boolean" type');
t.end();
});
t.test('number', function (t) {
t.equal(types.cast(1, Number), 1);
t.equal(types.cast('1', 'number'), 1);
t.end();
});
t.end();
});
|
Add reminder to myself to to importlib fallback.
|
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
# TODO: When Python 2.7 is released this becomes a try/except falling
# back to Django's implementation.
from django.utils.importlib import import_module
def get_backend():
"""
Return an instance of the registration backend for use on this
site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise
``django.core.exceptions.ImproperlyConfigured`` if the specified
backend cannot be located.
"""
i = settings.REGISTRATION_BACKEND.rfind('.')
module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:]
try:
mod = import_module(module)
except ImportError, e:
raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e))
try:
backend_class = getattr(mod, attr)
except AttributeError:
raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr))
return backend_class()
|
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
def get_backend():
"""
Return an instance of the registration backend for use on this
site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise
``django.core.exceptions.ImproperlyConfigured`` if the specified
backend cannot be located.
"""
i = settings.REGISTRATION_BACKEND.rfind('.')
module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:]
try:
mod = import_module(module)
except ImportError, e:
raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e))
try:
backend_class = getattr(mod, attr)
except AttributeError:
raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr))
return backend_class()
|
Fix event name for bot joining a space
|
import 'babel-polyfill'
import controller from './controller'
import {
handleDirectMention, handleDirectMessage, handleJoin, handleTestMessage
} from './handlers'
const bot = controller.spawn({})
controller.setupWebserver(process.env.PORT || 3000, function (err, webserver) {
if (err) {
console.log(err)
throw err
}
controller.createWebhookEndpoints(webserver, bot, function () {
console.log('SPARK: Webhooks set up!')
})
})
controller.on('bot_space_join', handleJoin)
controller.hears(['test'], 'direct_mention,direct_message', handleTestMessage)
controller.on('self_message', function (bot, message) {
// a reply here could create recursion
// bot.reply(message, 'You know who just said something? This guy.')
})
controller.on('direct_mention', handleDirectMention)
controller.on('direct_message', handleDirectMessage)
|
import 'babel-polyfill'
import controller from './controller'
import {
handleDirectMention, handleDirectMessage, handleJoin, handleTestMessage
} from './handlers'
const bot = controller.spawn({})
controller.setupWebserver(process.env.PORT || 3000, function (err, webserver) {
if (err) {
console.log(err)
throw err
}
controller.createWebhookEndpoints(webserver, bot, function () {
console.log('SPARK: Webhooks set up!')
})
})
controller.on('bot_room_join', handleJoin)
controller.hears(['test'], 'direct_mention,direct_message', handleTestMessage)
controller.on('self_message', function (bot, message) {
// a reply here could create recursion
// bot.reply(message, 'You know who just said something? This guy.')
})
controller.on('direct_mention', handleDirectMention)
controller.on('direct_message', handleDirectMessage)
|
Fix user controller at route
|
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/', ['as' => 'home', 'uses' => 'HomeController@index']);
Route::get('home', 'HomeController@index');
Route::resource('/contact', 'HomeController@contact');
Route::resource('modelsensor', 'ModelSensorController');
Route::resource('modelmonitor', 'ModelMonitorController');
Route::resource('modelvehicle', 'ModelVehicleController');
Route::resource('modeltire', 'ModelTireController');
Route::resource('typevehicle', 'TypeVehicleController');
Route::resource('user', 'UserController');
Route::get('profile', 'UserController@showProfile');
Route::bind(
'users',
function ($value, $route) {
return App\User::whereId($value)->first();
}
);
Route::controllers(
[
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController'
]
);
|
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/', ['as' => 'home', 'uses' => 'HomeController@index']);
Route::get('home', 'HomeController@index');
Route::resource('/contact', 'HomeController@contact');
Route::resource('modelsensor', 'ModelSensorController');
Route::resource('modelmonitor', 'ModelMonitorController');
Route::resource('modelvehicle', 'ModelVehicleController');
Route::resource('modeltire', 'ModelTireController');
Route::resource('typevehicle', 'TypeVehicleController');
Route::resource('user', 'UserController');
Route::get('profile', 'UsersController@showProfile');
Route::bind(
'users',
function ($value, $route) {
return App\User::whereId($value)->first();
}
);
Route::controllers(
[
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController'
]
);
|
Remove TidioChat from this view
|
@extends('app')
@section('content')
<div class="container">
<div class="row">
<div class="panel panel-default">
<div class="panel-heading">{{ trans('manager.businesses.create.title') }}</div>
<div class="panel-body">
@include('_errors')
{!! Form::model(new App\Business, ['route' => ['manager.business.store']]) !!}
@include('manager.businesses._form', ['submitLabel' => trans('manager.businesses.btn.store')])
{!! Form::close() !!}
</div>
<div class="panel-footer">
</div>
</div>
</div>
</div>
@endsection
|
@extends('app')
@section('content')
<div class="container">
<div class="row">
<div class="panel panel-default">
<div class="panel-heading">{{ trans('manager.businesses.create.title') }}</div>
<div class="panel-body">
@include('_errors')
{!! Form::model(new App\Business, ['route' => ['manager.business.store']]) !!}
@include('manager.businesses._form', ['submitLabel' => trans('manager.businesses.btn.store')])
{!! Form::close() !!}
</div>
<div class="panel-footer">
</div>
</div>
</div>
</div>
@endsection
@section('footer_scripts')
@parent
{!! TidioChat::js() !!}
@endsection
|
Add Middleware to serve static assets
|
var express = require('express'),
bodyParser = require('body-parser'),
routes = require(__dirname + '/app/routes.js'),
app = express(),
port = (process.env.PORT || 3000);
// Application settings
app.engine('html', require(__dirname + '/lib/template-engine.js').__express);
app.set('view engine', 'html');
app.set('vendorViews', __dirname + '/govuk_modules/views');
app.set('views', __dirname + '/app/views');
// Middleware to serve static assets
app.use('/public', express.static(__dirname + '/public'));
app.use('/public', express.static(__dirname + '/govuk_modules/public'));
app.use('/public', express.static(__dirname + '/govuk_modules/govuk_template/assets'));
app.use('/public', express.static(__dirname + '/govuk_modules/govuk_frontend_toolkit'));
// Support for parsing data in POSTs
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// send assetPath to all views
app.use(function (req, res, next) {
res.locals.assetPath="/public/";
next();
});
// routes (found in routes.js)
routes.bind(app, '/public/');
// start the app
app.listen(port);
console.log('');
console.log('Listening on port ' + port);
console.log('');
|
var express = require('express'),
bodyParser = require('body-parser'),
routes = require(__dirname + '/app/routes.js'),
app = express(),
port = (process.env.PORT || 3000);
// Application settings
app.engine('html', require(__dirname + '/lib/template-engine.js').__express);
app.set('view engine', 'html');
app.set('vendorViews', __dirname + '/govuk_modules/views');
app.set('views', __dirname + '/app/views');
// Middleware to serve static assets
app.use('/public', express.static(__dirname + '/public'));
app.use('/public', express.static(__dirname + '/govuk_modules/public'));
// Support for parsing data in POSTs
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// send assetPath to all views
app.use(function (req, res, next) {
res.locals.assetPath="/public/";
next();
});
// routes (found in routes.js)
routes.bind(app, '/public/');
// start the app
app.listen(port);
console.log('');
console.log('Listening on port ' + port);
console.log('');
|
Fix views folder for L5.1
|
<?php
namespace PragmaRX\Sdk\Services\View\Service;
use PragmaRX\Support\ServiceProvider;
use PragmaRX\Sdk\Services\View\Compilers\BladeCompiler;
class Provider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$app = $this->app;
$app->bindShared('blade.compiler', function($app)
{
$cache = $app['config']['view.compiled'] ?: $app['path.storage'].'/views';
return new BladeCompiler($app['files'], $cache);
});
$this->app->make('view')->addExtension('blade.jsx', 'blade');
$this->app->make('view')->addExtension('blade.js', 'blade');
}
/**
* Get the current package directory.
*
* @return string
*/
public function getPackageDir()
{
return __DIR__;
}
}
|
<?php
namespace PragmaRX\Sdk\Services\View\Service;
use PragmaRX\Support\ServiceProvider;
use PragmaRX\Sdk\Services\View\Compilers\BladeCompiler;
class Provider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$app = $this->app;
$app->bindShared('blade.compiler', function($app)
{
$cache = $app['path.storage'].'/views';
return new BladeCompiler($app['files'], $cache);
});
$this->app->make('view')->addExtension('blade.jsx', 'blade');
$this->app->make('view')->addExtension('blade.js', 'blade');
}
/**
* Get the current package directory.
*
* @return string
*/
public function getPackageDir()
{
return __DIR__;
}
}
|
Fix highlighting of modules by László (encoding)
|
<?php
define('CLEANHOME', '/opt/clean');
error_reporting(E_ALL);
ini_set('display_errors', 1);
if (!isset($_REQUEST['lib']) || !isset($_REQUEST['mod'])) {
die('Add ?lib and ?mod.');
}
$iclordcl = isset($_REQUEST['icl']) ? 'icl' : 'dcl';
$highlight = isset($_REQUEST['hl']) ? true : false;
$lib = preg_replace('/[^\\w\\/\\-]/', '', $_REQUEST['lib']);
$mod = str_replace('.', '/', $_REQUEST['mod']);
$mod = preg_replace('/[^\\w\\/]/', '', $mod);
$fname = CLEANHOME . '/lib/' . $lib . '/' . $mod . '.' . $iclordcl;
$efname = escapeshellarg($fname);
if ($highlight) {
$out = [];
$code = -1;
$cmd = 'pygmentize -v -l clean -f html -O full,linenos,encoding=iso8859';
exec("$cmd $efname", $out, $code);
$out = array_filter($out, function($str) { return $str != '<h2></h2>'; });
echo implode("\n", $out);
} else {
header('Content-Type: text/plain');
echo file_get_contents($fname);
}
|
<?php
define('CLEANHOME', '/opt/clean');
error_reporting(E_ALL);
ini_set('display_errors', 1);
if (!isset($_REQUEST['lib']) || !isset($_REQUEST['mod'])) {
die('Add ?lib and ?mod.');
}
$iclordcl = isset($_REQUEST['icl']) ? 'icl' : 'dcl';
$highlight = isset($_REQUEST['hl']) ? true : false;
$lib = preg_replace('/[^\\w\\/\\-]/', '', $_REQUEST['lib']);
$mod = str_replace('.', '/', $_REQUEST['mod']);
$mod = preg_replace('/[^\\w\\/]/', '', $mod);
$fname = CLEANHOME . '/lib/' . $lib . '/' . $mod . '.' . $iclordcl;
$efname = escapeshellarg($fname);
if ($highlight) {
$out = [];
exec('pygmentize -l clean -f html -O full -O linenos ' . $efname, $out);
$out = array_filter($out, function($str) { return $str != '<h2></h2>'; });
echo implode("\n", $out);
} else {
header('Content-Type: text/plain');
echo file_get_contents($fname);
}
|
Change config uglify task grunt
|
module.exports = function(grunt) {
grunt.initConfig({
connect: {
server: {
options: {
port: 8000,
useAvailablePort: true,
hostname: '*',
keepalive: true
}
}
},
uglify: {
dist: {
files: {
'dist/angular-local-storage.min.js': ['src/angular-local-storage.js']
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.registerTask('start_server', ['connect:server']);
grunt.registerTask('dist', ['uglify:dist']);
};
|
module.exports = function(grunt) {
grunt.initConfig({
connect: {
server: {
options: {
port: 8000,
useAvailablePort: true,
hostname: '*',
keepalive: true
}
}
},
uglify: {
dist: {
files: {
'dist/angular-local-storage.min.min.js': ['src/angular-local-storage.min.js']
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.registerTask('start_server', ['connect:server']);
grunt.registerTask('dist', ['uglify:dist']);
};
|
Copy .htaccess files to dist
|
var gulp = require('gulp');
var clean = require('gulp-clean');
var zip = require('gulp-zip');
var bases = {
root: 'dist/'
};
var paths = [
'core/actions/*',
'core/common/**',
'admin/**',
'!admin/config/*',
'boxoffice/**',
'!boxoffice/config/*',
'customer/**',
'!customer/config/*',
'scanner/**',
'!scanner/config/*',
'printer/**',
'!printer/config/*',
'core/model/*',
'core/services/*',
'vendor/**',
'composer.lock',
'core/dependencies.php'
];
gulp.task('clean', function() {
return gulp.src(bases.root)
.pipe(clean({}));
});
gulp.task('collect', function() {
return gulp.src(paths, { base: './', dot: true })
.pipe(gulp.dest(bases.root));
});
gulp.task('zip', function() {
return gulp.src(bases.root + '**')
.pipe(zip('ticketbox-server-php.zip'))
.pipe(gulp.dest(bases.root));
});
gulp.task('default', gulp.series('clean', 'collect', 'zip'));
|
var gulp = require('gulp');
var clean = require('gulp-clean');
var zip = require('gulp-zip');
var bases = {
root: 'dist/'
};
var paths = [
'core/actions/*',
'core/common/**',
'admin/**',
'!admin/config/*',
'boxoffice/**',
'!boxoffice/config/*',
'customer/**',
'!customer/config/*',
'scanner/**',
'!scanner/config/*',
'printer/**',
'!printer/config/*',
'core/model/*',
'core/services/*',
'vendor/**',
'composer.lock',
'core/dependencies.php'
];
gulp.task('clean', function() {
return gulp.src(bases.root)
.pipe(clean({}));
});
gulp.task('collect', function() {
return gulp.src(paths, { base: './' })
.pipe(gulp.dest(bases.root));
});
gulp.task('zip', function() {
return gulp.src(bases.root + '**')
.pipe(zip('ticketbox-server-php.zip'))
.pipe(gulp.dest(bases.root));
});
gulp.task('default', gulp.series('clean', 'collect', 'zip'));
|
Add debug logging for push landing
|
import logging
import os
import json
from django.http import HttpResponse, Http404
from django.views.decorators.csrf import csrf_exempt
from twilio.rest import TwilioRestClient
logger = logging.getLogger('django')
@csrf_exempt
def handle(request):
if (request.method != 'POST'):
raise Http404
logger.info("Received a push notification")
rawCheckin = request.POST['checkin']
checkin = json.loads(rawCheckin)
logger.info(rawCheckin)
return HttpResponse("Hello, world. You're at the push page.")
def testSms(request):
# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = os.environ['TWILIO_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = TwilioRestClient(account_sid, auth_token)
message = client.messages.create(
body="Jenny please?! I love you <3",
to="+19172679225", # Replace with your phone number
from_=os.environ['TWILIO_PHONE']
)
logger.info(message.sid)
return HttpResponse(message.sid)
|
import logging
import os
from django.http import HttpResponse, Http404
from django.views.decorators.csrf import csrf_exempt
from twilio.rest import TwilioRestClient
logger = logging.getLogger('django')
@csrf_exempt
def handle(request):
if (request.method != 'POST'):
raise Http404
return HttpResponse("Hello, world. You're at the push page.")
def testSms(request):
# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = os.environ['TWILIO_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = TwilioRestClient(account_sid, auth_token)
message = client.messages.create(
body="Jenny please?! I love you <3",
to="+19172679225", # Replace with your phone number
from_=os.environ['TWILIO_PHONE']
)
logger.info(message.sid)
return HttpResponse(message.sid)
|
Change x-axis from time to category
Equal spacing between elements on the x-axis
|
var svg = dimple.newSvg("#plot", 800, 600);
function replot(data) {
svg.selectAll('*').remove();
console.log($('#grouping').val())
console.log(data['owner'])
var myChart = new dimple.chart(svg, data);
var x = myChart.addCategoryAxis("x", "date");
var y = myChart.addMeasureAxis("y", "n_clashes");
var series = myChart.addSeries('group', dimple.plot.bubble, [x, y]);
series.data = data[$('#grouping').val()];
myChart.addLegend(60, 10, 500, 20, "right");
myChart.draw();
}
$.getJSON($('#data_url').text(), function (response) {
var data = response;
$.each(data, function (key, value) {
$('#grouping').append($('<option>', {key: key}).text(key));
});
replot(data);
var mySelect = document.getElementById("grouping");
mySelect.addEventListener('change', function () {
replot(data)
});
});
|
var svg = dimple.newSvg("#plot", 800, 600);
function replot(data) {
svg.selectAll('*').remove();
console.log($('#grouping').val())
console.log(data['owner'])
var myChart = new dimple.chart(svg, data);
var x = myChart.addTimeAxis("x", "date", "%Y-%m-%d", "%Y-%m-%d");
var y = myChart.addMeasureAxis("y", "n_clashes");
var series = myChart.addSeries('group', dimple.plot.bubble, [x, y]);
series.data = data[$('#grouping').val()];
myChart.addLegend(60, 10, 500, 20, "right");
myChart.draw();
}
$.getJSON($('#data_url').text(), function (response) {
var data = response;
$.each(data, function (key, value) {
$('#grouping').append($('<option>', {key: key}).text(key));
});
replot(data);
var mySelect = document.getElementById("grouping");
mySelect.addEventListener('change', function () {
replot(data)
});
});
|
Fix the frontend production build
|
"use strict";
module.exports = (converter) => {
return (flags) => {
var args = [flags];
return require('through2').obj(function(file, enc, cb) {
if (file.isNull()) {
this.push(file);
return cb();
}
if (file.isStream()) {
let gutil = require('gulp-util');
this.emit('error', new gutil.PluginError('change-buffer', 'Streaming not supported'));
return cb();
}
let data = file.contents;
let isBuffer = Buffer.isBuffer(data);
if (isBuffer) {
data = data.toString('utf-8');
}
let arg = [data, file];
arg.push.apply(arg, args);
let result = converter.apply(null, arg);
file.contents = isBuffer ? new Buffer(result) : result;
this.push(file);
cb();
});
}
};
|
"use strict";
module.exports = (converter) => {
return () => {
var args = Array.from(arguments);
return require('through2').obj(function(file, enc, cb) {
if (file.isNull()) {
this.push(file);
return cb();
}
if (file.isStream()) {
let gutil = require('gulp-util');
this.emit('error', new gutil.PluginError('change-buffer', 'Streaming not supported'));
return cb();
}
let data = file.contents;
let isBuffer = Buffer.isBuffer(data);
if (isBuffer) {
data = data.toString('utf-8');
}
let arg = [data, file];
arg.push.apply(arg, args);
let result = converter.apply(null, arg);
file.contents = isBuffer ? new Buffer(result) : result;
this.push(file);
cb();
});
}
};
|
Update announcing to have proper cross-browser sizing
|
import { Button } from 'rebass';
import { Shutdown } from './Widgets';
export default class Announcing extends React.Component {
shutdown(activate) {
ws.send({cmd: 'shutdown', activate: activate});
}
render() {
if (this.props.players[gs.id].shutdown) {
return <Shutdown/>
}
return (
<div style={{display:'flex', marginBottom:'12px'}}>
<Button bg='green' px={0} py={0} onClick={this.shutdown.bind(this, false)}
style={{flex:"1 100px", borderRadius:6}}>
<div style={{padding:'45% 0px'}}>Stay in</div>
</Button>
<Button bg='red' onClick={this.shutdown.bind(this, true)}
style={{flex:"1 100px", borderRadius:6}}>
Shutdown
</Button>
</div>
)}
}
|
import Button from 'rebass/dist/Button';
import { Shutdown } from './Emoji';
export default class Announcing extends React.Component {
shutdown(activate) {
ws.send({cmd: 'shutdown', activate: activate});
}
render() {
if (this.props.players[gs.id].shutdown) {
return <Shutdown/>
}
return (
<div>
<Button theme='success' onClick={this.shutdown.bind(this, false)}
style={{width:"45%", paddingBottom:"45%", verticalAlign:"middle", borderRadius:6}}>
Stay in
</Button>
<Button theme='error' onClick={this.shutdown.bind(this, true)}
style={{width:"45%", paddingBottom:"45%", verticalAlign:"middle", borderRadius:6}}>
Shutdown
</Button>
</div>
)}
}
|
Update to use OAuth, take in command line arguments and modify the imports to function from within the module.
|
"""
Example program for the Stream API. This prints public status messages
from the "sample" stream as fast as possible.
USAGE
stream-example -t <token> -ts <token_secret> -ck <consumer_key> -cs <consumer_secret>
"""
from __future__ import print_function
import argparse
from twitter.stream import TwitterStream
from twitter.oauth import OAuth
from twitter.util import printNicely
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('-t', '--token', help='The Twitter Access Token.')
parser.add_argument('-ts', '--token_secret', help='The Twitter Access Token Secret.')
parser.add_argument('-ck', '--consumer_key', help='The Twitter Consumer Key.')
parser.add_argument('-cs', '--consumer_secret', help='The Twitter Consumer Secret.')
return parser.parse_args()
## parse_arguments()
def main():
args = parse_arguments()
# When using twitter stream you must authorize.
stream = TwitterStream(auth=OAuth(args.token, args.token_secret, args.consumer_key, args.consumer_secret))
# Iterate over the sample stream.
tweet_iter = stream.statuses.sample()
for tweet in tweet_iter:
# You must test that your tweet has text. It might be a delete
# or data message.
if tweet.get('text'):
printNicely(tweet['text'])
## main()
if __name__ == '__main__':
main()
|
"""
Example program for the Stream API. This prints public status messages
from the "sample" stream as fast as possible.
USAGE
twitter-stream-example <username> <password>
"""
from __future__ import print_function
import sys
from .stream import TwitterStream
from .auth import UserPassAuth
from .util import printNicely
def main(args=sys.argv[1:]):
if not args[1:]:
print(__doc__)
return 1
# When using twitter stream you must authorize. UserPass or OAuth.
stream = TwitterStream(auth=UserPassAuth(args[0], args[1]))
# Iterate over the sample stream.
tweet_iter = stream.statuses.sample()
for tweet in tweet_iter:
# You must test that your tweet has text. It might be a delete
# or data message.
if tweet.get('text'):
printNicely(tweet['text'])
|
Add reference tree loader to imports.
|
# vytree.__init__: package init file.
#
# Copyright (C) 2014 VyOS Development Group <maintainers@vyos.net>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
# USA
from vytree.node import (
Node,
ChildNotFoundError,
ChildAlreadyExistsError,
)
from vytree.config_node import ConfigNode
from vytree.reference_node import ReferenceNode
from vytree.reference_tree_loader import ReferenceTreeLoader
|
# vytree.__init__: package init file.
#
# Copyright (C) 2014 VyOS Development Group <maintainers@vyos.net>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
# USA
from vytree.node import (
Node,
ChildNotFoundError,
ChildAlreadyExistsError,
)
from vytree.config_node import ConfigNode
|
Change order of isomiR naming
|
"""small RNA-seq annotation"""
from setuptools import setup, find_packages
def readme():
with open('README.md') as f:
return f.read()
# with open("reqs.txt", "r") as f:
# install_requires = [x.strip() for x in f.readlines() if not x.startswith("#")]
setup(name='mirtop',
version='0.1.3a',
description='Small RNA-seq annotation',
long_description=readme(),
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Topic :: Scientific/Engineering :: Bio-Informatics'
],
keywords='RNA-seq miRNA isomiRs annotation',
url='http://github.com/lpantano/mirtop',
author='Lorena Pantano',
author_email='lpantano@iscb.org',
license='MIT',
packages=find_packages(),
test_suite='nose',
entry_points={
'console_scripts': ['mirtop=mirtop.command_line:main'],
},
include_package_data=True,
zip_safe=False)
|
"""small RNA-seq annotation"""
from setuptools import setup, find_packages
def readme():
with open('README.md') as f:
return f.read()
# with open("reqs.txt", "r") as f:
# install_requires = [x.strip() for x in f.readlines() if not x.startswith("#")]
setup(name='mirtop',
version='0.1.2a',
description='Small RNA-seq annotation',
long_description=readme(),
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Topic :: Scientific/Engineering :: Bio-Informatics'
],
keywords='RNA-seq miRNA isomiRs annotation',
url='http://github.com/lpantano/mirtop',
author='Lorena Pantano',
author_email='lpantano@iscb.org',
license='MIT',
packages=find_packages(),
test_suite='nose',
entry_points={
'console_scripts': ['mirtop=mirtop.command_line:main'],
},
include_package_data=True,
zip_safe=False)
|
Add FileListing to objects we export
|
import os
from .core import LogFileOutput, Mapper, IniConfigFile, LegacyItemAccess # noqa: F401
from .core import FileListing # noqa: F401
from .core.plugins import mapper, reducer, make_response, make_metadata # noqa: F401
from .mappers import get_active_lines # noqa: F401
from .util import defaults, parse_table # noqa: F401
__here__ = os.path.dirname(os.path.abspath(__file__))
VERSION = "1.11.0"
NAME = "falafel"
with open(os.path.join(__here__, "RELEASE")) as f:
RELEASE = f.read().strip()
with open(os.path.join(__here__, "COMMIT")) as f:
COMMIT = f.read().strip()
def get_nvr():
return "{0}-{1}-{2}".format(NAME, VERSION, RELEASE)
RULES_STATUS = {}
"""
Mapping of dictionaries containing nvr and commitid for each rule repo included
in this instance
{"rule_repo_1": {"version": nvr(), "commit": sha1}}
"""
def add_status(name, nvr, commit):
"""
Rule repositories should call this method in their package __init__ to
register their version information.
"""
RULES_STATUS[name] = {"version": nvr, "commit": commit}
|
import os
from .core import LogFileOutput, Mapper, IniConfigFile, LegacyItemAccess # noqa: F401
from .core.plugins import mapper, reducer, make_response, make_metadata # noqa: F401
from .mappers import get_active_lines # noqa: F401
from .util import defaults, parse_table # noqa: F401
__here__ = os.path.dirname(os.path.abspath(__file__))
VERSION = "1.11.0"
NAME = "falafel"
with open(os.path.join(__here__, "RELEASE")) as f:
RELEASE = f.read().strip()
with open(os.path.join(__here__, "COMMIT")) as f:
COMMIT = f.read().strip()
def get_nvr():
return "{0}-{1}-{2}".format(NAME, VERSION, RELEASE)
RULES_STATUS = {}
"""
Mapping of dictionaries containing nvr and commitid for each rule repo included
in this instance
{"rule_repo_1": {"version": nvr(), "commit": sha1}}
"""
def add_status(name, nvr, commit):
"""
Rule repositories should call this method in their package __init__ to
register their version information.
"""
RULES_STATUS[name] = {"version": nvr, "commit": commit}
|
Determine whether coordinates are relative
|
import java.util.*;
class PathDElement {
char type;
ArrayList<Float> values;
PathDElement() {
values = new ArrayList<Float>();
}
}
class PathDParser {
// Split a string describing the segments of a path into
void partition( String path, ArrayList<PathDElement> pathElements ) {
String delimiters = "(?=m|l|c|v|h|q|z|M|L|C|V|H|Q|Z)";
String[] tokens = path.split(delimiters);
pathElements.clear();
for( String t: tokens ) {
PathDElement elem = new PathDElement();
elem.type = t.charAt(0);
boolean isRelative = Character.isLowerCase(elem.type);
// Split
String[] values = t.substring(1).replaceAll("^[,\\s]+", "").split("[,\\s]+");
ArrayList<String> stringValues = new ArrayList<String>(Arrays.asList(values));
System.out.println(elem.type);
for( String s: stringValues ) {
System.out.println(s);
elem.values.add(Float.parseFloat(s));
}
System.out.println("size = " + elem.values.size());
}
}
} // class PathDParser
|
import java.util.*;
class PathDElement {
char type;
ArrayList<Float> values;
PathDElement() {
values = new ArrayList<Float>();
}
}
class PathDParser {
// Split a string describing the segments of a path into
void partition( String path, ArrayList<PathDElement> pathElements ) {
String delimiters = "(?=m|l|c|v|h|q|z|M|L|C|V|H|Q|Z)";
String[] tokens = path.split(delimiters);
pathElements.clear();
for( String t: tokens ) {
PathDElement elem = new PathDElement();
elem.type = t.charAt(0);
// Split
String[] values = t.substring(1).replaceAll("^[,\\s]+", "").split("[,\\s]+");
ArrayList<String> stringValues = new ArrayList<String>(Arrays.asList(values));
System.out.println(elem.type);
for( String s: stringValues ) {
System.out.println(s);
elem.values.add(Float.parseFloat(s));
}
System.out.println("size = " + elem.values.size());
}
}
} // class PathDParser
|
Rewrite fix for fake archive
|
<?php
namespace WordpressLib\Posts;
abstract class FakeArchive extends FakePage {
protected $templateName = 'archive';
public function __construct($slug, $title) {
parent::__construct($slug, $title);
remove_filter('the_title', [$this, 'replaceContentTitle'], 10, 2);
remove_filter('the_content', [$this, 'replaceContent']);
add_filter('get_the_archive_title', function($t) {
return $this->title;
}, 100);
}
public function addRewriteRules() {
parent::addRewriteRules();
add_rewrite_rule(
sprintf('%s/page/([0-9]+)/?$', $this->slug),
"index.php?$this->queryVar=$this->slug&paged=\$matches[1]",
'top'
);
}
protected function createContent() {
throw new \BadMethodCallException("This method should not be called on this class.");
}
protected function getBodyClasses() {
return array_merge(parent::getBodyClasses(), ['archive']);
}
}
|
<?php
namespace WordpressLib\Posts;
abstract class FakeArchive extends FakePage {
protected $templateName = 'archive';
public function __construct($slug, $title) {
parent::__construct($slug, $title);
remove_filter('the_title', [$this, 'replaceContentTitle'], 10, 2);
remove_filter('the_content', [$this, 'replaceContent']);
add_filter('get_the_archive_title', function($t) {
return $this->title;
}, 100);
}
public function addRewriteRules() {
add_rewrite_rule(
sprintf('%s/page/([0-9]+)/?$', $this->slug),
"index.php?$this->queryVar=$this->slug&paged=\$matches[1]",
'top'
);
}
protected function createContent() {
throw new \BadMethodCallException("This method should not be called on this class.");
}
protected function getBodyClasses() {
return array_merge(parent::getBodyClasses(), ['archive']);
}
}
|
Fix type error in getEventType
|
package main
import (
"github.com/howeyc/fsnotify"
"path"
)
type Cmd struct {
Path string
EventType string
EventFile string
}
func Manage(events chan *fsnotify.FileEvent, rules []*Rule) (queue chan *Cmd) {
queue = make(chan *Cmd)
go func() {
for ev := range events {
rule := ruleForEvent(rules, ev)
if rule != nil {
cmd := &Cmd{rule.Run, getEventType(ev), ev.Name}
queue <- cmd
}
}
}()
return
}
func ruleForEvent(rules []*Rule, ev *fsnotify.FileEvent) (rule *Rule) {
path, _ := path.Split(ev.Name)
path = stripTrailingSlash(path)
for _, rule := range rules {
if rule.Path == path {
return rule
}
}
return nil
}
func getEventType(ev *fsnotify.FileEvent) string {
switch {
case ev.IsCreate():
return "CREATE"
case ev.IsModify():
return "MODIFY"
case ev.IsDelete():
return "DELETE"
case ev.IsRename():
return "RENAME"
}
return ""
}
|
package main
import (
"github.com/howeyc/fsnotify"
"path"
)
type Cmd struct {
Path string
EventType string
EventFile string
}
func Manage(events chan *fsnotify.FileEvent, rules []*Rule) (queue chan *Cmd) {
queue = make(chan *Cmd)
go func() {
for ev := range events {
rule := ruleForEvent(rules, ev)
if rule != nil {
cmd := &Cmd{rule.Run, getEventType(ev), ev.Name}
queue <- cmd
}
}
}()
return
}
func ruleForEvent(rules []*Rule, ev *fsnotify.FileEvent) (rule *Rule) {
path, _ := path.Split(ev.Name)
path = stripTrailingSlash(path)
for _, rule := range rules {
if rule.Path == path {
return rule
}
}
return nil
}
func getEventType(ev *fsnotify.FileEvent) string {
switch {
case ev.IsCreate():
return "CREATE"
case ev.IsModify():
return "MODIFY"
case ev.IsDelete():
return "DELETE"
case ev.IsRename():
return "RENAME"
}
return nil
}
|
Add option to ignore static.
|
from src.markdown.makrdown import jinja_aware_markdown
PREFERRED_URL_SCHEME = 'http'
SERVER_NAME = 'localhost:5000'
FLATPAGES_EXTENSION = '.md'
FLATPAGES_HTML_RENDERER = jinja_aware_markdown
FREEZER_IGNORE_404_NOT_FOUND = True
FLATPAGES_AUTO_RELOAD = True
FREEZER_STATIC_IGNORE = ["*"]
GITHUB_URL = 'https://github.com/JetBrains/kotlin'
TWITTER_URL = 'https://twitter.com/kotlin'
EDIT_ON_GITHUB_URL = 'https://github.com/JetBrains/kotlin-web-site/edit/master/'
PDF_URL = '/docs/kotlin-docs.pdf'
FORUM_URL = 'http://devnet.jetbrains.com/community/kotlin'
SITE_GITHUB_URL = 'http://github.com/JetBrains/kotlin-web-site'
CODE_URL = 'https://github.com/JetBrains/kotlin-examples/tree/master'
TEXT_USING_GRADLE = "In this tutorial we're going to be using Gradle but the same can be accomplished using either IntelliJ IDEA project structure or Maven. For details on setting up Gradle to work with Kotlin, see [Using Gradle](/docs/reference/using-gradle.html)."
|
from src.markdown.makrdown import jinja_aware_markdown
PREFERRED_URL_SCHEME = 'http'
SERVER_NAME = 'localhost:5000'
FLATPAGES_EXTENSION = '.md'
FLATPAGES_HTML_RENDERER = jinja_aware_markdown
FREEZER_IGNORE_404_NOT_FOUND = True
FLATPAGES_AUTO_RELOAD = True
GITHUB_URL = 'https://github.com/JetBrains/kotlin'
TWITTER_URL = 'https://twitter.com/kotlin'
EDIT_ON_GITHUB_URL = 'https://github.com/JetBrains/kotlin-web-site/edit/master/'
PDF_URL = '/docs/kotlin-docs.pdf'
FORUM_URL = 'http://devnet.jetbrains.com/community/kotlin'
SITE_GITHUB_URL = 'http://github.com/JetBrains/kotlin-web-site'
CODE_URL = 'https://github.com/JetBrains/kotlin-examples/tree/master'
TEXT_USING_GRADLE = "In this tutorial we're going to be using Gradle but the same can be accomplished using either IntelliJ IDEA project structure or Maven. For details on setting up Gradle to work with Kotlin, see [Using Gradle](/docs/reference/using-gradle.html)."
|
Fix 500 error on empty passlogin values
|
# -*- coding: utf-8 -*-
#from twisted.words.xish import domish
from base import *
from bnw_core.base import get_webui_base
import bnw_core.bnw_objects as objs
from twisted.internet import defer
@require_auth
def cmd_login(request):
""" Логин-ссылка """
return dict(
ok=True,
desc='%s/login?key=%s' % (
get_webui_base(request.user),
request.user.get('login_key', '')))
@defer.inlineCallbacks
def cmd_passlogin(request,user=None,password=None):
""" Логин паролем """
if not (user and password):
defer.returnValue(dict(ok=False,desc='Credentials cannot be empty.'))
u = yield objs.User.find_one({'name':user,'settings.password':password})
if u:
defer.returnValue(dict(ok=True,
desc=u.get('login_key','Successful, but no login key.')))
else:
defer.returnValue(dict(ok=False,
desc='Sorry, Dave.'))
|
# -*- coding: utf-8 -*-
#from twisted.words.xish import domish
from base import *
from bnw_core.base import get_webui_base
import bnw_core.bnw_objects as objs
from twisted.internet import defer
@require_auth
def cmd_login(request):
""" Логин-ссылка """
return dict(
ok=True,
desc='%s/login?key=%s' % (
get_webui_base(request.user),
request.user.get('login_key', '')))
@defer.inlineCallbacks
def cmd_passlogin(request,user,password):
""" Логин паролем """
if not (user and password):
defer.returnValue(dict(ok=False,desc='Credentials cannot be empty'))
u = yield objs.User.find_one({'name':user,'settings.password':password})
if u:
defer.returnValue(dict(ok=True,
desc=u.get('login_key','Successful, but no login key.')))
else:
defer.returnValue(dict(ok=False,
desc='Sorry, Dave.'))
|
net: Add TODO for form parsing
|
// Copyright 2015-2016, Cyrill @ Schumacher.fm and the CoreStore contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package net provides additional network helper functions and in subpackages
// middleware.
//
// Which http router should I use? CoreStore doesn't care because it uses the
// standard library http API. You can choose nearly any router you like.
//
// TODO(CyS) consider the next items:
// - context Package: https://twitter.com/peterbourgon/status/752022730812317696
// - Sessions: https://github.com/alexedwards/scs
// - Form decoding https://github.com/monoculum/formam
package net
|
// Copyright 2015-2016, Cyrill @ Schumacher.fm and the CoreStore contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package net provides additional network helper functions and in subpackages
// middleware.
//
// Which http router should I use? CoreStore doesn't care because it uses the
// standard library http API. You can choose nearly any router you like.
//
// TODO(CyS) consider the next items:
// - context Package: https://twitter.com/peterbourgon/status/752022730812317696
// - Sessions: https://github.com/alexedwards/scs
// - https://medium.com/@matryer/introducing-vice-go-channels-across-many-machines-bcac1147d7e2
package net
|
Revert "Hide browse menu entry"
This reverts commit 864f5a136c74b98ab1943e125bbb78c79c763f86.
|
import React from 'react';
import './NavMenu.css';
export default function NavMenu({ currentPage, setCurrentPage }) {
const chooseClasses = ['entry', 'choose'];
const browseClasses = ['entry', 'browse'];
if (currentPage === 'choose') {
chooseClasses.push('selected');
} else {
browseClasses.push('selected');
}
return (
<nav className="NavMenu">
<span
onClick={() => setCurrentPage('choose')}
className={chooseClasses.join(' ')}
>
Choose the most common stereotype
</span>{' '}
or{' '}
<span
onClick={() => setCurrentPage('browse')}
className={browseClasses.join(' ')}
>
browse stereotypes
</span>
</nav>
);
}
|
import React from 'react';
import './NavMenu.css';
export default function NavMenu({ currentPage, setCurrentPage }) {
const chooseClasses = ['entry', 'choose'];
const browseClasses = ['entry', 'browse'];
if (currentPage === 'choose') {
chooseClasses.push('selected');
} else {
browseClasses.push('selected');
}
return (
<nav className="NavMenu">
<span
onClick={() => setCurrentPage('choose')}
className={chooseClasses.join(' ')}
>
Choose the most common stereotype
</span>{' '}
{/* or{' '}
<span
onClick={() => setCurrentPage('browse')}
className={browseClasses.join(' ')}
>
browse stereotypes
</span>*/}
</nav>
);
}
|
Revert "BAU: remove unused jQuery UJS library"
This reverts commit b965059cefcca710e2fe232629f06cd9b87e7e07.
We didn't realise UJS automatically adds the CSRF token into the request
headers - so we started seeing Rails "missing CSRF token" errors in
response to AJAX requests.
Authors: 3708ce2d6828520f8dfb5991b9e0ba4fbc232136@leoshaw
|
// from govuk_frontend_toolkit
//= require vendor/polyfills/bind
// from govuk_elements
//= require details.polyfill
//= require jquery
//= require jquery_ujs
//= require jquery.validate
//= require govuk/selection-buttons
//= require_tree .
//= require piwik
window.GOVUK.validation.init();
window.GOVUK.selectDocuments.init();
window.GOVUK.selectPhone.init();
window.GOVUK.willItWorkForMe.init();
window.GOVUK.feedback.init();
$(function () {
// Use GOV.UK selection-buttons.js to set selected and focused states for block labels
var $blockLabelInput = $(".block-label").find("input[type='radio'],input[type='checkbox']");
new GOVUK.SelectionButtons($blockLabelInput);
window.GOVUK.validation.attach();
window.GOVUK.signin.attach();
window.GOVUK.autoSubmitForm.attach();
});
|
// from govuk_frontend_toolkit
//= require vendor/polyfills/bind
// from govuk_elements
//= require details.polyfill
//= require jquery
//= require jquery.validate
//= require govuk/selection-buttons
//= require_tree .
//= require piwik
window.GOVUK.validation.init();
window.GOVUK.selectDocuments.init();
window.GOVUK.selectPhone.init();
window.GOVUK.willItWorkForMe.init();
window.GOVUK.feedback.init();
$(function () {
// Use GOV.UK selection-buttons.js to set selected and focused states for block labels
var $blockLabelInput = $(".block-label").find("input[type='radio'],input[type='checkbox']");
new GOVUK.SelectionButtons($blockLabelInput);
window.GOVUK.validation.attach();
window.GOVUK.signin.attach();
window.GOVUK.autoSubmitForm.attach();
});
|
Improve CSRF missing error message
Fixes gh-3738
|
/*
* Copyright 2002-2013 the original author or 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 org.springframework.security.web.csrf;
/**
* Thrown when no expected {@link CsrfToken} is found but is required.
*
* @author Rob Winch
* @since 3.2
*/
@SuppressWarnings("serial")
public class MissingCsrfTokenException extends CsrfException {
public MissingCsrfTokenException(String actualToken) {
super("Could not verify the provided CSRF token because your session was not found.");
}
}
|
/*
* Copyright 2002-2013 the original author or 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 org.springframework.security.web.csrf;
/**
* Thrown when no expected {@link CsrfToken} is found but is required.
*
* @author Rob Winch
* @since 3.2
*/
@SuppressWarnings("serial")
public class MissingCsrfTokenException extends CsrfException {
public MissingCsrfTokenException(String actualToken) {
super("Expected CSRF token not found. Has your session expired?");
}
}
|
Move smll and dcm to baseline devices
|
# vim: sw=4 ts=4 sts expandtab smarttab
# HXN step-scan configuration
import hxntools.scans
from bluesky.global_state import get_gs
gs = get_gs()
hxntools.scans.setup()
ct = hxntools.scans.count
ascan = hxntools.scans.absolute_scan
dscan = hxntools.scans.relative_scan
fermat = hxntools.scans.relative_fermat
spiral = hxntools.scans.relative_spiral
mesh = hxntools.scans.absolute_mesh
dmesh = hxntools.scans.relative_mesh
gs.DETS = [zebra, sclr1, merlin1, timepix1, xspress3, lakeshore2, xbpm, s1, roi1_tot]
gs.TABLE_COLS = ['sclr1_ch2','sclr1_ch3', 'sclr1_ch4', 'sclr1_ch4_calc', 'ssx', 'ssy', 'ssz','roi1_tot',
't_base', 't_sample', 't_vlens', 't_hlens']
# Plot this by default versus motor position:
gs.PLOT_Y = 'Det2_Pt'
gs.OVERPLOT = False
gs.BASELINE_DEVICES = [dcm, smll]
|
# vim: sw=4 ts=4 sts expandtab smarttab
# HXN step-scan configuration
import hxntools.scans
from bluesky.global_state import get_gs
gs = get_gs()
hxntools.scans.setup()
ct = hxntools.scans.count
ascan = hxntools.scans.absolute_scan
dscan = hxntools.scans.relative_scan
fermat = hxntools.scans.relative_fermat
spiral = hxntools.scans.relative_spiral
mesh = hxntools.scans.absolute_mesh
dmesh = hxntools.scans.relative_mesh
gs.DETS = [zebra, sclr1, merlin1, xspress3, smll, lakeshore2, xbpm, s1]
gs.TABLE_COLS = ['sclr1_ch2','sclr1_ch3', 'sclr1_ch4', 'sclr1_ch4_calc', 'ssx', 'ssy', 'ssz',
't_base', 't_sample', 't_vlens', 't_hlens']
# Plot this by default versus motor position:
gs.PLOT_Y = 'Det2_Pt'
gs.OVERPLOT = False
gs.BASELINE_DEVICES = []
|
Add address group in use exception
Related change: https://review.opendev.org/#/c/751110/
Change-Id: I2a9872890ca4d5e59a9e266c1dcacd3488a3265c
|
# 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.
from neutron_lib._i18n import _
from neutron_lib import exceptions
class AddressGroupNotFound(exceptions.NotFound):
message = _("Address group %(address_group_id)s could not be found.")
class AddressGroupInUse(exceptions.InUse):
message = _("Address group %(address_group_id)s is in use on one or more "
"security group rules.")
class AddressesNotFound(exceptions.NotFound):
message = _("Addresses %(addresses)s not found in the address group "
"%(address_group_id)s.")
class AddressesAlreadyExist(exceptions.BadRequest):
message = _("Addresses %(addresses)s already exist in the "
"address group %(address_group_id)s.")
|
# 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.
from neutron_lib._i18n import _
from neutron_lib import exceptions
class AddressGroupNotFound(exceptions.NotFound):
message = _("Address group %(address_group_id)s could not be found.")
class AddressesNotFound(exceptions.NotFound):
message = _("Addresses %(addresses)s not found in the address group "
"%(address_group_id)s.")
class AddressesAlreadyExist(exceptions.BadRequest):
message = _("Addresses %(addresses)s already exist in the "
"address group %(address_group_id)s.")
|
Fix return type in documentation
|
<?php
namespace jvwp\common;
class Ajax
{
const WP_AJAX_HOOK_PREFIX = 'wp_ajax_';
/**
* Gets the action hook string to use, based on the action name that was provided
*
* @param string $action
*
* @return string
*/
public static function getHook ($action)
{
return self::WP_AJAX_HOOK_PREFIX . $action;
}
/**
* Normalizes the string to use in an action name, making the string lowercase and replacing every instance of a
* non-word and non-digit character with an underscore
*
* @param $actionName
*
* @return string
*/
public static function normalizeActionName ($actionName)
{
return preg_replace('/[^\w\d]+/', '_', strtolower($actionName));
}
}
|
<?php
namespace jvwp\common;
class Ajax
{
const WP_AJAX_HOOK_PREFIX = 'wp_ajax_';
/**
* Gets the action hook string to use, based on the action name that was provided
*
* @param string $action
*
* @return string
*/
public static function getHook ($action)
{
return self::WP_AJAX_HOOK_PREFIX . $action;
}
/**
* Normalizes the string to use in an action name, making the string lowercase and replacing every instance of a
* non-word and non-digit character with an underscore
*
* @param $actionName
*
* @return mixed
*/
public static function normalizeActionName ($actionName)
{
return preg_replace('/[^\w\d]+/', '_', strtolower($actionName));
}
}
|
Set preload default to false
|
package dmillerw.lore.core.proxy;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import dmillerw.lore.LoreExpansion;
import dmillerw.lore.client.handler.ClientTickHandler;
import dmillerw.lore.core.handler.KeyHandler;
import net.minecraft.world.World;
import net.minecraftforge.common.config.Configuration;
import java.io.File;
/**
* @author dmillerw
*/
public class ClientProxy extends CommonProxy {
@Override
public void preInit(FMLPreInitializationEvent event) {
Configuration config = new Configuration(new File(LoreExpansion.configFolder, "config.cfg"));
config.load();
boolean preload = config.get(Configuration.CATEGORY_GENERAL, "preload", false, "Preload all lore sounds when the game starts. Will induce additional startup lag, but prevents lag during game.").getBoolean(false);
config.save();
FMLCommonHandler.instance().bus().register(KeyHandler.INSTANCE);
if (preload) {
FMLCommonHandler.instance().bus().register(new ClientTickHandler());
}
}
@Override
public World getClientWorld() {
return FMLClientHandler.instance().getClient().theWorld;
}
}
|
package dmillerw.lore.core.proxy;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import dmillerw.lore.LoreExpansion;
import dmillerw.lore.client.handler.ClientTickHandler;
import dmillerw.lore.core.handler.KeyHandler;
import net.minecraft.world.World;
import net.minecraftforge.common.config.Configuration;
import java.io.File;
/**
* @author dmillerw
*/
public class ClientProxy extends CommonProxy {
@Override
public void preInit(FMLPreInitializationEvent event) {
Configuration config = new Configuration(new File(LoreExpansion.configFolder, "config.cfg"));
config.load();
boolean preload = config.get(Configuration.CATEGORY_GENERAL, "preload", true, "Preload all lore sounds when the game starts. Will induce additional startup lag, but prevents lag during game.").getBoolean(true);
config.save();
FMLCommonHandler.instance().bus().register(KeyHandler.INSTANCE);
if (preload) {
FMLCommonHandler.instance().bus().register(new ClientTickHandler());
}
}
@Override
public World getClientWorld() {
return FMLClientHandler.instance().getClient().theWorld;
}
}
|
Disable the VT test, the code ain't mature enough.
|
# -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)`
:copyright: © 2013 by the SaltStack Team, see AUTHORS for more details.
:license: Apache 2.0, see LICENSE for more details.
tests.unit.utils.vt_test
~~~~~~~~~~~~~~~~~~~~~~~~
VirtualTerminal tests
'''
# Import python libs
import random
# Import Salt Testing libs
from salttesting import TestCase
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')
# Import salt libs
from salt.utils import vt
class VTTestCase(TestCase):
def test_vt_size(self):
'''Confirm that the terminal size is being set'''
self.skipTest('The code is not mature enough. Test disabled.')
cols = random.choice(range(80, 250))
terminal = vt.Terminal(
'echo Foo!',
shell=True,
cols=cols
)
# First the assertion
self.assertEqual(
terminal.getwinsize(), (24, cols)
)
# Then wait for the terminal child to exit
terminal.wait()
if __name__ == '__main__':
from integration import run_tests
run_tests(VTTestCase, needs_daemon=False)
|
# -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)`
:copyright: © 2013 by the SaltStack Team, see AUTHORS for more details.
:license: Apache 2.0, see LICENSE for more details.
tests.unit.utils.vt_test
~~~~~~~~~~~~~~~~~~~~~~~~
VirtualTerminal tests
'''
# Import python libs
import random
# Import Salt Testing libs
from salttesting import TestCase
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')
# Import salt libs
from salt.utils import vt
class VTTestCase(TestCase):
def test_vt_size(self):
'''Confirm that the terminal size is being set'''
cols = random.choice(range(80, 250))
terminal = vt.Terminal(
'echo Foo!',
shell=True,
cols=cols
)
# First the assertion
self.assertEqual(
terminal.getwinsize(), (24, cols)
)
# Then wait for the terminal child to exit
terminal.wait()
if __name__ == '__main__':
from integration import run_tests
run_tests(VTTestCase, needs_daemon=False)
|
Support for Hierarchical trees added.
|
package org.pentaho.ui.xul.components;
import java.util.List;
import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.binding.InlineBindingExpression;
import org.pentaho.ui.xul.util.ColumnType;
public interface XulTreeCol extends XulComponent {
public void setEditable(boolean edit);
public boolean isEditable();
public void setFixed(boolean fixed);
public boolean isFixed();
public void setHidden(boolean hide);
public boolean isHidden();
public void setLabel(String label);
public String getLabel();
public void setPrimary(boolean primo);
public boolean isPrimary();
public void setSortActive(boolean sort);
public boolean isSortActive();
public void setSortDirection(String dir);
public String getSortDirection();
public void setSrc(String srcUrl);
public String getSrc();
public void setType(String type);
public String getType();
public ColumnType getColumnType();
public void setWidth(int width);
public int getWidth();
public void autoSize();
public String getCustomeditor();
public void setCustomeditor(String customClass);
public void setBinding(String binding);
public String getBinding();
public void setChildrenbinding(String childProperty);
public String getChildrenbinding();
public String getCombobinding();
public void setCombobinding(String property);
public List<InlineBindingExpression> getBindingExpressions();
}
|
package org.pentaho.ui.xul.components;
import java.util.List;
import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.binding.InlineBindingExpression;
import org.pentaho.ui.xul.util.ColumnType;
public interface XulTreeCol extends XulComponent {
public void setEditable(boolean edit);
public boolean isEditable();
public void setFixed(boolean fixed);
public boolean isFixed();
public void setHidden(boolean hide);
public boolean isHidden();
public void setLabel(String label);
public String getLabel();
public void setPrimary(boolean primo);
public boolean isPrimary();
public void setSortActive(boolean sort);
public boolean isSortActive();
public void setSortDirection(String dir);
public String getSortDirection();
public void setSrc(String srcUrl);
public String getSrc();
public void setType(String type);
public String getType();
public ColumnType getColumnType();
public void setWidth(int width);
public int getWidth();
public void autoSize();
public String getCustomeditor();
public void setCustomeditor(String customClass);
public void setBinding(String binding);
public String getBinding();
public List<InlineBindingExpression> getBindingExpressions();
}
|
Install c3d-metadata script as part of the package.
|
import os
import setuptools
setuptools.setup(
name='c3d',
version='0.2.0',
py_modules=['c3d'],
author='Leif Johnson',
author_email='leif@leifjohnson.net',
description='A library for manipulating C3D binary files',
long_description=open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'README.rst')).read(),
license='MIT',
url='http://github.com/EmbodiedCognition/py-c3d',
keywords=('c3d motion-capture'),
install_requires=['numpy'],
scripts=['scripts/c3d-metadata', 'scripts/c3d-viewer', 'scripts/c3d2csv'],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Topic :: Scientific/Engineering',
],
)
|
import os
import setuptools
setuptools.setup(
name='c3d',
version='0.2.0',
py_modules=['c3d'],
author='Leif Johnson',
author_email='leif@leifjohnson.net',
description='A library for manipulating C3D binary files',
long_description=open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'README.rst')).read(),
license='MIT',
url='http://github.com/EmbodiedCognition/py-c3d',
keywords=('c3d motion-capture'),
install_requires=['numpy'],
scripts=['scripts/c3d-viewer', 'scripts/c3d2csv'],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Topic :: Scientific/Engineering',
],
)
|
Use correct value for disable_escaping parameter
|
########################################################################
# amara/xslt/tree/text_element.py
"""
Implementation of the `xsl:text` element.
"""
from amara.xslt.tree import xslt_element, content_model, attribute_types
class text_element(xslt_element):
content_model = content_model.text
attribute_types = {
'disable-output-escaping': attribute_types.yesno(default='no'),
}
_value = None
def setup(self):
if self.children:
self._value = self.children[0].data
return
def instantiate(self, context):
value = self._value
if value:
if self._disable_output_escaping:
context.text(value, True)
else:
context.text(value)
return
|
########################################################################
# amara/xslt/tree/text_element.py
"""
Implementation of the `xsl:text` element.
"""
from amara.xslt.tree import xslt_element, content_model, attribute_types
class text_element(xslt_element):
content_model = content_model.text
attribute_types = {
'disable-output-escaping': attribute_types.yesno(default='no'),
}
_value = None
def setup(self):
if self.children:
self._value = self.children[0].data
return
def instantiate(self, context):
value = self._value
if value:
if self._disable_output_escaping:
context.text(value, False)
else:
context.text(value)
return
|
Add license to package metadata
|
#!/usr/bin/env python
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="autograd-gamma",
version="0.4.2",
description="Autograd compatible approximations to the gamma family of functions",
license='MIT License',
author="Cameron Davidson-Pilon",
author_email="cam.davidson.pilon@gmail.com",
url="https://github.com/CamDavidsonPilon/autograd-gamma",
keywords=["autograd", "gamma", "incomplete gamma function"],
long_description=long_description,
long_description_content_type="text/markdown",
classifiers=[
"Intended Audience :: Science/Research",
"Topic :: Scientific/Engineering",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
],
install_requires=["autograd>=1.2.0", "scipy>=1.2.0"],
packages=setuptools.find_packages(),
)
|
#!/usr/bin/env python
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="autograd-gamma",
version="0.4.2",
description="Autograd compatible approximations to the gamma family of functions",
author="Cameron Davidson-Pilon",
author_email="cam.davidson.pilon@gmail.com",
url="https://github.com/CamDavidsonPilon/autograd-gamma",
keywords=["autograd", "gamma", "incomplete gamma function"],
long_description=long_description,
long_description_content_type="text/markdown",
classifiers=[
"Intended Audience :: Science/Research",
"Topic :: Scientific/Engineering",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
],
install_requires=["autograd>=1.2.0", "scipy>=1.2.0"],
packages=setuptools.find_packages(),
)
|
openid: Fix notice about unititialized variable.
|
<?php
/* Find the authentication state. */
if (!array_key_exists('AuthState', $_REQUEST) || empty($_REQUEST['AuthState'])) {
throw new SimpleSAML_Error_BadRequest('Missing mandatory parameter: AuthState');
}
$authState = $_REQUEST['AuthState'];
$state = SimpleSAML_Auth_State::loadState($authState, 'openid:init');
$sourceId = $state['openid:AuthId'];
$authSource = SimpleSAML_Auth_Source::getById($sourceId);
if ($authSource === NULL) {
throw new SimpleSAML_Error_BadRequest('Invalid AuthId \'' . $sourceId . '\' - not found.');
}
$error = NULL;
try {
if (!empty($_GET['openid_url'])) {
$authSource->doAuth($state, (string)$_GET['openid_url']);
}
} catch (Exception $e) {
$error = $e->getMessage();
}
$config = SimpleSAML_Configuration::getInstance();
$t = new SimpleSAML_XHTML_Template($config, 'openid:consumer.php', 'openid');
$t->data['error'] = $error;
$t->data['AuthState'] = $authState;
$t->show();
|
<?php
/* Find the authentication state. */
if (!array_key_exists('AuthState', $_REQUEST) || empty($_REQUEST['AuthState'])) {
throw new SimpleSAML_Error_BadRequest('Missing mandatory parameter: AuthState');
}
$authState = $_REQUEST['AuthState'];
$state = SimpleSAML_Auth_State::loadState($authState, 'openid:init');
$sourceId = $state['openid:AuthId'];
$authSource = SimpleSAML_Auth_Source::getById($sourceId);
if ($authSource === NULL) {
throw new SimpleSAML_Error_BadRequest('Invalid AuthId \'' . $sourceId . '\' - not found.');
}
try {
if (!empty($_GET['openid_url'])) {
$authSource->doAuth($state, (string)$_GET['openid_url']);
}
} catch (Exception $e) {
$error = $e->getMessage();
}
$config = SimpleSAML_Configuration::getInstance();
$t = new SimpleSAML_XHTML_Template($config, 'openid:consumer.php', 'openid');
$t->data['error'] = $error;
$t->data['AuthState'] = $authState;
$t->show();
|
Connect to sodapop.se if debug is not found in the startup arguments
|
package edu.chalmers.sankoss.java;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
/**
* Class to start the application from.
* Creates a application window with initial
* size, title and GL20 support.
*
* @author Mikael Malmqvist
* @date 3/23/14
*/
public class SankossDesktop {
public static void main(String[] args) {
/**
* Load settings from ini file
*/
Settings.loadSettings();
if (args.length > 0) {
if (args[0].equals("debug")) {
Settings.HOSTNAME = "localhost";
} else {
Settings.HOSTNAME = "sodapop.se";
}
} else {
Settings.HOSTNAME = "sodapop.se";
}
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
cfg.title = "Battleships";
cfg.vSyncEnabled = true;
cfg.width = 800;
cfg.height = 600;
LwjglApplication application = new LwjglApplication(SankossGame.getInstance(), cfg);
}
}
|
package edu.chalmers.sankoss.java;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
/**
* Class to start the application from.
* Creates a application window with initial
* size, title and GL20 support.
*
* @author Mikael Malmqvist
* @date 3/23/14
*/
public class SankossDesktop {
public static void main(String[] args) {
/**
* Load settings from ini file
*/
Settings.loadSettings();
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
cfg.title = "Battleships";
cfg.vSyncEnabled = true;
cfg.width = 800;
cfg.height = 600;
LwjglApplication application = new LwjglApplication(SankossGame.getInstance(), cfg);
}
}
|
Change to multi-line imports in the test suite
|
#!/usr/bin/env python3
from libpals.util import (
xor_find_singlechar_key,
hamming_distance,
fixed_xor
)
def test_xor_find_singlechar_key():
input = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736'
ciphertext = bytes.fromhex(input)
result = xor_find_singlechar_key(ciphertext)
assert result['key'] == 88
assert result['plaintext'] == b"Cooking MC's like a pound of bacon"
def test_hamming_distance():
assert hamming_distance(b"this is a test", b"wokka wokka!!!") == 37
def test_fixed_xor():
input = bytes.fromhex("1c0111001f010100061a024b53535009181c")
key = bytes.fromhex("686974207468652062756c6c277320657965")
assert fixed_xor(input, key) == b"the kid don't play"
|
#!/usr/bin/env python3
from libpals.util import xor_find_singlechar_key, hamming_distance, fixed_xor
def test_xor_find_singlechar_key():
input = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736'
ciphertext = bytes.fromhex(input)
result = xor_find_singlechar_key(ciphertext)
assert result['key'] == 88
assert result['plaintext'] == b"Cooking MC's like a pound of bacon"
def test_hamming_distance():
assert hamming_distance(b"this is a test", b"wokka wokka!!!") == 37
def test_fixed_xor():
input = bytes.fromhex("1c0111001f010100061a024b53535009181c")
key = bytes.fromhex("686974207468652062756c6c277320657965")
assert fixed_xor(input, key) == b"the kid don't play"
|
Put routes in order of use.
|
'use strict';
/**
* Contains all of the functions necessary to deal with user
* signup and authentication.
*
* 1. decodeToken: decodes a token into user data using.
* 2. getToken middleware that sets up req.user if a token is passed in REST.
* 3. Login
*/
var token = require('./token');
/* * * Custom REST routes. * * */
module.exports = function(app, config){
// Secret is required.
if (!config.local.secret) {
throw new Error('A config.local.secret is required');
}
// TODO: Decouple Mandrill & pluginify. Offer other options.
// Mandrill Key is required.
if (!config.local.mandrill.key) {
throw new Error('A config.local.mandrill.key is required');
}
// All REST routes will set up req.feathers.user if a token is passed.
app.post('*', token.get);
// POST signup route / create user.
require('./route.signup')(app, config);
// Verify a user's account by passing a secret.
require('./route.verify')(app, config);
// POST login.
require('./route.login')(app, config);
// POST token login
require('./route.token-login')(app, config);
// Send a password-reset email.
require('./route.pw-reset-request')(app, config);
// Pass in a secret and password to change a user's password.
require('./route.pw-change')(app, config);
};
|
'use strict';
/**
* Contains all of the functions necessary to deal with user
* signup and authentication.
*
* 1. decodeToken: decodes a token into user data using.
* 2. getToken middleware that sets up req.user if a token is passed in REST.
* 3. Login
*/
var token = require('./token');
/* * * Custom REST routes. * * */
module.exports = function(app, config){
// Secret is required.
if (!config.local.secret) {
throw new Error('A config.local.secret is required');
}
// TODO: Decouple Mandrill & pluginify. Offer other options.
// Mandrill Key is required.
if (!config.local.mandrill.key) {
throw new Error('A config.local.mandrill.key is required');
}
// All REST routes will set up req.feathers.user if a token is passed.
app.post('*', token.get);
// POST signup route / create user.
require('./route.signup')(app, config);
// POST login.
require('./route.login')(app, config);
// POST token login
require('./route.token-login')(app, config);
// Verify a user's account by passing a secret.
require('./route.verify')(app, config);
// Send a password-reset email.
require('./route.pw-reset-request')(app, config);
// Pass in a secret and password to change a user's password.
require('./route.pw-change')(app, config);
};
|
Fix custom decoder on Python 3
|
# -*- coding: utf-8 -*-
from datetime import datetime
from time import mktime
import json
from doorman.compat import string_types
class DJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return {
'__type__': '__datetime__',
'epoch': int(mktime(obj.timetuple()))
}
else:
return json.JSONEncoder.default(self, obj)
def djson_decoder(obj):
if '__type__' in obj:
if obj['__type__'] == '__datetime__':
return datetime.fromtimestamp(obj['epoch'])
return obj
# Encoder function
def djson_dumps(obj):
return json.dumps(obj, cls=DJSONEncoder)
# Decoder function
def djson_loads(s):
if not isinstance(s, string_types):
s = s.decode('utf-8')
return json.loads(s, object_hook=djson_decoder)
|
# -*- coding: utf-8 -*-
from datetime import datetime
from time import mktime
import json
class DJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return {
'__type__': '__datetime__',
'epoch': int(mktime(obj.timetuple()))
}
else:
return json.JSONEncoder.default(self, obj)
def djson_decoder(obj):
if '__type__' in obj:
if obj['__type__'] == '__datetime__':
return datetime.fromtimestamp(obj['epoch'])
return obj
# Encoder function
def djson_dumps(obj):
return json.dumps(obj, cls=DJSONEncoder)
# Decoder function
def djson_loads(obj):
return json.loads(obj, object_hook=djson_decoder)
|
Make rooms in the example game (grammatically) "proper" (nouns)
|
from __future__ import unicode_literals
from imaginary.world import ImaginaryWorld
from imaginary.objects import Thing, Container, Exit
from imaginary.garments import createShirt, createPants
from imaginary.iimaginary import IClothing, IClothingWearer
from examplegame.squeaky import Squeaker
def world(store):
def room(name):
it = Thing(
store=store,
name=name,
proper=True,
)
Container.createFor(it, capacity=1000)
return it
world = ImaginaryWorld(store=store,
origin=room("The Beginning"))
protagonist = world.create("An Example Player")
shirt = createShirt(store=store, name="shirt", location=world.origin)
pants = createPants(store=store, name="pants", location=world.origin)
middle = room("The Middle")
wearer = IClothingWearer(protagonist)
wearer.putOn(IClothing(shirt))
wearer.putOn(IClothing(pants))
Exit.link(world.origin, middle, "north")
squeakerThing = Thing(name="squeaker", location=middle, store=store)
Squeaker.createFor(squeakerThing)
return world
|
from __future__ import unicode_literals
from imaginary.world import ImaginaryWorld
from imaginary.objects import Thing, Container, Exit
from imaginary.garments import createShirt, createPants
from imaginary.iimaginary import IClothing, IClothingWearer
from examplegame.squeaky import Squeaker
def world(store):
def room(name):
it = Thing(store=store, name=name)
Container.createFor(it, capacity=1000)
return it
world = ImaginaryWorld(store=store,
origin=room("The Beginning"))
protagonist = world.create("An Example Player")
shirt = createShirt(store=store, name="shirt", location=world.origin)
pants = createPants(store=store, name="pants", location=world.origin)
middle = room("The Middle")
wearer = IClothingWearer(protagonist)
wearer.putOn(IClothing(shirt))
wearer.putOn(IClothing(pants))
Exit.link(world.origin, middle, "north")
squeakerThing = Thing(name="squeaker", location=middle, store=store)
Squeaker.createFor(squeakerThing)
return world
|
Add first draft of lpa journey ordering
|
define([
'extensions/collections/conversioncollection'
], function (ConversionCollection) {
var ConversionSeries = ConversionCollection.extend({
serviceName:'lasting-power-of-attorney',
apiName:'journey',
queryId:'lpa-conversion',
steps:[
'user/register',
'user/login',
'user/dashboard',
'create/lpa-type',
'create/donor',
'create/attorneys',
'create/people-to-be-told',
'create/review',
'create/complete',
'register'
],
stepTitles:{
'user/register':'Register user',
'user/login':'Login',
'user/dashboard':'Dashboard',
'create/lpa-type':'Choose LPA Type',
'create/donor':'Add donor details',
'create/attorneys':'Create attorneys',
'create/people-to-be-told':'People to be told',
'create/review':'Review',
'create/complete':'Complete',
'register':'Register LPA'
},
getStep: function(d) {
return d.eventLabel;
}
});
return ConversionSeries;
});
|
define([
'extensions/collections/conversioncollection'
], function (ConversionCollection) {
var ConversionSeries = ConversionCollection.extend({
serviceName:'lasting-power-of-attorney',
apiName:'journey',
queryId:'lpa-conversion',
steps:[
'step1',
'step2',
'step3',
'step4',
'step5',
'step6',
'step7',
'step8',
'step9',
'step10'
],
stepTitles:{
'step1':'Step 1',
'step2':'Step 2',
'step3':'Step 3',
'step4':'Step 4',
'step5':'Step 5',
'step6':'Step 6',
'step7':'Step 7',
'step8':'Step 8',
'step9':'Step 9',
'step10':'Step 10'
},
getStep: function(d) {
return d.eventLabel;
}
});
return ConversionSeries;
});
|
Improve CLI test mocking using sinon
|
/**
* Copyright 2012 Microsoft Corporation
*
* 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.
*/
var sinon = require('sinon');
exports = module.exports = {
capture: capture,
};
function capture(action, cb) {
var sandbox = sinon.sandbox.create();
var result = {
text: '',
errorText: ''
}
sandbox.stub(process.stdout, 'write', function(data, encoding, fd) {
result.text += data;
});
sandbox.stub(process.stderr, 'write', function (data, encoding, fd) {
result.errorText += data;
});
sandbox.stub(process, 'exit', function(status) {
result.exitStatus = status;
sandbox.restore();
return cb(result);
});
try {
action();
} catch(err) {
result.error = err;
sandbox.restore();
if (!result.exitStatus) {
cb(result);
}
}
}
|
/**
* Copyright 2012 Microsoft Corporation
*
* 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.
*/
exports = module.exports = {
capture: capture,
};
function capture(action, cb) {
var result = {
text: '',
errorText: ''
}
var processStdoutWrite = process.stdout.write
var processStderrWrite = process.stderr.write
var processExit = process.exit
process.stdout.write = function(data, encoding, fd) {
result.text += data;
};
process.stderr.write = function (data, encoding, fd) {
result.errorText += data;
};
process.exit = function(status) {
result.exitStatus = status;
process.stdout.write = processStdoutWrite;
process.stderr.write = processStderrWrite;
process.exit = processExit;
return cb(result);
};
try {
action();
} catch(err) {
result.error = err;
process.stdout.write = processStdoutWrite;
process.stderr.write = processStderrWrite;
process.exit = processExit;
if (!result.exitStatus) {
cb(result);
}
}
}
|
Add a version field into the header.
|
# The Header class contains the data structure of the Header class, and methods includes encapsulate, and decapsulate.
import struct
import random
from MessageType import MessageType
class Header:
"""docstring for Header"""
def __init__(self, type = MessageType.undefined):
self.version = 1
self.type = type
self.length = 0
self.port = 0
def encapsulate(self):
return struct.pack("!BBHH", self.version, self.type, self.length, self.port)
def decapsulate(self, data):
header = struct.unpack("!BBHH", data)
self.version = header[0]
self.type = header[1]
self.length = header[2]
self.port = header[3]
"""Write the test code here"""
if __name__ == '__main__':
header = Header(MessageType.query)
print str(header.port)
header.length = 1
header.decapsulate(header.encapsulate())
print header.version
print header.type
print header.length
print header.port
print "Header class should work if you see this"
|
# The Header class contains the data structure of the Header class, and methods includes encapsulate, and decapsulate.
import struct
import random
from MessageType import MessageType
class Header:
"""docstring for Header"""
def __init__(self, type = MessageType.undefined):
self.type = type
self.length = 0
self.port = 0
def encapsulate(self):
return struct.pack("!BHH", self.type, self.length, self.port)
def decapsulate(self, data):
header = struct.unpack("!BHH", data)
self.type = header[0]
self.length = header[1]
self.port = header[2]
"""Write the test code here"""
if __name__ == '__main__':
header = Header(MessageType.query)
print str(header.port)
header.length = 1
header.decapsulate(header.encapsulate())
print header.type
print header.length
print header.port
print "Header class should work if you see this"
|
Fix 'ImportError: DLL load failed'
|
# -*- coding: utf-8 -*-
import os
import sys
import ctypes
import platform
if platform.system() == 'Windows':
lib32 = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib32')
lib64 = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib64')
from glob import glob
try:
if ctypes.sizeof(ctypes.c_voidp) == 4:
dllfile = glob(lib32 + '/*.dll')[0]
else:
dllfile = glob(lib64 + '/*.dll')[0]
ctypes.CDLL(dllfile)
except:
pass
sys.path.append(os.path.join(os.path.dirname(__file__), 'cppinterface'))
from amplpython import *
from amplpython import _READTABLE, _WRITETABLE
|
# -*- coding: utf-8 -*-
import os
import sys
import ctypes
import platform
if platform.system() == 'Windows':
lib32 = os.path.join(os.path.dirname(__file__), 'lib32')
lib64 = os.path.join(os.path.dirname(__file__), 'lib64')
from glob import glob
try:
if ctypes.sizeof(ctypes.c_voidp) == 4:
dllfile = glob(lib32 + '/*.dll')[0]
else:
dllfile = glob(lib64 + '/*.dll')[0]
ctypes.CDLL(dllfile)
except:
pass
sys.path.append(os.path.join(os.path.dirname(__file__), 'cppinterface'))
from amplpython import *
from amplpython import _READTABLE, _WRITETABLE
|
Allow almost all puppeteer pdf configurations
|
const puppeteer = require("puppeteer")
const defaults = require("../configurations/defaults")
const puppeteerArgs = [
"--no-sandbox",
"--disable-setuid-sandbox",
"--disable-gpu"
]
const allowedOptions = [
"scale",
"displayHeaderFooter",
"printBackground",
"format",
"landscape",
"pageRanges",
"width",
"height",
"margin"
]
const formatOptions = options => allowedOptions.reduce((filtered, key) => {
if (options[key] == 'true') {
filtered[key] = true
return filtered
}
if (options[key] == 'false') {
filtered[key] = false
return filtered
}
if (!isNaN(options[key])) {
filtered[key] = +options[key]
return filtered
}
filtered[key] = options[key]
return filtered
}, {})
const pageToPdf = options => page =>
page
.goto(options.uri, { waitUntil: "networkidle" })
.then(() => page.pdf(Object.assign(defaults, formatOptions(options))))
const browserToPdf = options => browser =>
browser
.newPage()
.then(pageToPdf(options))
.then(pdf => {
browser.close()
return pdf
})
const uriToPdf = options =>
puppeteer
.launch({ args: puppeteerArgs })
.then(browserToPdf(options))
module.exports = {
uriToPdf
}
|
const puppeteer = require("puppeteer")
const defaults = require("../configurations/defaults")
const puppeteerArgs = [
"--no-sandbox",
"--disable-setuid-sandbox",
"--disable-gpu"
]
const allowedOptions = [
"scale",
"printBackground",
"margin"
]
const formatOptions = options => allowedOptions.reduce((filtered, key) => {
if (options[key] == 'true') {
filtered[key] = true
return filtered
}
if (options[key] == 'false') {
filtered[key] = false
return filtered
}
if (!isNaN(options[key])) {
filtered[key] = +options[key]
return filtered
}
filtered[key] = options[key]
return filtered
}, {})
const pageToPdf = options => page =>
page
.goto(options.uri, { waitUntil: "networkidle" })
.then(() => page.pdf(Object.assign(defaults, formatOptions(options))))
const browserToPdf = options => browser =>
browser
.newPage()
.then(pageToPdf(options))
.then(pdf => {
browser.close()
return pdf
})
const uriToPdf = options =>
puppeteer
.launch({ args: puppeteerArgs })
.then(browserToPdf(options))
module.exports = {
uriToPdf
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.