text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Send mail in the test
|
package nlgids
import (
"testing"
"github.com/miekg/nlgids/email"
"github.com/miekg/nlgids/webcontact"
)
func newContact() *webcontact.Contact {
return &webcontact.Contact{
Name: "Miek Gieben",
Email: "miek@miek.nl",
Phone: "07774 517 566",
Message: "Hee, hoe is het daar?",
}
}
func TestContactCreate(t *testing.T) {
c := newContact()
subject := c.MailSubject()
body, err := c.MailBody()
if err != nil {
t.Fatal(err)
}
mail := email.NewContact(subject, body)
if mail.Subject != "[NLgids] Contact van \"Miek Gieben\"" {
t.Fatal("wrong email Subject")
}
if mail.From != "nlgids@nlgids.london" {
t.Fatal("wrong email From")
}
if len(mail.Cc) != 0 {
t.Fatal("wrong email Cc")
}
if err := mail.Do(); err != nil {
t.Fatalf("can't send mail %s: ", err)
}
}
|
package nlgids
import (
"testing"
"github.com/miekg/nlgids/email"
"github.com/miekg/nlgids/webcontact"
)
func newContact() *webcontact.Contact {
return &webcontact.Contact{
Name: "Miek Gieben",
Email: "miek@miek.nl",
Phone: "07774 517 566",
Message: "Hee, hoe is het daar?",
}
}
func TestContactCreate(t *testing.T) {
c := newContact()
subject := c.MailSubject()
body, err := c.MailBody()
if err != nil {
t.Fatal(err)
}
mail := email.NewContact(subject, body)
if mail.Subject != "[NLgids] Contact van \"Miek Gieben\"" {
t.Fatal("wrong email Subject")
}
if mail.From != "nlgids@nlgids.london" {
t.Fatal("wrong email From")
}
if len(mail.Cc) != 0 {
t.Fatal("wrong email Cc")
}
}
|
Allow runtime configurable test environment
|
module.exports = require('should');
var DataSource = require('loopback-datasource-juggler').DataSource;
var TEST_ENV = process.env.TEST_ENV || 'test';
var config = require('rc')('loopback', {test: {mongodb: {}}})[TEST_ENV].mongodb;
if (process.env.CI) {
config = {
host: process.env.MONGODB_HOST || 'localhost',
port: process.env.MONGODB_PORT || 27017,
database: 'lb-ds-mongodb-test-' + (
process.env.TRAVIS_BUILD_NUMBER || process.env.BUILD_NUMBER || '1'
),
};
}
global.config = config;
global.getDataSource = global.getSchema = function (customConfig) {
var db = new DataSource(require('../'), customConfig || config);
db.log = function (a) {
console.log(a);
};
return db;
};
global.sinon = require('sinon');
|
module.exports = require('should');
var DataSource = require('loopback-datasource-juggler').DataSource;
var config = require('rc')('loopback', {test: {mongodb: {}}}).test.mongodb;
if (process.env.CI) {
config = {
host: process.env.MONGODB_HOST || 'localhost',
port: process.env.MONGODB_PORT || 27017,
database: 'lb-ds-mongodb-test-' + (
process.env.TRAVIS_BUILD_NUMBER || process.env.BUILD_NUMBER || '1'
),
};
}
global.config = config;
global.getDataSource = global.getSchema = function (customConfig) {
var db = new DataSource(require('../'), customConfig || config);
db.log = function (a) {
console.log(a);
};
return db;
};
global.sinon = require('sinon');
|
Add search form and increase the number of visible pagination numbers
|
<?php get_header(); ?>
<div class="container">
<?php if (!is_front_page()) : ?>
<?php
if (!is_404()):
get_search_form();
endif;
?>
<div id="primary" class="content-area">
<?php get_template_part(SNIPPETS_DIR . '/header/page', 'header'); ?>
<main id="main" class="site-main" role="main">
<?php
if (have_posts()) :
/* Start the Loop */
while (have_posts()) :
the_post();
/*
* Include the Post-Format-specific template for the content.
* If you want to override this in a child theme, then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
if (is_page()) :
get_template_part(SNIPPETS_DIR . '/content/content', 'page');
else :
get_template_part(SNIPPETS_DIR . '/content/content');
endif;
endwhile;
else :
get_template_part(SNIPPETS_DIR . '/content/content', 'none');
endif;
echo paginate_links(array(
'mid_size' => 6,
'type' => 'list',
));
?>
</main>
</div>
<?php endif; ?>
<?php get_sidebar(); ?>
</div>
<?php
get_footer();
|
<?php get_header(); ?>
<div class="container">
<?php if (!is_front_page()) : ?>
<div id="primary" class="content-area">
<?php get_template_part(SNIPPETS_DIR . '/header/page', 'header'); ?>
<main id="main" class="site-main" role="main">
<?php
if (have_posts()) :
/* Start the Loop */
while (have_posts()) :
the_post();
/*
* Include the Post-Format-specific template for the content.
* If you want to override this in a child theme, then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
if (is_page()) :
get_template_part(SNIPPETS_DIR . '/content/content', 'page');
else :
get_template_part(SNIPPETS_DIR . '/content/content');
endif;
endwhile;
else :
get_template_part(SNIPPETS_DIR . '/content/content', 'none');
endif;
echo paginate_links(array(
'mid_size' => 4,
'type' => 'list',
));
?>
</main>
</div>
<?php endif; ?>
<?php get_sidebar(); ?>
</div>
<?php
get_footer();
|
Add a toJSON method to the error object
|
'use strict';
module.exports = makeError;
function makeError(code, message, options) {
var line = options.line;
var column = options.column;
var filename = options.filename;
var src = options.src;
var fullMessage;
var location = line + (column ? ':' + column : '');
if (src) {
var lines = src.split('\n');
var start = Math.max(line - 3, 0);
var end = Math.min(lines.length, line + 3);
// Error context
var context = lines.slice(start, end).map(function(text, i){
var curr = i + start + 1;
return (curr == line ? ' > ' : ' ')
+ curr
+ '| '
+ text;
}).join('\n');
fullMessage = (filename || 'Jade') + ':' + location + '\n' + context + '\n\n' + message;
} else {
fullMessage = (filename || 'Jade') + ':' + location + '\n\n' + message;
}
var err = new Error(fullMessage);
err.code = 'JADE:' + code;
err.msg = message;
err.line = line;
err.column = column;
err.filename = filename;
err.src = src;
err.toJSON = function () {
return {
code: this.code,
msg: this.msg,
line: this.line,
column: this.column,
filename: this.filename
};
};
return err;
}
|
'use strict';
module.exports = makeError;
function makeError(code, message, options) {
var line = options.line;
var column = options.column;
var filename = options.filename;
var src = options.src;
var fullMessage;
var location = line + (column ? ':' + column : '');
if (src) {
var lines = src.split('\n');
var start = Math.max(line - 3, 0);
var end = Math.min(lines.length, line + 3);
// Error context
var context = lines.slice(start, end).map(function(text, i){
var curr = i + start + 1;
return (curr == line ? ' > ' : ' ')
+ curr
+ '| '
+ text;
}).join('\n');
fullMessage = (filename || 'Jade') + ':' + location + '\n' + context + '\n\n' + message;
} else {
fullMessage = (filename || 'Jade') + ':' + location + '\n\n' + message;
}
var err = new Error(fullMessage);
err.code = 'JADE:' + code;
err.msg = message;
err.line = line;
err.column = column;
err.filename = filename;
err.src = src;
return err;
}
|
Add gcsfs, tensorflow-datasets, zarr as dependencies.
PiperOrigin-RevId: 414517642
|
# coding=utf-8
# Copyright 2021 The Balloon Learning Environment 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.
"""Setup file for installing the BLE."""
import setuptools
setuptools.setup(
name='balloon_learning_environment',
version='0.0.1',
packages=setuptools.find_packages(),
install_requires=[
'absl-py',
'dopamine-rl',
'flax',
'gcsfs',
'gin-config',
'gym',
'opensimplex',
's2sphere',
'scikit-learn',
'tensorflow',
'tensorflow-datasets',
'tensorflow-probability',
'transitions',
'zarr',
],
package_data={
'': ['*.msgpack', '*.pb'],
},
python_requires='>=3.7',
)
|
# coding=utf-8
# Copyright 2021 The Balloon Learning Environment 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.
"""Setup file for installing the BLE."""
import setuptools
setuptools.setup(
name='balloon_learning_environment',
version='0.0.1',
packages=setuptools.find_packages(),
install_requires=[
'absl-py',
'dopamine-rl',
'flax',
'gin-config',
'gym',
'opensimplex',
's2sphere',
'scikit-learn',
'tensorflow',
'tensorflow-probability',
'transitions',
],
package_data={
'': ['*.msgpack', '*.pb'],
},
python_requires='>=3.7',
)
|
Check isEmbedded and isDuplicate only when needed
|
var embeddedRegexp = /data:(.*?);base64,/;
var commentRegexp = /\/\*([\s\S]*?)\*\//g;
var urlsRegexp = /((?:@import\s+)?url\s*\(['"]?)(\S*?)(['"]?\s*\))|(@import\s+['"]?)([^;'"]+)/ig;
function isEmbedded (src) {
return embeddedRegexp.test(src);
}
function getUrls (text) {
var urls = [];
var urlMatch, url;
text = text.replace(commentRegexp, '');
while (urlMatch = urlsRegexp.exec(text)) {
// Match 2 group if '[@import] url(path)', match 5 group if '@import path'
url = urlMatch[2] || urlMatch[5];
if (url && !isEmbedded(url) && urls.indexOf(url) === -1) {
urls.push(url);
}
}
return urls;
}
module.exports = getUrls;
|
var embeddedRegexp = /data:(.*?);base64,/;
var commentRegexp = /\/\*([\s\S]*?)\*\//g;
var urlsRegexp = /((?:@import\s+)?url\s*\(['"]?)(\S*?)(['"]?\s*\))|(@import\s+['"]?)([^;'"]+)/ig;
function isEmbedded (src) {
return embeddedRegexp.test(src);
}
function getUrls (text) {
var urls = [];
var urlMatch, url, isEmbeddedUrl, isDuplicatedUrl;
text = text.replace(commentRegexp, '');
while (urlMatch = urlsRegexp.exec(text)) {
// Match 2 group if '[@import] url(path)', match 5 group if '@import path'
url = urlMatch[2] || urlMatch[5];
isEmbeddedUrl = isEmbedded(url);
isDuplicatedUrl = urls.indexOf(url) !== -1;
if (url && !isEmbeddedUrl && !isDuplicatedUrl) {
urls.push(url);
}
}
return urls;
}
module.exports = getUrls;
|
Fix favicon tests to match the new scheme
|
import unittest
import foauth.providers
import urllib
class ProviderTests(unittest.TestCase):
def setUp(self):
class Example(foauth.providers.OAuth):
provider_url = 'http://example.com'
api_domain = 'api.example.com'
self.provider = Example
def test_auto_name(self):
self.assertEqual(self.provider.name, 'Example')
def test_auto_alias(self):
self.assertEqual(self.provider.alias, 'example')
def test_auto_favicon_url(self):
primary = 'https://getfavicon.appspot.com/http://example.com'
backup = 'https://www.google.com/s2/favicons?domain=example.com'
url = '%s?defaulticon=%s' % (primary, urllib.quote(backup))
self.assertEqual(self.provider.favicon_url, url)
def test_auto_api_domains(self):
self.assertEqual(self.provider.api_domains, ['api.example.com'])
|
import unittest
import foauth.providers
class ProviderTests(unittest.TestCase):
def setUp(self):
class Example(foauth.providers.OAuth):
provider_url = 'http://example.com'
api_domain = 'api.example.com'
self.provider = Example
def test_auto_name(self):
self.assertEqual(self.provider.name, 'Example')
def test_auto_alias(self):
self.assertEqual(self.provider.alias, 'example')
def test_auto_favicon_url(self):
url = 'https://www.google.com/s2/favicons?domain=example.com'
self.assertEqual(self.provider.favicon_url, url)
def test_auto_api_domains(self):
self.assertEqual(self.provider.api_domains, ['api.example.com'])
|
Fix SoulBound enchant not registering when id set to -1
@CrazyPants wat r u doin
|
package crazypants.enderio.enchantment;
import net.minecraft.enchantment.Enchantment;
import crazypants.enderio.Log;
import crazypants.enderio.config.Config;
public class Enchantments {
private static Enchantments instance;
public static Enchantments getInstance() {
if(instance == null) {
instance = new Enchantments();
instance.registerEnchantments();
}
return instance;
}
private EnchantmentSoulBound soulBound;
private void registerEnchantments() {
if(Config.enchantmentSoulBoundEnabled) {
int id = Config.enchantmentSoulBoundId;
if(id < 0) {
id = getEmptyEnchantId();
}
if(id < 0) {
Log.error("Could not find an empty enchantment ID to add enchanments");
return;
}
soulBound = EnchantmentSoulBound.create(id);
}
}
private int getEmptyEnchantId() {
for (int i = 0; i < Enchantment.enchantmentsList.length; i++) {
if(Enchantment.enchantmentsList[i] == null) {
return i;
}
}
return -1;
}
}
|
package crazypants.enderio.enchantment;
import net.minecraft.enchantment.Enchantment;
import crazypants.enderio.Log;
import crazypants.enderio.config.Config;
public class Enchantments {
private static Enchantments instance;
public static Enchantments getInstance() {
if(instance == null) {
instance = new Enchantments();
instance.registerEnchantments();
}
return instance;
}
private EnchantmentSoulBound soulBound;
private void registerEnchantments() {
if(Config.enchantmentSoulBoundEnabled) {
int id = Config.enchantmentSoulBoundId;
if(id < 0) {
getEmptyEnchantId();
}
if(id < 0) {
Log.error("Could not find an empty enchantment ID to add enchanments");
return;
}
soulBound = EnchantmentSoulBound.create(id);
}
}
private int getEmptyEnchantId() {
for (int i = 0; i < Enchantment.enchantmentsList.length; i++) {
if(Enchantment.enchantmentsList[i] == null) {
return i;
}
}
return -1;
}
}
|
Add logging to InfoStart debugging
|
<?php
set_time_limit(0);
// Configuration
include 'config/config.php';
// Version Functions
include 'functions/getVersion.php';
include 'functions/checkVersion.php';
// Debugging Functions
include 'functions/debug.php';
// Stats Functions
include 'functions/loadAvg.php';
include 'functions/memory.php';
include 'functions/misc.php';
define("DEBUG", $config['debug']);
define("LOG", $config['log']);
define("INTERVAL", $config['updateinterval']);
echo "LinMon slave version ".getVersion("version")." started \n\n";
echo checkVersion();
debug_collectionInterval(DEBUG, INTERVAL, LOG);
while (true){
debug_collectionInfoStart(DEBUG, LOG);
collect_loadAvg(DEBUG, LOG);
collect_memory(DEBUG, LOG);
collect_kernel(DEBUG, LOG);
collect_hostname(DEBUG, LOG);
collect_uptime(DEBUG, LOG);
debug_collectionInfoEnd(DEBUG, LOG);
sleep(INTERVAL);
}
?>
|
<?php
set_time_limit(0);
// Configuration
include 'config/config.php';
// Version Functions
include 'functions/getVersion.php';
include 'functions/checkVersion.php';
// Debugging Functions
include 'functions/debug.php';
// Stats Functions
include 'functions/loadAvg.php';
include 'functions/memory.php';
include 'functions/misc.php';
define("DEBUG", $config['debug']);
define("LOG", $config['log']);
define("INTERVAL", $config['updateinterval']);
echo "LinMon slave version ".getVersion("version")." started \n\n";
echo checkVersion();
debug_collectionInterval(DEBUG, INTERVAL, LOG);
while (true){
debug_collectionInfoStart(DEBUG);
collect_loadAvg(DEBUG, LOG);
collect_memory(DEBUG, LOG);
collect_kernel(DEBUG, LOG);
collect_hostname(DEBUG, LOG);
collect_uptime(DEBUG, LOG);
debug_collectionInfoEnd(DEBUG);
sleep(INTERVAL);
}
?>
|
Fix locale for old Firefox desktop page functional test
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import pytest
from pages.firefox.desktop.all import FirefoxDesktopBasePage
@pytest.mark.skip_if_firefox(reason='Download button is not shown for up-to-date Firefox browsers.')
@pytest.mark.nondestructive
@pytest.mark.parametrize(('slug', 'locale'), [
('', 'de'),
('customize', None),
('fast', 'de'),
('trust', None)])
def test_download_button_is_displayed(slug, locale, base_url, selenium):
locale = locale or 'en-US'
page = FirefoxDesktopBasePage(selenium, base_url, locale, slug=slug).open()
assert page.download_button.is_displayed
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import pytest
from pages.firefox.desktop.all import FirefoxDesktopBasePage
@pytest.mark.skip_if_firefox(reason='Download button is not shown for up-to-date Firefox browsers.')
@pytest.mark.nondestructive
@pytest.mark.parametrize(('slug', 'locale'), [
('', None),
('customize', None),
('fast', 'de'),
('trust', None)])
def test_download_button_is_displayed(slug, locale, base_url, selenium):
locale = locale or 'en-US'
page = FirefoxDesktopBasePage(selenium, base_url, locale, slug=slug).open()
assert page.download_button.is_displayed
|
Drop mox, no longer needed
The porting of mistral-dashboard is complete.
This fullfills the community goal "Remove Use of mox/mox3 for Testing"
set for Rocky: https://governance.openstack.org/tc/goals/rocky/mox_removal.html
Remove use_mox and remove dead code.
Change-Id: I59839fecd85caaf8b81129b7f890c4ed50d39db8
Signed-off-by: Chuck Short <61c7e57c8f71fbf1f6c3fcd85c16ccd0f494e116@redhat.com>
|
# Copyright 2015 Huawei Technologies Co., Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from openstack_dashboard.test import helpers
from mistraldashboard.test.test_data import utils
class MistralTestsMixin(object):
def _setup_test_data(self):
super(MistralTestsMixin, self)._setup_test_data()
utils.load_test_data(self)
class TestCase(MistralTestsMixin, helpers.TestCase):
pass
class APITestCase(MistralTestsMixin, helpers.APITestCase):
pass
|
# Copyright 2015 Huawei Technologies Co., Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from openstack_dashboard.test import helpers
from mistraldashboard.test.test_data import utils
def create_stubs(stubs_to_create={}):
return helpers.create_stubs(stubs_to_create)
class MistralTestsMixin(object):
def _setup_test_data(self):
super(MistralTestsMixin, self)._setup_test_data()
utils.load_test_data(self)
class TestCase(MistralTestsMixin, helpers.TestCase):
use_mox = False
pass
class APITestCase(MistralTestsMixin, helpers.APITestCase):
use_mox = False
pass
|
Fix softmax dim (I hope!!!)
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..helpers_torch import Net4Both
class Net(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=2)
self.conv2 = nn.Conv2d(in_channels=32, out_channels=32, kernel_size=2)
# TODO: make sure we check cnt_classes
self.dense1 = nn.Linear(1577088, 2)
def __call__(self, x):
h = x
h = self.conv1(h)
h = F.relu(h)
h = self.conv2(h)
h = F.relu(h)
h = torch.flatten(h, 1)
h = self.dense1(h)
return h
def get_kernel(params, unparsed_args=None):
net = Net()
return Net4Both(params, net, lambda t1: F.softmax(t1, dim=-1))
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..helpers_torch import Net4Both
class Net(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=2)
self.conv2 = nn.Conv2d(in_channels=32, out_channels=32, kernel_size=2)
# TODO: make sure we check cnt_classes
self.dense1 = nn.Linear(1577088, 2)
def __call__(self, x):
h = x
h = self.conv1(h)
h = F.relu(h)
h = self.conv2(h)
h = F.relu(h)
h = torch.flatten(h, 1)
h = self.dense1(h)
return h
def get_kernel(params, unparsed_args=None):
net = Net()
return Net4Both(params, net, lambda t1: F.softmax(t1, dim=1))
|
Add from prop to fix imports
|
var through = require('through-gulp')
var gutil = require('gulp-util')
var rext = require('replace-ext')
var preprocessor = require('sourdough-preprocessor')
var PluginError = gutil.PluginError
var PLUGIN_NAME = 'gulp-sourdough'
function sourdough(options) {
options = options || {}
return through(function (file, enc, cb) {
if (options.from === undefined) {
options.from = file.path
}
if (file.isStream()) {
return cb(new PluginError(PLUGIN_NAME, 'Streaming not supported'))
}
if (file.isBuffer()) {
try {
file.path = rext(file.path, '.css')
file.contents = new Buffer(preprocessor(String(file.contents), options))
} catch (e) {
return cb(new PluginError(PLUGIN_NAME, e))
}
}
this.push(file)
cb()
}, function (cb) {
cb()
});
}
module.exports = sourdough
|
var through = require('through-gulp')
var gutil = require('gulp-util')
var rext = require('replace-ext')
var preprocessor = require('sourdough-preprocessor')
var PluginError = gutil.PluginError
var PLUGIN_NAME = 'gulp-sourdough'
function sourdough(options) {
options = options || {}
return through(function (file, enc, cb) {
if (file.isStream()) {
return cb(new PluginError(PLUGIN_NAME, 'Streaming not supported'))
}
if (file.isBuffer()) {
try {
file.path = rext(file.path, '.css')
file.contents = new Buffer(preprocessor(String(file.contents), options))
} catch (e) {
return cb(new PluginError(PLUGIN_NAME, e))
}
}
this.push(file)
cb()
}, function (cb) {
cb()
});
}
module.exports = sourdough
|
Replace inline 'script!' with 'script-loader!'
This change is necessary to allow this module to properly work with newer
versions of Webpack.
|
require('font-awesome-webpack');
window.$ = require('jquery');
require('./css/html_styles.scss');
require('./css/set_view.scss');
require('./css/element_view.scss');
require('script-loader!./event-manager');
require('script-loader!./venn');
require('script-loader!./utilities');
require('script-loader!./attribute');
require('script-loader!./viewer/word-cloud');
require('script-loader!./viewer/scatterplot');
require('script-loader!./viewer/histogram');
require('script-loader!./viewer/variant-frequency');
require('script-loader!./element-viewer');
require('script-loader!./dataLoading');
require('script-loader!./filter');
require('script-loader!./selection');
require('script-loader!./dataStructure');
require('script-loader!./ui');
require('script-loader!./setSelection');
require('script-loader!./sort');
require('script-loader!./highlight');
require('script-loader!./scrollbar');
require('script-loader!./items');
require('script-loader!./setGrouping');
require('script-loader!./logicPanel');
require('script-loader!./brushableScale');
require('script-loader!./statisticGraphs');
require('script-loader!./upset');
module.exports = {
UpSet: window.UpSet,
Ui: window.Ui
};
|
require('font-awesome-webpack');
window.$ = require('jquery');
require('./css/html_styles.scss');
require('./css/set_view.scss');
require('./css/element_view.scss');
require('script!./event-manager');
require('script!./venn');
require('script!./utilities');
require('script!./attribute');
require('script!./viewer/word-cloud');
require('script!./viewer/scatterplot');
require('script!./viewer/histogram');
require('script!./viewer/variant-frequency');
require('script!./element-viewer');
require('script!./dataLoading');
require('script!./filter');
require('script!./selection');
require('script!./dataStructure');
require('script!./ui');
require('script!./setSelection');
require('script!./sort');
require('script!./highlight');
require('script!./scrollbar');
require('script!./items');
require('script!./setGrouping');
require('script!./logicPanel');
require('script!./brushableScale');
require('script!./statisticGraphs');
require('script!./upset');
module.exports = {
UpSet: window.UpSet,
Ui: window.Ui
};
|
Fix sanitizer service reference for windows
|
if __name__ == "__main__":
import gaphor
from gaphor import core
from gaphor.core.modeling import ElementFactory
from gaphor.plugins.console import ConsoleWindow
from gaphor.plugins.diagramexport import DiagramExport
from gaphor.plugins.xmiexport import XMIExport
from gaphor.services.componentregistry import ComponentRegistry
from gaphor.services.copyservice import CopyService
from gaphor.core.eventmanager import EventManager
from gaphor.services.helpservice import HelpService
from gaphor.services.properties import Properties
from gaphor.UML.sanitizerservice import SanitizerService
from gaphor.services.session import Session
from gaphor.services.undomanager import UndoManager
from gaphor.ui.elementeditor import ElementEditor
from gaphor.ui.appfilemanager import AppFileManager
from gaphor.ui.filemanager import FileManager
from gaphor.ui.mainwindow import Diagrams
from gaphor.ui.mainwindow import MainWindow
from gaphor.ui.menufragment import MenuFragment
from gaphor.ui.namespace import Namespace
from gaphor.ui.preferences import Preferences
from gaphor.ui.recentfiles import RecentFiles
from gaphor.ui.toolbox import Toolbox
from gaphor.ui import main
import sys
main(sys.argv)
|
if __name__ == "__main__":
import gaphor
from gaphor import core
from gaphor.core.modeling import ElementFactory
from gaphor.plugins.console import ConsoleWindow
from gaphor.plugins.diagramexport import DiagramExport
from gaphor.plugins.xmiexport import XMIExport
from gaphor.services.componentregistry import ComponentRegistry
from gaphor.services.copyservice import CopyService
from gaphor.core.eventmanager import EventManager
from gaphor.services.helpservice import HelpService
from gaphor.services.properties import Properties
from gaphor.services.sanitizerservice import SanitizerService
from gaphor.services.session import Session
from gaphor.services.undomanager import UndoManager
from gaphor.ui.elementeditor import ElementEditor
from gaphor.ui.appfilemanager import AppFileManager
from gaphor.ui.filemanager import FileManager
from gaphor.ui.mainwindow import Diagrams
from gaphor.ui.mainwindow import MainWindow
from gaphor.ui.menufragment import MenuFragment
from gaphor.ui.namespace import Namespace
from gaphor.ui.preferences import Preferences
from gaphor.ui.recentfiles import RecentFiles
from gaphor.ui.toolbox import Toolbox
from gaphor.ui import main
import sys
main(sys.argv)
|
Add dependency to jest transform
|
module.exports = {
setupFilesAfterEnv: ['./rtl.setup.js'],
verbose: true,
moduleDirectories: ['node_modules'],
transform: {
'^.+\\.(js|tsx?)$': '<rootDir>/jest.transform.js',
},
collectCoverage: true,
collectCoverageFrom: ['src/**/*.{js,jsx,ts,tsx}'],
transformIgnorePatterns: ['node_modules/(?!(proton-shared|react-components|mutex-browser)/)'],
moduleNameMapper: {
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)$': '<rootDir>/__mocks__/fileMock.js',
'\\.(css|scss|less)$': '<rootDir>/__mocks__/styleMock.js',
pmcrypto: '<rootDir>/__mocks__/pmcrypto.js',
'sieve.js': '<rootDir>/__mocks__/sieve.js',
},
};
|
module.exports = {
setupFilesAfterEnv: ['./rtl.setup.js'],
verbose: true,
moduleDirectories: ['node_modules'],
transform: {
'^.+\\.(js|tsx?)$': '<rootDir>/jest.transform.js'
},
collectCoverage: true,
collectCoverageFrom: ['src/**/*.{js,jsx,ts,tsx}'],
transformIgnorePatterns: ['node_modules/(?!(proton-shared|react-components)/)'],
moduleNameMapper: {
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)$': '<rootDir>/__mocks__/fileMock.js',
'\\.(css|scss|less)$': '<rootDir>/__mocks__/styleMock.js',
pmcrypto: '<rootDir>/__mocks__/pmcrypto.js',
'sieve.js': '<rootDir>/__mocks__/sieve.js'
}
};
|
Remove debugging statements and provide support for Python 2.7
|
import redis
class RedisPersist:
_redis_connection = None
def __init__(self, host="localhost", port=6379, db=0):
self._redis_connection = redis.StrictRedis(
host=host,
port=port,
db=db
)
self._redis_connection.set('tmp_validate', 'tmp_validate')
def save(self, key=None, jsonstr=None):
if key is None:
raise ValueError("Key must be present to persist game.")
if jsonstr is None:
raise ValueError("JSON is badly formed or not present")
self._redis_connection.set(key, str(jsonstr), ex=(60*60))
def load(self, key=None):
if key is None:
raise ValueError("Key must be present to load game")
return_result = self._redis_connection.get(key)
if return_result is not None:
return_result = str(return_result)
return return_result
|
import redis
class RedisPersist:
_redis_connection = None
def __init__(self, host="localhost", port=6379, db=0):
self._redis_connection = redis.StrictRedis(
host=host,
port=port,
db=db
)
self._redis_connection.set('tmp_validate', 'tmp_validate')
def save(self, key=None, jsonstr=None):
if key is None:
raise ValueError("Key must be present to persist game.")
if jsonstr is None:
raise ValueError("JSON is badly formed or not present")
self._redis_connection.set(key, str(jsonstr))
def load(self, key=None):
if key is None:
raise ValueError("Key must be present to load game")
return_result = self._redis_connection.get(key)
if return_result is not None:
return_result = str(return_result)
return return_result
|
Make this Python 2.x compatible
|
import six
import json
from django.core.urlresolvers import reverse
from django.utils.html import format_html, mark_safe
from django.utils.encoding import python_2_unicode_compatible
CHARTS = {}
class ChartMeta(type):
def __new__(cls, name, bases, attrs):
klass = super(ChartMeta, cls).__new__(cls, name, bases, attrs)
if klass.chart_slug:
CHARTS[klass.chart_slug] = klass
return klass
@six.add_metaclass(ChartMeta)
@python_2_unicode_compatible
class Chart(object):
options = {}
chart_slug = None
columns = None
def get_data(self):
raise NotImplementedError
def __str__(self):
return format_html(
"<div "
"data-chart-options='{0}'"
"data-chart-url='{1}'"
"></div>",
json.dumps(self.options),
reverse(
'djgc-chart-data',
args=(self.chart_slug,),
),
)
|
import six
import json
from django.core.urlresolvers import reverse
from django.utils.html import format_html, mark_safe
CHARTS = {}
class ChartMeta(type):
def __new__(cls, name, bases, attrs):
klass = super(ChartMeta, cls).__new__(cls, name, bases, attrs)
if klass.chart_slug:
CHARTS[klass.chart_slug] = klass
return klass
@six.add_metaclass(ChartMeta)
class Chart(object):
options = {}
chart_slug = None
columns = None
def get_data(self):
raise NotImplementedError
def __str__(self):
return format_html(
"<div "
"data-chart-options='{0}'"
"data-chart-url='{1}'"
"></div>",
json.dumps(self.options),
reverse(
'djgc-chart-data',
args=(self.chart_slug,),
),
)
|
Add whitespace to make markup clearer (whitespace only)
|
<p>So OpenAustralia.org.au helped you find the facts - what next?</p>
<h3>If you have a problem</h3>
<h4>... with a public body or organisation</h4>
<p>The Ombudsman Association can help you find the right organisation to take your complaint to:<br />
<a href="http://www.anzoa.com.au/for-complaints.html">http://www.anzoa.com.au/for-complaints.html</a></p>
<h4>... with how your MP is representing you</h4>
<p>You can contact your MP using the details on their page at OpenAustralia.<br />
<a href="/mp/">Find your MP by entering your postcode</a>.</p>
<h3>If you want to know more</h3>
<h4>... about how how MPs vote</h4>
<p>You can search votes and see how your MP has voted on the policies that matter to you at They Vote For You:<br />
<a href="https://theyvoteforyou.org.au">https://theyvoteforyou.org.au</a></p>
<h4>... from a public authority</h4>
<p>You can ask for information from public authorities using Right To Know. You can also view requests made by other people, and see the responses that they received:<br />
<a href="https://www.righttoknow.org.au/">https://www.righttoknow.org.au/</a></p>
|
<p>So OpenAustralia.org.au helped you find the facts - what next?</p>
<h3>If you have a problem</h3>
<h4>... with a public body or organisation</h4>
<p>The Ombudsman Association can help you find the right organisation to take your complaint to:<br />
<a href="http://www.anzoa.com.au/for-complaints.html">http://www.anzoa.com.au/for-complaints.html</a></p>
<h4>... with how your MP is representing you</h4>
<p>You can contact your MP using the details on their page at OpenAustralia.<br />
<a href="/mp/">Find your MP by entering your postcode</a>.</p>
<h3>If you want to know more</h3>
<h4>... about how how MPs vote</h4>
<p>You can search votes and see how your MP has voted on the policies that matter to you at They Vote For You:<br />
<a href="https://theyvoteforyou.org.au">https://theyvoteforyou.org.au</a></p>
<h4>... from a public authority</h4>
<p>You can ask for information from public authorities using Right To Know. You can also view requests made by other people, and see the responses that they received:<br />
<a href="https://www.righttoknow.org.au/">https://www.righttoknow.org.au/</a></p>
|
Fix for rerunning intro tutorial on previously used database.
|
from snorkel.models import Span, Label
from sqlalchemy.orm.exc import NoResultFound
def add_spouse_label(session, key, cls, person1, person2, value):
try:
person1 = session.query(Span).filter(Span.stable_id == person1).one()
person2 = session.query(Span).filter(Span.stable_id == person2).one()
except NoResultFound as e:
if int(value) == -1:
### Due to variations in the NER output of CoreNLP, some of the included annotations for
### false candidates might cover slightly different text spans when run on some systems,
### so we must skip them.
return
else:
raise e
candidate = session.query(cls).filter(cls.person1 == person1).filter(cls.person2 == person2).first()
if candidate is None:
candidate = session.query(cls).filter(cls.person1 == person2).filter(cls.person2 == person1).one()
label = session.query(Label).filter(Label.candidate == candidate).one_or_none()
if label is None:
label = Label(candidate=candidate, key=key, value=value)
session.add(label)
else:
label.value = int(value)
session.commit()
|
from snorkel.models import Span, Label
from sqlalchemy.orm.exc import NoResultFound
def add_spouse_label(session, key, cls, person1, person2, value):
try:
person1 = session.query(Span).filter(Span.stable_id == person1).one()
person2 = session.query(Span).filter(Span.stable_id == person2).one()
except NoResultFound as e:
if int(value) == -1:
### Due to variations in the NER output of CoreNLP, some of the included annotations for
### false candidates might cover slightly different text spans when run on some systems,
### so we must skip them.
return
else:
raise e
candidate = session.query(cls).filter(cls.person1 == person1).filter(cls.person2 == person2).first()
if candidate is None:
candidate = session.query(cls).filter(cls.person1 == person2).filter(cls.person2 == person1).one()
label = session.query(Label).filter(Label.candidate == candidate).one_or_none()
if label is None:
label = Label(candidate=candidate, key=key, value=value)
session.add(label)
else:
label.value = int(label)
session.commit()
|
Add a help_text string to the admin form
|
import csv
from django import forms
class BulkUploadForm(forms.Form):
data = forms.FileField(help_text="""
<p>Select the CSV file to upload. The file should have a header for
each column you want to populate. When you have selected your
file, click the 'Upload' button below.</p>
""")
def clean(self):
cleaned_data = super(BulkUploadForm, self).clean()
cleaned_data['data'] = BulkUploadForm.load_csv(cleaned_data['data'])
return cleaned_data
@staticmethod
def load_csv(f):
reader = csv.reader(f)
data = []
i = 0
for row in reader:
if i == 0:
header = row
else:
data.append(dict(zip(header, row)))
i += 1
return data
|
import csv
from django import forms
class BulkUploadForm(forms.Form):
data = forms.FileField()
def clean(self):
cleaned_data = super(BulkUploadForm, self).clean()
cleaned_data['data'] = BulkUploadForm.load_csv(cleaned_data['data'])
return cleaned_data
@staticmethod
def load_csv(f):
reader = csv.reader(f)
data = []
i = 0
for row in reader:
if i == 0:
header = row
else:
data.append(dict(zip(header, row)))
i += 1
return data
|
Test Insertion Sort: Test for sorting in ascending order with equal values
|
/* eslint-env mocha */
const InsertionSort = require('../../../src').Algorithms.Sorting.InsertionSort;
const assert = require('assert');
describe('Insertion Sort', () => {
it('should have no data when empty initialization', () => {
const inst = new InsertionSort();
assert.equal(inst.size, 0);
assert.deepEqual(inst.unsortedList, []);
assert.deepEqual(inst.sortedList, []);
});
it('should sort the array', () => {
const inst = new InsertionSort([2, 1, 3, 4]);
assert.equal(inst.size, 4);
assert.deepEqual(inst.unsortedList, [2, 1, 3, 4]);
assert.deepEqual(inst.sortedList, [1, 2, 3, 4]);
assert.equal(inst.toString(), '1, 2, 3, 4');
});
it('should sort the array in ascending order with few equal vals', () => {
const inst = new InsertionSort([2, 1, 3, 4, 2], (a, b) => a < b);
assert.equal(inst.size, 5);
assert.deepEqual(inst.unsortedList, [2, 1, 3, 4, 2]);
assert.deepEqual(inst.sortedList, [1, 2, 2, 3, 4]);
assert.equal(inst.toString(), '1, 2, 2, 3, 4');
});
});
|
/* eslint-env mocha */
const InsertionSort = require('../../../src').Algorithms.Sorting.InsertionSort;
const assert = require('assert');
describe('Insertion Sort', () => {
it('should have no data when empty initialization', () => {
const inst = new InsertionSort();
assert.equal(inst.size, 0);
assert.deepEqual(inst.unsortedList, []);
assert.deepEqual(inst.sortedList, []);
});
it('should sort the array', () => {
const inst = new InsertionSort([2, 1, 3, 4]);
assert.equal(inst.size, 4);
assert.deepEqual(inst.unsortedList, [2, 1, 3, 4]);
assert.deepEqual(inst.sortedList, [1, 2, 3, 4]);
assert.equal(inst.toString(), '1, 2, 3, 4');
});
});
|
Fix ReactiveDict on server (for iron:router)
Note: We don’t officially support Tracker on the server.
|
ReactiveDict._migratedDictData = {}; // name -> data
ReactiveDict._dictsToMigrate = {}; // name -> ReactiveDict
ReactiveDict._loadMigratedDict = function (dictName) {
if (_.has(ReactiveDict._migratedDictData, dictName))
return ReactiveDict._migratedDictData[dictName];
return null;
};
ReactiveDict._registerDictForMigrate = function (dictName, dict) {
if (_.has(ReactiveDict._dictsToMigrate, dictName))
throw new Error("Duplicate ReactiveDict name: " + dictName);
ReactiveDict._dictsToMigrate[dictName] = dict;
};
if (Meteor.isClient && Package.reload) {
// Put old migrated data into ReactiveDict._migratedDictData,
// where it can be accessed by ReactiveDict._loadMigratedDict.
var migrationData = Package.reload.Reload._migrationData('reactive-dict');
if (migrationData && migrationData.dicts)
ReactiveDict._migratedDictData = migrationData.dicts;
// On migration, assemble the data from all the dicts that have been
// registered.
Package.reload.Reload._onMigrate('reactive-dict', function () {
var dictsToMigrate = ReactiveDict._dictsToMigrate;
var dataToMigrate = {};
for (var dictName in dictsToMigrate)
dataToMigrate[dictName] = dictsToMigrate[dictName]._getMigrationData();
return [true, {dicts: dataToMigrate}];
});
}
|
ReactiveDict._migratedDictData = {}; // name -> data
ReactiveDict._dictsToMigrate = {}; // name -> ReactiveDict
ReactiveDict._loadMigratedDict = function (dictName) {
if (_.has(ReactiveDict._migratedDictData, dictName))
return ReactiveDict._migratedDictData[dictName];
return null;
};
ReactiveDict._registerDictForMigrate = function (dictName, dict) {
if (_.has(ReactiveDict._dictsToMigrate, dictName))
throw new Error("Duplicate ReactiveDict name: " + dictName);
ReactiveDict._dictsToMigrate[dictName] = dict;
};
if (Package.reload) {
// Put old migrated data into ReactiveDict._migratedDictData,
// where it can be accessed by ReactiveDict._loadMigratedDict.
var migrationData = Package.reload.Reload._migrationData('reactive-dict');
if (migrationData && migrationData.dicts)
ReactiveDict._migratedDictData = migrationData.dicts;
// On migration, assemble the data from all the dicts that have been
// registered.
Package.reload.Reload._onMigrate('reactive-dict', function () {
var dictsToMigrate = ReactiveDict._dictsToMigrate;
var dataToMigrate = {};
for (var dictName in dictsToMigrate)
dataToMigrate[dictName] = dictsToMigrate[dictName]._getMigrationData();
return [true, {dicts: dataToMigrate}];
});
}
|
Prepend 'veyndan_' tag to each Timber log for easy logcat usage
|
package com.veyndan.redditclient;
import android.app.Application;
import com.squareup.leakcanary.LeakCanary;
import com.twitter.sdk.android.Twitter;
import com.twitter.sdk.android.core.TwitterAuthConfig;
import io.fabric.sdk.android.Fabric;
import timber.log.Timber;
public class RedditClientApp extends Application {
@Override
public void onCreate() {
super.onCreate();
if (BuildConfig.DEBUG) {
Timber.plant(new Timber.DebugTree() {
@Override
protected void log(final int priority, final String tag, final String message,
final Throwable t) {
super.log(priority, "veyndan_" + tag, message, t);
}
});
}
final TwitterAuthConfig authConfig = new TwitterAuthConfig(Config.TWITTER_KEY, Config.TWITTER_SECRET);
Fabric.with(this, new Twitter(authConfig));
LeakCanary.install(this);
}
}
|
package com.veyndan.redditclient;
import android.app.Application;
import com.squareup.leakcanary.LeakCanary;
import com.twitter.sdk.android.Twitter;
import com.twitter.sdk.android.core.TwitterAuthConfig;
import io.fabric.sdk.android.Fabric;
import timber.log.Timber;
public class RedditClientApp extends Application {
@Override
public void onCreate() {
super.onCreate();
if (BuildConfig.DEBUG) {
Timber.plant(new Timber.DebugTree());
}
final TwitterAuthConfig authConfig = new TwitterAuthConfig(Config.TWITTER_KEY, Config.TWITTER_SECRET);
Fabric.with(this, new Twitter(authConfig));
LeakCanary.install(this);
}
}
|
Update validation in Create Content tour
|
(function () {
"use strict";
function NodeNameController($scope) {
var vm = this;
var element = angular.element($scope.model.currentStep.element);
vm.error = false;
vm.initNextStep = initNextStep;
function initNextStep() {
if(element.val().toLowerCase() === 'home') {
$scope.model.nextStep();
} else {
vm.error = true;
}
}
}
angular.module("umbraco").controller("Umbraco.Tours.UmbIntroCreateContent.NodeNameController", NodeNameController);
})();
|
(function () {
"use strict";
function NodeNameController($scope) {
var vm = this;
var element = angular.element($scope.model.currentStep.element);
vm.error = false;
vm.initNextStep = initNextStep;
function initNextStep() {
if(element.val().lowerCase() === 'Home') {
$scope.model.nextStep();
} else {
vm.error = true;
}
}
}
angular.module("umbraco").controller("Umbraco.Tours.UmbIntroCreateContent.NodeNameController", NodeNameController);
})();
|
Add the editor field to the required fields at the book ref.
|
package ryhma57.references;
import java.util.EnumSet;
import ryhma57.backend.BibtexReferenceField;
import static ryhma57.backend.BibtexReferenceField.*;
public class Book extends Reference {
private static EnumSet<BibtexReferenceField> existingFields;
private static EnumSet<BibtexReferenceField> requiredFields, optionalFields;
static {
Book.requiredFields = Reference.createFieldSet(AUTHOR,
EDITOR, TITLE, YEAR, PUBLISHER);
Book.optionalFields = Reference.createFieldSet(VOLUME,
NUMBER, SERIES, ADDRESS, EDITION, MONTH, NOTE);
Book.existingFields = Reference.createExistingSet(
Book.requiredFields, Book.optionalFields);
}
public Book(String id, String author, String title, String year, String publisher) {
super(existingFields, requiredFields, "book");
setID(id);
setField(AUTHOR, author);
setField(TITLE, title);
setField(YEAR, year);
setField(PUBLISHER, publisher);
}
public Book() {
super(existingFields, requiredFields, "book");
}
}
|
package ryhma57.references;
import java.util.EnumSet;
import ryhma57.backend.BibtexReferenceField;
import static ryhma57.backend.BibtexReferenceField.*;
public class Book extends Reference {
private static EnumSet<BibtexReferenceField> existingFields;
private static EnumSet<BibtexReferenceField> requiredFields, optionalFields;
static {
Book.requiredFields = Reference.createFieldSet(AUTHOR,
TITLE, YEAR, PUBLISHER);
Book.optionalFields = Reference.createFieldSet(VOLUME,
NUMBER, SERIES, ADDRESS, EDITION, MONTH, NOTE);
Book.existingFields = Reference.createExistingSet(
Book.requiredFields, Book.optionalFields);
}
public Book(String id, String author, String title, String year, String publisher) {
super(existingFields, requiredFields, "book");
setID(id);
setField(AUTHOR, author);
setField(TITLE, title);
setField(YEAR, year);
setField(PUBLISHER, publisher);
}
public Book() {
super(existingFields, requiredFields, "book");
}
}
|
Fix for building indexes for MongoDB
|
package dbServices
import (
"github.com/DanielRenne/GoCore/core/extensions"
"reflect"
)
//GetIndexes provides a way to reflect on your structure to get structs tagged with `dbIndex`.
//This function is used to generate Indexes for MongoDB and other databases.
func GetDBIndexes(x interface{}) map[string]string {
keys := make(map[string]string)
getDBIndexesRecursive(reflect.ValueOf(x), keys, "")
return keys
}
func getDBIndexesRecursive(val reflect.Value, keys map[string]string, key string) {
kind := val.Kind()
if kind == reflect.Slice {
return
}
for i := 0; i < val.NumField(); i++ {
valueField := val.Field(i)
typeField := val.Type().Field(i)
index := typeField.Tag.Get("dbIndex")
appendKey := extensions.MakeFirstLowerCase(typeField.Name)
if !valueField.CanInterface() {
continue
}
field := valueField.Interface()
fieldval := reflect.ValueOf(field)
switch fieldval.Kind() {
case reflect.Array, reflect.Slice, reflect.Struct:
getDBIndexesRecursive(fieldval, keys, key+appendKey+".")
default:
if index != "" {
keys[key+appendKey] = index
}
}
}
}
|
package dbServices
import (
"github.com/DanielRenne/GoCore/core/extensions"
"reflect"
)
//GetIndexes provides a way to reflect on your structure to get structs tagged with `dbIndex`.
//This function is used to generate Indexes for MongoDB and other databases.
func GetDBIndexes(x interface{}) map[string]string {
keys := make(map[string]string)
getDBIndexesRecursive(reflect.ValueOf(x), keys, "")
return keys
}
func getDBIndexesRecursive(val reflect.Value, keys map[string]string, key string) {
for i := 0; i < val.NumField(); i++ {
valueField := val.Field(i)
typeField := val.Type().Field(i)
index := typeField.Tag.Get("dbIndex")
appendKey := extensions.MakeFirstLowerCase(typeField.Name)
if !valueField.CanInterface() {
continue
}
field := valueField.Interface()
fieldval := reflect.ValueOf(field)
switch fieldval.Kind() {
case reflect.Array, reflect.Slice, reflect.Struct:
getDBIndexesRecursive(fieldval, keys, key+appendKey+".")
default:
if index != "" {
keys[key+appendKey] = index
}
}
}
}
|
Add child_count taken from new Subject property
|
from rest_framework import serializers as ser
from api.base.serializers import JSONAPISerializer, LinksField, JSONAPIListField
class TaxonomyField(ser.Field):
def to_representation(self, obj):
if obj is not None:
return {'id': obj._id,
'text': obj.text}
return None
def to_internal_value(self, data):
return data
class TaxonomySerializer(JSONAPISerializer):
filterable_fields = frozenset([
'text',
'parents',
'id'
])
id = ser.CharField(source='_id', required=True)
text = ser.CharField(max_length=200)
parents = JSONAPIListField(child=TaxonomyField())
child_count = ser.IntegerField()
links = LinksField({
'parents': 'get_parent_urls',
'self': 'get_absolute_url',
})
def get_parent_urls(self, obj):
return [p.get_absolute_url() for p in obj.parents]
def get_absolute_url(self, obj):
return obj.get_absolute_url()
class Meta:
type_ = 'taxonomies'
|
from rest_framework import serializers as ser
from api.base.serializers import JSONAPISerializer, LinksField, JSONAPIListField
class TaxonomyField(ser.Field):
def to_representation(self, obj):
if obj is not None:
return {'id': obj._id,
'text': obj.text}
return None
def to_internal_value(self, data):
return data
class TaxonomySerializer(JSONAPISerializer):
filterable_fields = frozenset([
'text',
'parents',
'id'
])
id = ser.CharField(source='_id', required=True)
text = ser.CharField(max_length=200)
parents = JSONAPIListField(child=TaxonomyField())
links = LinksField({
'parents': 'get_parent_urls',
'self': 'get_absolute_url',
})
def get_parent_urls(self, obj):
return [p.get_absolute_url() for p in obj.parents]
def get_absolute_url(self, obj):
return obj.get_absolute_url()
class Meta:
type_ = 'taxonomies'
|
Adjust IMC2 trigger regex to handle multiple colons correctly.
|
import re
from battlesnake.core.triggers import TriggerTable
from battlesnake.core.triggers import Trigger
from battlesnake.plugins.imc2 import imc2
from battlesnake.plugins.imc2.channel_map import MUX_TO_IMC2_CHANNEL_MAP
class ChannelMessageTrigger(Trigger):
"""
Tries to identify potential IMC2 channel activity.
"""
line_regex = re.compile(r'.*\[(?P<channel>.*)\] (?P<author>[\w`$_\-.,\']+)[:] (?P<message>.*)\r')
def run(self, protocol, line, re_match):
"""
:param basestring line: The line that matched the trigger.
:param re.MatchObject re_match: A Python MatchObject for the regex
groups specified in the Trigger's regex string.
"""
channel = re_match.group("channel")
author = re_match.group("author")
message = re_match.group("message")
imc2_channel = MUX_TO_IMC2_CHANNEL_MAP.get(channel, None)
imc2.IMC2_PROTO_INSTANCE.data_out(
text=message, packet_type="broadcast", sender=author,
channel=imc2_channel)
class IMC2TriggerTable(TriggerTable):
triggers = [
ChannelMessageTrigger,
]
|
import re
from battlesnake.core.triggers import TriggerTable
from battlesnake.core.triggers import Trigger
from battlesnake.plugins.imc2 import imc2
from battlesnake.plugins.imc2.channel_map import MUX_TO_IMC2_CHANNEL_MAP
class ChannelMessageTrigger(Trigger):
"""
Tries to identify potential IMC2 channel activity.
"""
line_regex = re.compile(r'.*\[(?P<channel>.*)\] (?P<author>.*): (?P<message>.*)\r')
def run(self, protocol, line, re_match):
"""
:param basestring line: The line that matched the trigger.
:param re.MatchObject re_match: A Python MatchObject for the regex
groups specified in the Trigger's regex string.
"""
channel = re_match.group("channel")
author = re_match.group("author")
message = re_match.group("message")
imc2_channel = MUX_TO_IMC2_CHANNEL_MAP.get(channel, None)
imc2.IMC2_PROTO_INSTANCE.data_out(
text=message, packet_type="broadcast", sender=author,
channel=imc2_channel)
class IMC2TriggerTable(TriggerTable):
triggers = [
ChannelMessageTrigger,
]
|
Store renderer's objects in an array.
|
var objectMappings = {
circle: function(object) {
return new SvgCircle()
.setRadius(object.radius)
.setTransform(object.getTransformation() || Transformation.IDENTITY)
.setFill(object.fill || "#ffffff");
},
rectangle: function(object) {
return new SvgRectangle()
.setWidth(object.width || 0)
.setHeight(object.height || 0)
.setFill(object.fill || '#ffffff');
}
};
function SvgRenderer() {
this.objects = [];
this.rootElement = null;
}
extend(Renderer).withObject(SvgRenderer);
SvgRenderer.prototype.attachTo = function(parentElement) {
parentElement.appendChild(this.rootElement.element);
};
SvgRenderer.prototype.addElement = function(element) {
this.elements.push(element);
};
SvgRenderer.fromModel = function(model, width, height, fullscreen) {
var renderer = new SvgRenderer();
if (fullscreen) {
renderer.rootElement = SvgRoot.fullScreenSvgForWindow();
} else {
renderer.rootElement = new SvgRoot(width, height, false);
}
for (var i in model.objects) {
var obj = model.objects[i];
var element = objectMappings[obj.shape](obj) || null;
if (element !== null) {
renderer.objects[i] = element;
renderer.rootElement.addElement(element);
}
}
return renderer;
};
|
var objectMappings = {
circle: function(object) {
return new SvgCircle()
.setRadius(object.radius)
.setTransform(object.getTransformation() || Transformation.IDENTITY)
.setFill(object.fill || "#ffffff");
},
rectangle: function(object) {
return new SvgRectangle()
.setWidth(object.width || 0)
.setHeight(object.height || 0)
.setFill(object.fill || '#ffffff');
}
};
function SvgRenderer() {
this.elements = [];
this.objectMap = {};
this.rootElement = null;
}
extend(Renderer).withObject(SvgRenderer);
SvgRenderer.prototype.attachTo = function(parentElement) {
parentElement.appendChild(this.rootElement.element);
};
SvgRenderer.prototype.addElement = function(element) {
this.elements.push(element);
};
SvgRenderer.fromModel = function(model, width, height, fullscreen) {
var renderer = new SvgRenderer();
if (fullscreen) {
renderer.rootElement = SvgRoot.fullScreenSvgForWindow();
} else {
renderer.rootElement = new SvgRoot(width, height, false);
}
for (var i in model.objects) {
var obj = model.objects[i];
var element = objectMappings[obj.shape](obj) || null;
if (element !== null) {
renderer.objectMap[obj] = element;
renderer.rootElement.addElement(element);
}
}
return renderer;
};
|
Update display for player order
|
package vrampal.connectfour.robot;
import vrampal.connectfour.core.Player;
public class ConnectFourRobotStats implements Runnable {
public static void main(String[] args) {
new ConnectFourRobotStats().run();
}
private static final int NB_TOTAL_GAME = 1000000;
private int nbYellowWin = 0;
private int nbRedWin = 0;
private int nbDraw = 0;
@Override
public void run() {
long beginTime = System.currentTimeMillis();
for (int i = 0; i < NB_TOTAL_GAME; i++) {
ConnectFourRobot robotGame = new ConnectFourRobot(false);
robotGame.run();
Player winner = robotGame.getGame().getWinner();
if (winner == null) {
nbDraw++;
} else if (winner.getName().equals("Yellow")) {
nbYellowWin++;
} else if (winner.getName().equals("Red")) {
nbRedWin++;
} else {
throw new RuntimeException("Unknown winner");
}
}
long endTime = System.currentTimeMillis();
System.out.println("Nb yellow win: " + nbYellowWin);
System.out.println("Nb red win: " + nbRedWin);
System.out.println("Nb draw: " + nbDraw);
System.out.println("Elapsed time: " + (endTime - beginTime) + " ms");
}
}
|
package vrampal.connectfour.robot;
import vrampal.connectfour.core.Player;
public class ConnectFourRobotStats implements Runnable {
public static void main(String[] args) {
new ConnectFourRobotStats().run();
}
private static final int NB_TOTAL_GAME = 1000000;
private int nbRedWin = 0;
private int nbYellowWin = 0;
private int nbDraw = 0;
@Override
public void run() {
long beginTime = System.currentTimeMillis();
for (int i = 0; i < NB_TOTAL_GAME; i++) {
ConnectFourRobot robotGame = new ConnectFourRobot(false);
robotGame.run();
Player winner = robotGame.getGame().getWinner();
if (winner == null) {
nbDraw++;
} else if (winner.getName().equals("Red")) {
nbRedWin++;
} else if (winner.getName().equals("Yellow")) {
nbYellowWin++;
} else {
throw new RuntimeException("Unknown winner");
}
}
long endTime = System.currentTimeMillis();
System.out.println("Nb red win: " + nbRedWin);
System.out.println("Nb yellow win: " + nbYellowWin);
System.out.println("Nb draw: " + nbDraw);
System.out.println("Elapsed time: " + (endTime - beginTime) + " ms");
}
}
|
Put file in correct place
|
const path = require('path');
const jetpack = require('fs-jetpack');
const archive = require('./archive');
const info = require('./info');
const manifest = require('./manifest');
const config = require('./util/config');
module.exports = (packageName, targetDir) => {
targetDir = targetDir || process.cwd();
const dir = path.join(targetDir, packageName);
jetpack.dir(dir);
if (jetpack.list(dir).length > 0) {
throw new Error('Target directory is not empty');
}
return info(packageName)
.then(archive.download)
.then(archive.verify)
.then(args => {
const data = manifest.expand(args.packageInfo);
jetpack.write(
path.join(dir, config.get('filename')),
JSON.stringify(data, null, 2)
);
return archive.extract(args.tmpFile, targetDir);
});
};
|
const path = require('path');
const jetpack = require('fs-jetpack');
const archive = require('./archive');
const info = require('./info');
const manifest = require('./manifest');
const config = require('./util/config');
module.exports = (packageName, targetDir) => {
targetDir = targetDir || process.cwd();
const dir = path.join(targetDir, packageName);
jetpack.dir(dir);
if (jetpack.list(dir).length > 0) {
throw new Error('Target directory is not empty');
}
return info(packageName)
.then(archive.download)
.then(archive.verify)
.then(args => {
const data = manifest.expand(args.packageInfo);
jetpack.write(
path.join(targetDir, config.get('filename')),
JSON.stringify(data, null, 2)
);
return archive.extract(args.tmpFile, targetDir);
});
};
|
Use view.close() to close view.
|
import sublime
from unittest import TestCase
class ViewTestCase(TestCase):
def setUp(self):
self.view = sublime.active_window().new_file()
settings = self.view.settings()
default_settings = getattr(self.__class__, 'view_settings', {})
for key, value in default_settings.items():
settings.set(key, value)
def tearDown(self):
if self.view:
self.view.set_scratch(True)
self.view.close()
def _viewContents(self):
return self.view.substr(sublime.Region(0, self.view.size()))
def assertViewContentsEqual(self, text):
self.assertEqual(self._viewContents(), text)
|
import sublime
from unittest import TestCase
class ViewTestCase(TestCase):
def setUp(self):
self.view = sublime.active_window().new_file()
settings = self.view.settings()
default_settings = getattr(self.__class__, 'view_settings', {})
for key, value in default_settings.items():
settings.set(key, value)
def tearDown(self):
if self.view:
self.view.set_scratch(True)
self.view.window().focus_view(self.view)
self.view.window().run_command("close_file")
def _viewContents(self):
return self.view.substr(sublime.Region(0, self.view.size()))
def assertViewContentsEqual(self, text):
self.assertEqual(self._viewContents(), text)
|
Indent properly, get helloworld working
|
#!/usr/bin/env python
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.escape
import tornado.template
from tornado.options import define, options
define("port", default=8888, help="run on the given port", type=int)
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
class ProjectHandler(tornado.web.RequestHandler):
def get(self, project_id):
self.write("You requested the project " + project_id)
def main():
tornado.options.parse_command_line()
application = tornado.web.Application([
(r"/", MainHandler),
(r"/(\w+)", ProjectHandler),
])
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
|
#!/usr/bin/env python
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.escape
import tornado.template
from tornado.options import define, options
define("port", default=8888, help="run on the given port", type=int)
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
class ProjectHandler(tornado.web.RequestHandler):
def get(self, project_id):
self.write("You requested the project " + project_id)
def main():
tornado.options.parse_command_line()
application = tornado.web.Application([
(r"/", MainHandler),
(r"/(\w+)", ProjectHandler),
])
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
|
Update sensor server to grab from disk.
|
"""
This runs continuously and serves our sensor readings when requested.
Base script from:
http://ilab.cs.byu.edu/python/socket/echoserver.html
"""
import socket
import json
class SensorServer:
def __init__(self, host='', port=8888, size=1024, backlog=5):
self.host = host
self.port = port
self.size = size
self.backlog = backlog
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s.bind((host, port))
self.s.listen(backlog)
def serve_readings(self):
client, address = self.s.accept()
with open('readings.json') as f:
data = json.load(f)
try:
print("Sending: %s" % str(data))
client.send(data.encode(encoding='utf_8'))
except:
print("Couldn't send data.")
client.close()
if __name__ == '__main__':
input("Start sensors.py in the background then hit enter to start server.")
ss = SensorServer
while 1:
ss.serve_readings()
|
"""
This runs continuously and serves our sensor readings when requested.
Base script from:
http://ilab.cs.byu.edu/python/socket/echoserver.html
"""
import socket
from sensors import Sensors
class SensorServer:
def __init__(self, host='', port=8888, size=1024, backlog=5):
self.host = host
self.port = port
self.size = size
self.backlog = backlog
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s.bind((host, port))
self.s.listen(backlog)
def serve_readings(self, sensors):
client, address = self.s.accept()
data = str(sensors.get_all_readings())
try:
print("Sending: %s" % str(data))
client.send(data.encode(encoding='utf_8'))
except:
print("Couldn't send data.")
client.close()
if __name__ == '__main__':
# Input pins.
ir_pins = [24, 21]
sonar_pins = [[25, 8]]
# Get objects.
sensors = Sensors(ir_pins, sonar_pins)
ss = SensorServer()
while 1:
ss.serve_readings(sensors)
sensors.cleanup_gpio()
|
Remove unsupport M2M field in channelAdmin handler. Removes traceback when DEBUG=True.
|
#
# This sets up how models are displayed
# in the web admin interface.
#
from django.contrib import admin
from src.comms.models import ChannelDB
class MsgAdmin(admin.ModelAdmin):
list_display = ('id', 'db_date_sent', 'db_sender', 'db_receivers',
'db_channels', 'db_message', 'db_lock_storage')
list_display_links = ("id",)
ordering = ["db_date_sent", 'db_sender', 'db_receivers', 'db_channels']
#readonly_fields = ['db_message', 'db_sender', 'db_receivers', 'db_channels']
search_fields = ['id', '^db_date_sent', '^db_message']
save_as = True
save_on_top = True
list_select_related = True
#admin.site.register(Msg, MsgAdmin)
class ChannelAdmin(admin.ModelAdmin):
list_display = ('id', 'db_key', 'db_lock_storage')
list_display_links = ("id", 'db_key')
ordering = ["db_key"]
search_fields = ['id', 'db_key', 'db_aliases']
save_as = True
save_on_top = True
list_select_related = True
fieldsets = (
(None, {'fields': (('db_key',), 'db_lock_storage')}),
)
admin.site.register(ChannelDB, ChannelAdmin)
|
#
# This sets up how models are displayed
# in the web admin interface.
#
from django.contrib import admin
from src.comms.models import ChannelDB
class MsgAdmin(admin.ModelAdmin):
list_display = ('id', 'db_date_sent', 'db_sender', 'db_receivers',
'db_channels', 'db_message', 'db_lock_storage')
list_display_links = ("id",)
ordering = ["db_date_sent", 'db_sender', 'db_receivers', 'db_channels']
#readonly_fields = ['db_message', 'db_sender', 'db_receivers', 'db_channels']
search_fields = ['id', '^db_date_sent', '^db_message']
save_as = True
save_on_top = True
list_select_related = True
#admin.site.register(Msg, MsgAdmin)
class ChannelAdmin(admin.ModelAdmin):
list_display = ('id', 'db_key', 'db_lock_storage', "db_subscriptions")
list_display_links = ("id", 'db_key')
ordering = ["db_key"]
search_fields = ['id', 'db_key', 'db_aliases']
save_as = True
save_on_top = True
list_select_related = True
fieldsets = (
(None, {'fields': (('db_key',), 'db_lock_storage')}),
)
admin.site.register(ChannelDB, ChannelAdmin)
|
Add ChannelData length to struct
|
package stun
import (
"encoding/binary"
"github.com/pkg/errors"
)
type ChannelData struct {
ChannelNumber uint16
Length uint16
Data []byte
}
func NewChannelData(packet []byte) (*ChannelData, error) {
cn, err := getChannelNumber(packet)
if err != nil {
return nil, err
}
return &ChannelData{
ChannelNumber: cn,
Length: getChannelLength(packet),
Data: packet[4:],
}, nil
}
// 0b01: ChannelData message (since the channel number is the first
// field in the ChannelData message and channel numbers fall in the
// range 0x4000 - 0x7FFF).
func getChannelNumber(header []byte) (uint16, error) {
cn := binary.BigEndian.Uint16(header)
if cn < 0x4000 || cn > 0x7FFF {
return 0, errors.Errorf("ChannelNumber is out of range: %d", cn)
}
return cn, nil
}
func getChannelLength(header []byte) uint16 {
return binary.BigEndian.Uint16(header[2:])
}
|
package stun
import (
"encoding/binary"
"github.com/pkg/errors"
)
type ChannelData struct {
ChannelNumber uint16
Data []byte
}
func NewChannelData(packet []byte) (*ChannelData, error) {
cn, err := getChannelNumber(packet)
if err != nil {
return nil, err
}
return &ChannelData{
ChannelNumber: cn,
Data: packet,
}, nil
}
// 0b01: ChannelData message (since the channel number is the first
// field in the ChannelData message and channel numbers fall in the
// range 0x4000 - 0x7FFF).
func getChannelNumber(header []byte) (uint16, error) {
cn := binary.BigEndian.Uint16(header)
if cn < 0x4000 || cn > 0x7FFF {
return 0, errors.Errorf("ChannelNumber is out of range: %d", cn)
}
return cn, nil
}
|
Add missing cdata tags to index scene.
|
var _ = require('underscore'),
Vector = require("./vector"),
path = require("path");
'use strict';
var IndexScene = function(file){
var self = this;
self.xml = "<scene><spawn position='0 0 10' /><skybox style='color: linear-gradient(#fff, #99f);' />";
var i = 0;
_.each(file, function(filename){
var v = new Vector(i * 3,1,0),
name = path.basename(filename, '.xml'),
pathname = path.basename(filename);
self.xml += "<billboard position='" + v.toString() + "'><![CDATA[<h3 style='text-align: center; font-size: 3em'>" + name +"</h3>]]></billboard>";
v.z += 0.28;
self.xml += "<link position='" + v.toString() + "' href='/" + pathname + "' scale='0.25 0.25 0.25' />";
i++;
});
self.xml += "</scene>";
}
IndexScene.prototype.toXml = function(){
return this.xml;
};
module.exports = IndexScene;
|
var _ = require('underscore'),
Vector = require("./vector"),
path = require("path");
'use strict';
var IndexScene = function(file){
var self = this;
self.xml = "<scene><spawn position='0 0 10' /><skybox style='color: linear-gradient(#fff, #99f);' />";
var i = 0;
_.each(file, function(filename){
var v = new Vector(i * 3,1,0),
name = path.basename(filename, '.xml'),
pathname = path.basename(filename);
self.xml += "<billboard position='" + v.toString() + "'><h3 style='text-align: center; font-size: 3em'>" + name +"</h3></billboard>";
v.z += 0.28;
self.xml += "<link position='" + v.toString() + "' href='/" + pathname + "' scale='0.25 0.25 0.25' />";
i++;
});
self.xml += "</scene>";
}
IndexScene.prototype.toXml = function(){
return this.xml;
};
module.exports = IndexScene;
|
Use HTTPS for the project url
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
import inflection
setup(
name='inflection',
version=inflection.__version__,
description="A port of Ruby on Rails inflector to Python",
long_description=open('README.rst').read(),
author='Janne Vanhala',
author_email='janne.vanhala@gmail.com',
url='https://github.com/jpvanhal/inflection',
license='MIT',
py_modules=['inflection'],
zip_safe=False,
python_requires='>=3.5',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
],
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
import inflection
setup(
name='inflection',
version=inflection.__version__,
description="A port of Ruby on Rails inflector to Python",
long_description=open('README.rst').read(),
author='Janne Vanhala',
author_email='janne.vanhala@gmail.com',
url='http://github.com/jpvanhal/inflection',
license='MIT',
py_modules=['inflection'],
zip_safe=False,
python_requires='>=3.5',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
],
)
|
Fix rock paper scissors test, introduce deck config
|
"use strict";
const nodeUuid = require("node-uuid"),
_ = require("lodash"),
BeginningState = require("dc-game-states").BeginningState,
GameData = require("dc-engine").GameData;
function Game($players, $deckConfig, $choiceProvider) {
let uuid = nodeUuid.v1();
let choiceProvider, gameData, state;
function initialize() {
choiceProvider = $choiceProvider;
gameData = new GameData($players, $deckConfig);
state = new BeginningState(gameData, choiceProvider);
$players = $deckConfig = $choiceProvider = null;
}
// Returns promise for boolean:
// true if game should continue
// false if game is over
function doNext() {
return state.go()
.then(function(newState) {
state = newState;
return !!state;
});
}
this.doNext = doNext;
function getPlayerIndexById(playerId) {
return _.findIndex(gameData.players, { id: playerId });
}
this.getPlayerIndexById = getPlayerIndexById;
Object.defineProperties(this, {
id: {
enumerable: true,
get: function() {
return uuid;
}
},
players: {
enumerable: true,
get: function() {
return gameData.players;
}
}
});
initialize();
}
module.exports = Game;
|
"use strict";
const nodeUuid = require("node-uuid"),
BeginningState = require("dc-game-states").BeginningState,
GameData = require("dc-engine").GameData;
function Game($players, $deckConfig, $choiceProvider) {
let uuid = nodeUuid.v1();
let choiceProvider, gameData, state;
function initialize() {
choiceProvider = $choiceProvider;
gameData = new GameData($players, $deckConfig);
state = new BeginningState(gameData, choiceProvider);
$players = $deckConfig = $choiceProvider = null;
}
// Returns promise for boolean:
// true if game should continue
// false if game is over
function doNext() {
return state.go()
.then(function(newState) {
state = newState;
return !!state;
});
}
this.doNext = doNext;
Object.defineProperties(this, {
id: {
enumerable: true,
get: function() {
return uuid;
}
},
players: {
enumerable: true,
get: function() {
return gameData.players;
}
}
});
initialize();
}
module.exports = Game;
|
Fix a compiler warning by explicitly passing null.
|
// Copyright 2010 Steven Dee. 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.
goog.provide('jsprettify.example');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('jsprettify.prettifyStr');
jsprettify.example.doJsprettifyExample = function() {
var input = goog.dom.$('input');
var output = goog.dom.$('output');
var updateText = function(e) {
if (e)
e.stopPropagation();
goog.dom.setTextContent(output, jsprettify.prettifyStr(input.value));
};
updateText(null);
goog.events.listen(input, goog.events.EventType.KEYUP, updateText);
};
window['doJsprettifyExample'] = jsprettify.example.doJsprettifyExample;
|
// Copyright 2010 Steven Dee. 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.
goog.provide('jsprettify.example');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('jsprettify.prettifyStr');
jsprettify.example.doJsprettifyExample = function() {
var input = goog.dom.$('input');
var output = goog.dom.$('output');
var updateText = function(e) {
if (e)
e.stopPropagation();
goog.dom.setTextContent(output, jsprettify.prettifyStr(input.value));
};
updateText();
goog.events.listen(input, goog.events.EventType.KEYUP, updateText);
};
window['doJsprettifyExample'] = jsprettify.example.doJsprettifyExample;
|
Add get list accout method.
|
package com.growthbeat.model;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.codehaus.jackson.type.TypeReference;
import com.growthbeat.Context;
public class Account extends Model {
private String id;
private String name;
private Date created;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public static Account findById(String id, Context context) {
return get(context, String.format("1/accounts/%s", id), new HashMap<String, Object>(), Account.class);
}
public static List<Account> findListById(String id, Context context) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("id", id);
return get(context, "1/accounts/", params, new TypeReference<List<Account>>() {
});
}
public static Account create(String name, Context context) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("name", name);
return post(context, "1/accounts", params, Account.class);
}
}
|
package com.growthbeat.model;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.growthbeat.Context;
public class Account extends Model {
private String id;
private String name;
private Date created;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public static Account findById(String id, Context context) {
return get(context, String.format("1/accounts/%s", id), new HashMap<String, Object>(), Account.class);
}
public static Account create(String name, Context context) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("name", name);
return post(context, "1/accounts", params, Account.class);
}
}
|
Remove password from 'listdb' command
|
<?php
namespace BackupCli\Commands;
use BackupCli\Config;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ProfileListDb extends Command
{
protected function configure()
{
$this->setName('profile:listdb')->setDescription('Lists all the existing database profiles.');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
// Database data.
$databases = Config::getFile('database');
foreach ($databases as $profile => $data) {
$dbs[] = [$profile, $data['type'], $data['database'], $data['user'], $data['host'], $data['port']];
}
// Output table.
$table = new Table($output);
$table->setHeaders(['Profile', 'Type', 'Database', 'Username', 'Server', 'Port'])->setRows($dbs);
$table->render();
}
}
|
<?php
namespace BackupCli\Commands;
use BackupCli\Config;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ProfileListDb extends Command
{
protected function configure()
{
$this->setName('profile:listdb')->setDescription('Lists all the existing database profiles.');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
// Database data.
$databases = Config::getFile('database');
foreach ($databases as $profile => $data) {
$dbs[] = [$profile, $data['type'], $data['database'], $data['user'], $data['pass'], $data['host'], $data['port']];
}
// Output table.
$table = new Table($output);
$table->setHeaders(['Profile', 'Type', 'Database', 'Username', 'Password', 'Server', 'Port'])->setRows($dbs);
$table->render();
}
}
|
Correct a Property Name Typo
|
<?php
/**
* This file is part of PMG\Queue
*
* Copyright (c) PMG <https://www.pmg.com>
*
* For full copyright information see the LICENSE file distributed
* with this source code.
*
* @license http://opensource.org/licenses/MIT MIT
*/
namespace PMG\Queue;
/**
* Default implementation of the `Envelop` with no extras.
*
* @since 2.0
*/
class DefaultEnvelope implements Envelope
{
protected $message;
protected $attempts;
public function __construct(Message $message, $attempts=0)
{
$this->message = $message;
$this->attempts = $attempts;
}
/**
* {@inheritdoc}
*/
public function attempts()
{
return $this->attempts;
}
/**
* {@inheritdoc}
*/
public function unwrap()
{
return $this->message;
}
/**
* {@inheritdoc}
*/
public function retry()
{
$new = clone $this;
$new->attempts++;
return $new;
}
}
|
<?php
/**
* This file is part of PMG\Queue
*
* Copyright (c) PMG <https://www.pmg.com>
*
* For full copyright information see the LICENSE file distributed
* with this source code.
*
* @license http://opensource.org/licenses/MIT MIT
*/
namespace PMG\Queue;
/**
* Default implementation of the `Envelop` with no extras.
*
* @since 2.0
*/
class DefaultEnvelope implements Envelope
{
protected $message;
protected $attemps;
public function __construct(Message $message, $attempts=0)
{
$this->message = $message;
$this->attempts = $attempts;
}
/**
* {@inheritdoc}
*/
public function attempts()
{
return $this->attempts;
}
/**
* {@inheritdoc}
*/
public function unwrap()
{
return $this->message;
}
/**
* {@inheritdoc}
*/
public function retry()
{
$new = clone $this;
$new->attempts++;
return $new;
}
}
|
Add UTF8 compatibility switch for py2.
|
#coding=utf-8
import unittest
from s2f.Sanitize import (
sanitize_prefix,
sanitize_for_latex
)
class TestSanitize(unittest.TestCase):
""" Test case for the Sanitize module """
def testSanitizePrefix(self):
""" The function sanitize_prefix should only allow for lower case ASCII
letters, digits and the hyphen. Upper case letters are supposed to be
converted to lower case, everything else is supposed to be omitted.
"""
self.assertEqual(sanitize_prefix('_. Testü@# - .5$ç§÷≠0π00'),
'test-5000')
def testSanitizeForLatex(self):
""" LaTeX special characters are supposed to be escaped. """
self.assertEqual(sanitize_for_latex('I am 100% certain!'),
r'I am 100\% certain!')
self.assertEqual(sanitize_for_latex('Toto & Harry'),
r'Toto \& Harry')
self.assertEqual(sanitize_for_latex('~50%'), r'\~50\%')
self.assertEqual(sanitize_for_latex('%_&~'), r'\%\_\&\~')
|
import unittest
from s2f.Sanitize import (
sanitize_prefix,
sanitize_for_latex
)
class TestSanitize(unittest.TestCase):
""" Test case for the Sanitize module """
def testSanitizePrefix(self):
""" The function sanitize_prefix should only allow for lower case ASCII
letters, digits and the hyphen. Upper case letters are supposed to be
converted to lower case, everything else is supposed to be omitted.
"""
self.assertEqual(sanitize_prefix('_. Testü@# - .5$ç§÷≠0π00'),
'test-5000')
def testSanitizeForLatex(self):
""" LaTeX special characters are supposed to be escaped. """
self.assertEqual(sanitize_for_latex('I am 100% certain!'),
r'I am 100\% certain!')
self.assertEqual(sanitize_for_latex('Toto & Harry'),
r'Toto \& Harry')
self.assertEqual(sanitize_for_latex('~50%'), r'\~50\%')
self.assertEqual(sanitize_for_latex('%_&~'), r'\%\_\&\~')
|
Fix imported exception & protect DELETE routes too.
|
<?php
namespace Rogue\Http\Middleware;
use Closure;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Auth\Middleware\Authenticate;
class AuthenticateApi extends Authenticate
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string[] ...$guards
* @return mixed
*
* @throws \Illuminate\Auth\AuthenticationException
*/
public function handle($request, Closure $next, ...$guards)
{
// Only protected POST, PUT, and DELETE routes
if (! in_array($request->method(), ['POST', 'PUT', 'DELETE'])) {
return $next($request);
}
// Allow using the `X-DS-Rogue-API-Key` header to override auth.
if ($request->hasHeader('X-DS-Rogue-API-Key')) {
if ($request->header('X-DS-Rogue-API-Key') !== config('app.api_key')) {
throw new AuthenticationException;
}
return $next($request);
}
// Otherwise, we can't do anything!
// @TODO: Instead, pass on to default auth middleware with Gateway guard.
throw new AuthenticationException;
}
}
|
<?php
namespace Rogue\Http\Middleware;
use Closure;
class AuthenticateApi
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->method() === 'POST' || $request->method() === 'PUT') {
if ($request->header('X-DS-Rogue-API-Key') !== env('ROGUE_API_KEY')) {
throw new UnauthorizedAccessException;
}
}
return $next($request);
}
}
|
Change camera position to use state
|
import {Entity} from 'aframe-react';
import React from 'react';
import CameraAnimation from './CameraAnimation';
import Cursor from './Cursor';
export default class Camera extends React.Component {
constructor(props) {
super(props);
this.state = { currentPosition: [10, 0, 20]}
}
render() {
return (
<Entity position={ this.state.currentPosition }>
<CameraAnimation />
<Entity camera=""
look-controls=""
wasd-controls={{enabled: true}}>
<Cursor />
</Entity>
</Entity>
);
}
}
|
import {Entity} from 'aframe-react';
import React from 'react';
import CameraAnimation from './CameraAnimation';
import Cursor from './Cursor';
export default class Camera extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<Entity position={[10, 0, 20]}
rotation={[0, 0, 0]}>
<CameraAnimation />
<Entity camera=""
look-controls=""
wasd-controls={{enabled: true}}>
<Cursor />
</Entity>
</Entity>
);
}
}
|
Switch from styled(Value) to Value.extend
|
import React from 'react'
import {storiesOf} from '@storybook/react'
import data from './dataMock'
import Component from './index'
import Value from '../Value'
const ValueComponent = Value.extend`
font-style: italic;
color: ${({type}) => {
switch (type) {
case 'string':
return 'orange'
case 'function':
return 'lightblue'
case 'number':
return 'red'
default:
return 'green'
}
}};
`
const CustomComponent = ({data}) => (
<Component ValueComponent={ValueComponent} data={data} />
)
storiesOf(Component.displayName, module)
.add('default', () => <Component data={data} />)
.add('custom presentation', () => <CustomComponent data={data} />)
|
import React from 'react'
import {storiesOf} from '@storybook/react'
import styled from 'styled-components'
import data from './dataMock'
import Component from './index'
import Value from '../Value'
const ValueComponent = styled(Value)`
font-weight: normal;
font-style: italic;
color: ${({type}) => {
switch (type) {
case 'string':
return 'orange'
case 'function':
return 'lightblue'
case 'number':
return 'red'
default:
return 'green'
}
}};
`
const CustomComponent = ({data}) => (
<Component ValueComponent={ValueComponent} data={data} />
)
storiesOf(Component.displayName, module)
.add('default', () => <Component data={data} />)
.add('custom presentation', () => <CustomComponent data={data} />)
|
Use Pillow instead of PILwoTK
|
from setuptools import setup, find_packages
setup(
name='zeit.content.gallery',
version='2.4.2dev',
author='gocept',
author_email='mail@gocept.com',
url='https://svn.gocept.com/repos/gocept-int/zeit.cms',
description="ZEIT portraitbox",
packages=find_packages('src'),
package_dir = {'': 'src'},
include_package_data = True,
zip_safe=False,
license='gocept proprietary',
namespace_packages = ['zeit', 'zeit.content'],
install_requires=[
'Pillow',
'gocept.form',
'setuptools',
'zeit.cms>=1.46dev',
'zeit.imp>=0.12dev',
'zeit.wysiwyg',
'zope.app.appsetup',
'zope.app.testing',
'zope.component',
'zope.formlib',
'zope.interface',
'zope.publisher',
'zope.security',
'zope.testing',
],
)
|
from setuptools import setup, find_packages
setup(
name='zeit.content.gallery',
version='2.4.2dev',
author='gocept',
author_email='mail@gocept.com',
url='https://svn.gocept.com/repos/gocept-int/zeit.cms',
description="ZEIT portraitbox",
packages=find_packages('src'),
package_dir = {'': 'src'},
include_package_data = True,
zip_safe=False,
license='gocept proprietary',
namespace_packages = ['zeit', 'zeit.content'],
install_requires=[
'PILwoTk',
'gocept.form',
'setuptools',
'zeit.cms>=1.46dev',
'zeit.imp>=0.12dev',
'zeit.wysiwyg',
'zope.app.appsetup',
'zope.app.testing',
'zope.component',
'zope.formlib',
'zope.interface',
'zope.publisher',
'zope.security',
'zope.testing',
],
)
|
3: Implement example producer
Small refactoring
Task-Url:
http://github.com/sergej-samsonow/code-generator/issues/issue/3
|
package com.github.sergejsamsonow.codegenerator.pojo.renderer;
import com.github.sergejsamsonow.codegenerator.api.CodeFormat;
import com.github.sergejsamsonow.codegenerator.api.MethodCodeWriter;
import com.github.sergejsamsonow.codegenerator.pojo.model.PojoBean;
import com.github.sergejsamsonow.codegenerator.pojo.model.PojoProperty;
public class Setter extends AbstractPropertyRenderer<PojoProperty, PojoBean> {
public Setter(CodeFormat format) {
super(format);
}
@Override
protected void writePropertyCode(PojoProperty property) {
String type = property.getDeclarationType();
String field = property.getFieldName();
String name = property.getSetterName();
MethodCodeWriter method = getMethodCodeWriter();
method.start("public void %s(%s %s) {", name, type, field);
method.code("this.%s = %s;", field, field);
method.end();
}
}
|
package com.github.sergejsamsonow.codegenerator.pojo.renderer;
import com.github.sergejsamsonow.codegenerator.api.CodeFormat;
import com.github.sergejsamsonow.codegenerator.api.MethodCodeWriter;
import com.github.sergejsamsonow.codegenerator.pojo.model.PojoBean;
import com.github.sergejsamsonow.codegenerator.pojo.model.PojoProperty;
public class Setter extends AbstractPropertyRenderer<PojoProperty, PojoBean> {
public Setter(CodeFormat format) {
super(format);
}
@Override
protected void writePropertyCode(PojoProperty property) {
String type = property.getDeclarationType();
String field = property.getFieldName();
String setter = property.getSetterName();
MethodCodeWriter writer = getMethodCodeWriter();
writer.start("public void %s(%s %s) {", setter, type, field);
writer.code("this.%s = %s;", field, field);
writer.end();
}
}
|
Fix issue with incorrect URL in Google Analytics script.
Better research later! Why does it work with my other sites, but not for this one?
|
<?php ///////////////////////////////////////////////////////
// ----------------------------------------------------------
// SNIPPET
// ----------------------------------------------------------
// Google analytics.js
// ----------------------------------------------------------
// Enable and set analytics ID/API KEY in config.php
// ----------------------------------------------------------
// Respect user's privacy:
// https://blog.j15h.nu/web-analytics-privacy/
// ----------------------------------------------------------
/////////////////////////////////////////////////////////////
// ----------------------------------------------------------
// Google Universal Analytics
// ----------------------------------------------------------
if (c::get('google.analytics') == true && c::get('google.analytics.id') != 'TRACKING ID IS NOT SET'): ?>
<script>
// Respect user's privacy
if ('navigator.doNotTrack' != 'yes' && 'navigator.doNotTrack' != '1' && 'navigator.msDoNotTrack' != '1') {
window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;ga('create','<?php echo c::get("google.analytics.id", "TRACKING ID IS NOT SET"); ?>','<?php $tmp = strstr($site->url(), ':'); echo substr($tmp, 3); //echo str::after($site->url(), '://'); ?>');ga('set', 'anonymizeIp', true);ga('set', 'forceSSL', true);ga('send','pageview');
}
</script>
<script src="https://www.google-analytics.com/analytics.js" async defer></script>
<?php else: ?>
<!-- NO TRACKING SET! -->
<?php endif; ?>
|
<?php ///////////////////////////////////////////////////////
// ----------------------------------------------------------
// SNIPPET
// ----------------------------------------------------------
// Google analytics.js
// ----------------------------------------------------------
// Enable and set analytics ID/API KEY in config.php
// ----------------------------------------------------------
// Respect user's privacy:
// https://blog.j15h.nu/web-analytics-privacy/
// ----------------------------------------------------------
/////////////////////////////////////////////////////////////
// ----------------------------------------------------------
// Google Universal Analytics
// ----------------------------------------------------------
if (c::get('google.analytics') == true && c::get('google.analytics.id') != 'TRACKING ID IS NOT SET'): ?>
<script>
// Respect user's privacy
if ('navigator.doNotTrack' != 'yes' && 'navigator.doNotTrack' != '1' && 'navigator.msDoNotTrack' != '1') {
window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;ga('create','<?php echo c::get("google.analytics.id", "TRACKING ID IS NOT SET"); ?>','<?php echo str::after($site->url(), '://'); ?>');ga('set', 'anonymizeIp', true);ga('set', 'forceSSL', true);ga('send','pageview');
}
</script>
<script src="https://www.google-analytics.com/analytics.js" async defer></script>
<?php else: ?>
<!-- NO TRACKING SET! -->
<?php endif; ?>
|
Fix the XRC package_data entry.
|
#!/usr/bin/env python3
from setuptools import setup, find_packages
from thotkeeper import __version__ as tk_version
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='thotkeeper',
version=tk_version,
author='C. Michael Pilato',
author_email='cmpilato@red-bean.com',
description='Cross-platform personal daily journaling',
long_description=long_description,
long_description_content_type='text/markdown',
keywords='journaling',
url='https://github.com/cmpilato/thotkeeper',
packages=find_packages(),
package_data={
'thotkeeper': ['*.xrc'],
},
data_files=[
('share/pixmaps', ['icons/thotkeeper.xpm']),
('share/icons/hicolor/scalable/apps', ['icons/thotkeeper.svg']),
],
entry_points={
'console_scripts': [
'thotkeeper = thotkeeper:main',
],
},
classifiers=[
'Programming Language :: Python :: 3',
'License :: OSI Approved :: BSD-2 License',
'Operating System :: OS Independent',
],
include_package_data=True,
zip_safe=False,
platforms='any',
python_requires='>=3.4',
)
|
#!/usr/bin/env python3
from setuptools import setup, find_packages
from thotkeeper import __version__ as tk_version
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='thotkeeper',
version=tk_version,
author='C. Michael Pilato',
author_email='cmpilato@red-bean.com',
description='Cross-platform personal daily journaling',
long_description=long_description,
long_description_content_type='text/markdown',
keywords='journaling',
url='https://github.com/cmpilato/thotkeeper',
packages=find_packages(),
package_data={
'thotkeeper': ['thotkeeper/*.xrc'],
},
data_files=[
('share/pixmaps', ['icons/thotkeeper.xpm']),
('share/icons/hicolor/scalable/apps', ['icons/thotkeeper.svg']),
],
entry_points={
'console_scripts': [
'thotkeeper = thotkeeper:main',
],
},
classifiers=[
'Programming Language :: Python :: 3',
'License :: OSI Approved :: BSD-2 License',
'Operating System :: OS Independent',
],
include_package_data=True,
zip_safe=False,
platforms='any',
python_requires='>=3.4',
)
|
Fix error in RaspberryPi environment <numpy type error>.
|
#!/usr/bin/python
from sys import argv
import numpy as np
import cv2
import cv2.cv as cv
def detectCircle(imagePath):
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.Canny(gray, 32, 2)
cv2.imwrite("canny.jpg", gray)
circles = cv2.HoughCircles(gray, cv.CV_HOUGH_GRADIENT, 1, 10, np.array([]), 10, 20, 6, 20)
if circles is not None:
circles = np.uint16(np.around(circles))
gray = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
for i in circles[0,:]:
# draw the outer circle
cv2.circle(gray,(i[0],i[1]),i[2],(0,255,0),2)
# draw the center of the circle
cv2.circle(gray,(i[0],i[1]),2,(0,0,255),3)
cv2.imwrite('circled.jpg', gray)
return len(circles[0])
if __name__ == '__main__':
if len(argv) < 2:
exit(1)
print detectCircle(argv[1])
|
#!/usr/bin/python
from sys import argv
import numpy as np
import cv2
import cv2.cv as cv
def detectCircle(imagePath):
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.Canny(gray, 32, 2)
cv2.imwrite("canny.jpg", gray)
circles = cv2.HoughCircles(gray, cv.CV_HOUGH_GRADIENT, 1, 50, 10, 50, 6, 10)
if circles is not None:
circles = np.uint16(np.around(circles))
gray = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
for i in circles[0,:]:
# draw the outer circle
cv2.circle(gray,(i[0],i[1]),i[2],(0,255,0),2)
# draw the center of the circle
cv2.circle(gray,(i[0],i[1]),2,(0,0,255),3)
cv2.imwrite('circled.jpg', gray)
return len(circles[0])
if __name__ == '__main__':
if len(argv) < 2:
exit(1)
print detectCircle(argv[1])
|
Fix Symfony 4.2 deprecations for TreeBuilder
|
<?php
namespace Burgov\Bundle\KeyValueFormBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('burgov_key_value_form');
if (method_exists($treeBuilder, 'getRootNode')) {
$rootNode = $treeBuilder->getRootNode();
} else {
// BC layer for symfony/config 4.1 and older
$rootNode = $treeBuilder->root('burgov_key_value_form');
}
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
}
}
|
<?php
namespace Burgov\Bundle\KeyValueFormBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('burgov_key_value_form');
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
}
}
|
Add UCLDC-Deep-Harvester as a dependency.
|
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name = "UCLDC Deep Harvester",
version = "0.0.1",
description = ("deep harvester code for the UCLDC project"),
long_description=read('README.md'),
author='Barbara Hui',
author_email='barbara.hui@ucop.edu',
dependency_links=[
'https://github.com/ucldc/pynux/archive/master.zip#egg=pynux',
'https://github.com/barbarahui/nuxeo-calisphere/archive/master.zip#egg=UCLDC-Deep-Harvester'
],
install_requires=[
'boto',
'pynux',
'python-magic',
'UCLDC-Deep-Harvester'
],
packages=['deepharvest'],
test_suite='tests'
)
|
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name = "UCLDC Deep Harvester",
version = "0.0.1",
description = ("deep harvester code for the UCLDC project"),
long_description=read('README.md'),
author='Barbara Hui',
author_email='barbara.hui@ucop.edu',
dependency_links=[
'https://github.com/ucldc/pynux/archive/master.zip#egg=pynux'
],
install_requires=[
'boto',
'pynux',
'python-magic'
],
packages=['deepharvest'],
test_suite='tests'
)
|
Document shortcuts for VLC Remote
|
// ==UserScript==
// @name VLC Remote
// @namespace fatmonkeys
// @include http://[IP address of VLC Remote server]:8080/
// @version 1
// @grant none
// ==/UserScript==
// Enables new keyboard shortcuts:
// Space to pause/resume the current video.
// Ctrl + Right arrow to jump to the next video in the playlist.
// Ctrl + Left arrow to jump to the previous video in the playlist.
document.onkeypress = checkKey;
function eventFire(el, etype){
if (el.fireEvent) {
el.fireEvent('on' + etype);
} else {
var evObj = document.createEvent('Events');
evObj.initEvent(etype, true, false);
el.dispatchEvent(evObj);
}
}
function checkKey(e) {
e = e || window.event;
if (e.charCode == 32) {
eventFire(document.getElementById('buttonPlay'), 'click');
} else if(e.ctrlKey && e.keyCode == 37) {
eventFire(document.getElementById('buttonPrev'), 'mousedown');
eventFire(document.getElementById('buttonPrev'), 'mouseup');
} else if(e.ctrlKey && e.keyCode == 39) {
eventFire(document.getElementById('buttonNext'), 'mousedown');
eventFire(document.getElementById('buttonNext'), 'mouseup');
}
}
|
// ==UserScript==
// @name VLC Remote
// @namespace fatmonkeys
// @include http://[IP address of VLC Remote server]:8080/
// @version 1
// @grant none
// ==/UserScript==
document.onkeypress = checkKey;
function eventFire(el, etype){
if (el.fireEvent) {
el.fireEvent('on' + etype);
} else {
var evObj = document.createEvent('Events');
evObj.initEvent(etype, true, false);
el.dispatchEvent(evObj);
}
}
function checkKey(e) {
e = e || window.event;
if (e.charCode == 32) {
eventFire(document.getElementById('buttonPlay'), 'click');
} else if(e.ctrlKey && e.keyCode == 37) {
eventFire(document.getElementById('buttonPrev'), 'mousedown');
eventFire(document.getElementById('buttonPrev'), 'mouseup');
} else if(e.ctrlKey && e.keyCode == 39) {
eventFire(document.getElementById('buttonNext'), 'mousedown');
eventFire(document.getElementById('buttonNext'), 'mouseup');
}
}
|
Improve prefetch speed in predict listing pages
|
"""
Basic view mixins for predict views
"""
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from .models import PredictDataset
class PredictMixin(object):
"""The baseline predict view"""
slug_field = 'md5'
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
"""Only allow a logged in users to view"""
return super(PredictMixin, self).dispatch(request, *args, **kwargs)
def get_queryset(self):
"""Limit queryset to the user's own predictions only"""
qset = PredictDataset.objects.all()
if 'slug' not in self.kwargs:
# Limit to my own predictions unless I have the md5
qset = qset.filter(user_id=self.request.user.pk)
return qset.prefetch_related('strains', 'strains__piperun', 'strains__piperun__programs')
|
"""
Basic view mixins for predict views
"""
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from .models import PredictDataset
class PredictMixin(object):
"""The baseline predict view"""
slug_field = 'md5'
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
"""Only allow a logged in users to view"""
return super(PredictMixin, self).dispatch(request, *args, **kwargs)
def get_queryset(self):
"""Limit queryset to the user's own predictions only"""
qs = PredictDataset.objects.all()
if 'slug' not in self.kwargs:
# Limit to my own predictions unless I have the md5
qs = qs.filter(user_id=self.request.user.pk)
return qs
|
Make mismatchFilter a factory for API consistency
|
import { isEqual } from 'lodash';
const TAG_COMPARISON = {
TOTAL: Symbol(),
PARTIAL: Symbol(),
MISMATCH: Symbol()
};
function compareTags (a, b) {
/* Returns a TAG_COMPARISON value */
if (isEqual(a, b)) return TAG_COMPARISON.TOTAL;
// If the tags are unequal but have the same length, it stands to reason
// there is a mismatch.
if (a.length === b.length) return TAG_COMPARISON.MISMATCH;
const [shorter, longer] = a < b ? [a, b] : [b, a];
if (shorter.find((x, i) => x !== longer[i])) return TAG_COMPARISON.MISMATCH;
return TAG_COMPARISON.PARTIAL;
}
function mismatchFilterSub (group, model) {
/* Ensures that the group and model don't have any mismatched tags */
const result = group.tags.find(function (groupTag) {
// Look for a mismatch.
const matched = model.tags.find(modelTag => modelTag[0] === groupTag[0]);
if (matched === undefined) return false;
if (compareTags(groupTag, matched) === TAG_COMPARISON.MISMATCH) return true;
return false;
});
if (result === undefined) return 0;
return null;
}
export default {
mismatchFilter () { return mismatchFilterSub; }
};
|
import { isEqual } from 'lodash';
const TAG_COMPARISON = {
TOTAL: Symbol(),
PARTIAL: Symbol(),
MISMATCH: Symbol()
};
function compareTags (a, b) {
/* Returns a TAG_COMPARISON value */
if (isEqual(a, b)) return TAG_COMPARISON.TOTAL;
// If the tags are unequal but have the same length, it stands to reason
// there is a mismatch.
if (a.length === b.length) return TAG_COMPARISON.MISMATCH;
const [shorter, longer] = a < b ? [a, b] : [b, a];
if (shorter.find((x, i) => x !== longer[i])) return TAG_COMPARISON.MISMATCH;
return TAG_COMPARISON.PARTIAL;
}
export default {
mismatchFilter (group, model) {
/* Ensures that the group and model don't have any mismatched tags */
const result = group.tags.find(function (groupTag) {
// Look for a mismatch.
const matched = model.tags.find(modelTag => modelTag[0] === groupTag[0]);
if (matched === undefined) return false;
if (compareTags(groupTag, matched) === TAG_COMPARISON.MISMATCH) return true;
return false;
});
if (result === undefined) return 0;
return null;
}
};
|
Clean up Firebase middleware code.
|
import {
LOAD_MESSAGES,
LOGIN,
LOGOUT,
SAVE_PREFERENCES,
SEND_MESSAGE,
UPDATE_USER
} from '../../actions'
const firebaseMiddleware = firebase => store => next => action => {
const firebaseCommand = action.firebase
const state = store.getState()
// Early return if nothing for Firebase
if (firebaseCommand == undefined) {
return next(action)
}
// Error on Firebase-y actions if there's no logged-in user
if (firebaseCommand !== LOGIN && firebase.auth.currentUser == undefined) {
console.error('User is not signed in')
return
}
switch (firebaseCommand) {
case SAVE_PREFERENCES:
setTimeout(() => firebase.savePreferences(store.getState()), 0)
break
case LOAD_MESSAGES:
firebase.loadMessages()
break
case LOGIN:
firebase.login(action)
break
case LOGOUT:
firebase.logout(state)
break
case SEND_MESSAGE:
firebase.sendMessage(state, action)
break
case UPDATE_USER:
firebase.updateUser(action)
break
default:
break
}
next(action)
}
export default firebaseMiddleware
|
import {
LOAD_MESSAGES,
LOGIN,
LOGOUT,
SAVE_PREFERENCES,
SEND_MESSAGE,
UPDATE_USER
} from '../../actions'
const firebaseMiddleware = firebase => store => next => action => {
const firebaseCommand = action.firebase
const state = store.getState()
if (firebaseCommand) {
if (firebaseCommand !== LOGIN && firebase.auth.currentUser == undefined) {
console.error('User is not signed in')
return
}
switch (firebaseCommand) {
case SAVE_PREFERENCES:
setTimeout(() => firebase.savePreferences(store.getState()), 0)
break
case LOAD_MESSAGES:
firebase.loadMessages()
break
case LOGIN:
firebase.login(action)
break
case LOGOUT:
firebase.logout(state)
break
case SEND_MESSAGE:
firebase.sendMessage(state, action)
break
case UPDATE_USER:
firebase.updateUser(action)
break
default:
break
}
}
next(action)
}
export default firebaseMiddleware
|
Document that retrievers must throw an exception when requested to retrieve unknown dependencies.
|
<?php
namespace BartFeenstra\DependencyRetriever\Retriever;
/**
* Defines a dependency retriever.
*/
interface Retriever
{
/**
* The PCRE pattern that defines a valid dependency retriever name.
*/
const VALID_NAME_PCRE_PATTERN = '/^[a-z0-9-_]*$/';
/**
* Gets the dependency retriever's name.
*
* @return string
* The value MUST match self::VALID_NAME_PCRE_PATTERN.
*/
public function getName();
/**
* Checks whether a dependency can be retrieved.
*
* @param string $id
* The ID of the dependency to retrieve.
*
* @return bool
* Whether the dependency is known.
*/
public function knowsDependency($id);
/**
* Retrieves a dependency.
*
* @param string $id
* The ID of the dependency to retrieve.
*
* @return mixed
* The dependency.
*
* @throws \BartFeenstra\DependencyRetriever\Exception\MissingDependencyException
* Thrown if the requested dependency is unknown.
*/
public function retrieveDependency($id);
}
|
<?php
namespace BartFeenstra\DependencyRetriever\Retriever;
/**
* Defines a dependency retriever.
*/
interface Retriever
{
/**
* The PCRE pattern that defines a valid dependency retriever name.
*/
const VALID_NAME_PCRE_PATTERN = '/^[a-z0-9-_]*$/';
/**
* Gets the dependency retriever's name.
*
* @return string
* The value MUST match self::VALID_NAME_PCRE_PATTERN.
*/
public function getName();
/**
* Checks whether a dependency can be retrieved.
*
* @param string $id
* The ID of the dependency to retrieve.
*
* @return bool
* Whether the dependency is known.
*/
public function knowsDependency($id);
/**
* Retrieves a dependency.
*
* @param string $id
* The ID of the dependency to retrieve.
*
* @return mixed
* The dependency.
*/
public function retrieveDependency($id);
}
|
Use plugin_dir as base for script_path
|
#!/usr/bin/env python
import sys
import os
from bashscriptrunner import BashScriptRunner
name = "chef"
def setup(config={}):
LOG.debug('Doing setup in test.py')
plugin_dir = config.get("plugin_dir", "roushagent/plugins")
script_path = [os.path.join(plugin_dir, "lib", name)]
script = BashScriptRunner(script_path=script_path)
register_action('install_chef', lambda x: install_chef(x, script))
register_action('run_chef', lambda x: run_chef(x, script))
def install_chef(input_data, script):
payload = input_data['payload']
action = input_data['action']
required = ["CHEF_SERVER", "CHEF_VALIDATOR"]
optional = ["CHEF_RUNLIST", "CHEF_ENVIRONMENT", "CHEF_VALIDATION_NAME"]
env = dict([(k, v) for k, v in payload.iteritems()
if k in required + optional])
for r in required:
if not r in env:
return {'result_code': 22,
'result_str': 'Bad Request (missing %s)' % r,
'result_data': None}
return script.run_env("install-chef.sh", env, "")
def run_chef(input_data, script):
payload = input_data['payload']
action = input_data['action']
return script.run("run-chef.sh")
|
#!/usr/bin/env python
import sys
from bashscriptrunner import BashScriptRunner
name = "chef"
script = BashScriptRunner(script_path=["roushagent/plugins/lib/%s" % name])
def setup(config):
LOG.debug('Doing setup in test.py')
register_action('install_chef', install_chef)
register_action('run_chef', run_chef)
def install_chef(input_data):
payload = input_data['payload']
action = input_data['action']
required = ["CHEF_SERVER", "CHEF_VALIDATOR"]
optional = ["CHEF_RUNLIST", "CHEF_ENVIRONMENT", "CHEF_VALIDATION_NAME"]
env = dict([(k, v) for k, v in payload.iteritems()
if k in required + optional])
for r in required:
if not r in env:
return {'result_code': 22,
'result_str': 'Bad Request (missing %s)' % r,
'result_data': None}
return script.run_env("install-chef.sh", env, "")
def run_chef(input_data):
payload = input_data['payload']
action = input_data['action']
return script.run("run-chef.sh")
|
Fix bug with hash-ref url
|
<?
include_once("include/passwd.php");
pg_connect($pgconnstr);
Header("Content-Type: text/html; charset=utf-8");
if (!isset($_GET["title"])) {
print "Обязательный параметр title не определён!";
exit;
}
$title = $_GET["title"];
if (isset($_GET["js"]) && $_GET["js"]) $title = urldecode($title);
$title = preg_replace("@^http://commons\.wikimedia\.org/wiki/@", "", $title);
$title = preg_replace("@\?.+$@", "", $title);
$title = preg_replace("@#.+$@", "", $title);
if (!preg_match("@^File:@", $title)) {
print "Страница <b>$title</b> не является страницей описания картинки";
exit;
}
$query = "INSERT INTO wpc_req (page, added) VALUES ('".pg_escape_string($title)."', NOW())";
$res = pg_query($query);
print "Страница <b>$title</b> добавлена в <a href=\"wpc-queue.php\">очередь</a> на обновление";
?>
|
<?
include_once("include/passwd.php");
pg_connect($pgconnstr);
Header("Content-Type: text/html; charset=utf-8");
if (!isset($_GET["title"])) {
print "Обязательный параметр title не определён!";
exit;
}
$title = $_GET["title"];
if (isset($_GET["js"]) && $_GET["js"]) $title = urldecode($title);
$title = preg_replace("@^http://commons\.wikimedia\.org/wiki/@", "", $title);
$title = preg_replace("@\?.+$@", "", $title);
if (!preg_match("@^File:@", $title)) {
print "Страница <b>$title</b> не является страницей описания картинки";
exit;
}
$query = "INSERT INTO wpc_req (page, added) VALUES ('".pg_escape_string($title)."', NOW())";
$res = pg_query($query);
print "Страница <b>$title</b> добавлена в <a href=\"wpc-queue.php\">очередь</a> на обновление";
?>
|
Make BasicGP kernel strings lowercase.
|
"""
Simple wrapper class for a Basic GP.
"""
# future imports
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
# global imports
import numpy as np
# local imports
from .exact import ExactGP
from ..likelihoods import Gaussian
from ..kernels import SE, Matern
from ..utils.models import Printable
# exported symbols
__all__ = ['BasicGP']
# NOTE: in the definition of the BasicGP class Printable has to come first so
# that we use the __repr__ method defined there and override the base method.
class BasicGP(Printable, ExactGP):
def __init__(self, sn, sf, ell, ndim=None, kernel='se'):
likelihood = Gaussian(sn)
kernel = (
SE(sf, ell, ndim) if (kernel == 'se') else
Matern(sf, ell, 1, ndim) if (kernel == 'matern1') else
Matern(sf, ell, 3, ndim) if (kernel == 'matern3') else
Matern(sf, ell, 5, ndim) if (kernel == 'matern5') else None)
if kernel is None:
raise RuntimeError('Unknown kernel type')
super(BasicGP, self).__init__(likelihood, kernel)
def _params(self):
# replace the parameters for the base GP model with a simplified
# structure and rename the likelihood's sigma parameter to sn (ie its
# the sigma corresponding to the noise).
return [('sn', 1)] + self._kernel._params()
|
"""
Simple wrapper class for a Basic GP.
"""
# future imports
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
# global imports
import numpy as np
# local imports
from .exact import ExactGP
from ..likelihoods import Gaussian
from ..kernels import SE, Matern
from ..utils.models import Printable
# exported symbols
__all__ = ['BasicGP']
# NOTE: in the definition of the BasicGP class Printable has to come first so
# that we use the __repr__ method defined there and override the base method.
class BasicGP(Printable, ExactGP):
def __init__(self, sn, sf, ell, ndim=None, kernel='SE'):
likelihood = Gaussian(sn)
kernel = (
SE(sf, ell, ndim) if (kernel == 'SE') else
Matern(sf, ell, 1, ndim) if (kernel == 'Matern1') else
Matern(sf, ell, 3, ndim) if (kernel == 'Matern3') else
Matern(sf, ell, 5, ndim) if (kernel == 'Matern5') else None)
if kernel is None:
raise RuntimeError('Unknown kernel type')
super(BasicGP, self).__init__(likelihood, kernel)
def _params(self):
# replace the parameters for the base GP model with a simplified
# structure and rename the likelihood's sigma parameter to sn (ie its
# the sigma corresponding to the noise).
return [('sn', 1)] + self._kernel._params()
|
Add route for molecule mf
|
'use strict';
const api = require('api');
const router = require('koa-router')();
router.get('/search/em', function*() {
const value = +this.query.value;
if (!value) {
return error(this, 'missing value');
}
const options = {};
if (this.query.limit) options.limit = +this.query.limit;
if (this.query.precision) options.precision = +this.query.precision;
this.body = {
result: yield api.search.em(value, options)
};
});
router.get('/molecules/em', function*() {
const value = +this.query.value;
if (!value) {
return error(this, 'missing value');
}
this.body = {
result: yield api.molecules.em(value)
};
});
router.get('/molecules/mf', function*() {
const value = this.query.value;
if (!value) {
return error(this, 'missing value');
}
this.body = {
result: yield api.molecules.mf(value)
};
});
function error(ctx, message) {
ctx.status = 400;
ctx.body = {
error: message
};
}
module.exports = router;
|
'use strict';
const api = require('api');
const router = require('koa-router')();
router.get('/search/em', function*() {
const value = +this.query.value;
if (!value) {
return error(this, 'missing value');
}
const options = {};
if (this.query.limit) options.limit = +this.query.limit;
if (this.query.precision) options.precision = +this.query.precision;
this.body = {
result: yield api.search.em(value, options)
};
});
router.get('/molecules/em', function*() {
const value = +this.query.value;
if (!value) {
return error(this, 'missing value');
}
this.body = {
result: yield api.molecules.em(value)
};
});
router.get('/molecules/mf', function*() {
const value = +this.query.value;
if (!value) {
return error(this, 'missing value');
}
this.body = {
result: yield api.molecules.mf(value)
};
});
function error(ctx, message) {
ctx.status = 400;
ctx.body = {
error: message
};
}
module.exports = router;
|
Remove name conflict module => moduleConfig
|
const nodeExternals = require('webpack-node-externals');
const path = require('path');
const entry = './src/ReactResponsiveSelect.js';
const library = 'ReactResponsiveSelect';
const moduleConfig = {
rules: [{
test: /\.js$/,
loader: 'babel-loader',
exclude: path.resolve(__dirname, 'node_modules')
}]
};
module.exports = [{
entry,
module: moduleConfig,
output: {
filename: './dist/ReactResponsiveSelect.js',
libraryTarget: 'umd',
library
},
externals: [ nodeExternals({ whitelist: ['prop-types'] }) ]
}, {
entry,
module: moduleConfig,
output: {
filename: './dist/ReactResponsiveSelect.window.js',
libraryTarget: 'window',
library
},
externals: { react: 'React' }
}, {
entry,
module: moduleConfig,
output: {
filename: './dist/ReactResponsiveSelect.var.js',
libraryTarget: 'var',
library
},
externals: { react: 'React' }
}];
|
const nodeExternals = require('webpack-node-externals');
const path = require('path');
const entry = './src/ReactResponsiveSelect.js';
const library = 'ReactResponsiveSelect';
const module = {
rules: [{
test: /\.js$/,
loader: 'babel-loader',
exclude: path.resolve(__dirname, 'node_modules')
}]
};
module.exports = [{
entry,
module,
output: {
filename: './dist/ReactResponsiveSelect.js',
libraryTarget: 'umd',
library
},
externals: [ nodeExternals({ whitelist: ['prop-types'] }) ]
}, {
entry,
module,
output: {
filename: './dist/ReactResponsiveSelect.window.js',
libraryTarget: 'window',
library
},
externals: { react: 'React' }
}, {
entry,
module,
output: {
filename: './dist/ReactResponsiveSelect.var.js',
libraryTarget: 'var',
library
},
externals: { react: 'React' }
}];
|
Change text for hover over rate your pup
|
/**
* Created by mcgourtyalex on 4/14/15.
*/
var MainButtons = {
// setup sets a callback for #breeder_find keyup
setup: function() {
$('.button-a').hover( function() {
$('#tagline-text').html("Contribute information about <strong>your<strong> dog to our database");
});
$('.button-b').click( function() {
$('.box-b').toggleClass("hidden");
}).hover( function() {
$('#tagline-text').html("Find the <strong>right</strong> breed for you");
});
$('#cancel-b').click( function() {
$('.box-b').toggleClass("hidden");
});
$('.button-c').click( function() {
$('.box-c').toggleClass("hidden");
}).hover( function() {
$('#tagline-text').html("Find a dog breeder with <strong>great</strong> reviews");
});
$('#cancel-c').click( function() {
$('.box-c').toggleClass("hidden");
});
}
};
$(document).ready(function () {
$(MainButtons.setup);
});
|
/**
* Created by mcgourtyalex on 4/14/15.
*/
var MainButtons = {
// setup sets a callback for #breeder_find keyup
setup: function() {
$('.button-a').hover( function() {
$('#tagline-text').html("Keep breeders <strong>honest</strong> by rating your pup");
});
$('.button-b').click( function() {
$('.box-b').toggleClass("hidden");
}).hover( function() {
$('#tagline-text').html("Find the <strong>right</strong> breed for you");
});
$('#cancel-b').click( function() {
$('.box-b').toggleClass("hidden");
});
$('.button-c').click( function() {
$('.box-c').toggleClass("hidden");
}).hover( function() {
$('#tagline-text').html("Find a dog breeder with <strong>great</strong> reviews");
});
$('#cancel-c').click( function() {
$('.box-c').toggleClass("hidden");
});
}
};
$(document).ready(function () {
$(MainButtons.setup);
});
|
[js] Fix typo and optimize DOM querying
|
(function() {
"use strict";
// animate moving between anchor hash links
smoothScroll.init({
selector: "a",
speed: 500,
easing: "easeInOutCubic"
});
// better external SVG spritesheet support
svg4everybody();
// random placeholders for the contact form fields
var names = [
"Paul Bunyan",
"Luke Skywalker",
"Jason Bourne",
"James Bond"
],
messages = [
"Like what you see? Let me know!",
"Want to know more? Get in touch!",
"Hey! Did I tickle your fancy?"
];
document.getElementById("name").placeholder = randomFromArray(names);
document.getElementById("message").placeholder = randomFromArray(messages);
function randomFromArray(array) {
return array[Math.floor(Math.random() * array.length)];
}
})();
|
(function() {
"use strict";
// animate moving between anchor links
smoothScroll.init({
selector: "a",
speed: 500,
easing: "easeInOutCubic"
});
// better external SVG spiresheet support
svg4everybody();
// random placeholders for the contact form fields
var form = document.querySelector(".contact"),
names = [
"Paul Bunyan",
"Luke Skywalker",
"Jason Bourne",
"James Bond"
],
messages = [
"Like what you see? Let me know!",
"Want to know more? Get in touch!",
"Hey! Did I tickle your fancy?"
];
form.querySelector("[id='name']").placeholder = randomFromArray(names);
form.querySelector("[id='message']").placeholder = randomFromArray(messages);
function randomFromArray(array) {
return array[Math.floor(Math.random() * array.length)];
}
})();
|
Fix bug where all data points are same height
|
# -*- coding: utf-8 -*-
from __future__ import division
import argparse
ticks = ('▁', '▂', '▃', '▄', '▅', '▆', '▇', '█')
def scale_data(data):
m = min(data)
n = (max(data) - m) / (len(ticks) - 1)
# if every element is the same height return all lower ticks, else compute
# the tick height
if n == 0:
return [ ticks[0] for t in data]
else:
return [ ticks[int((t - m) / n)] for t in data ]
def print_ansi_spark(d):
print ''.join(d)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
args = parser.parse_args()
print_ansi_spark(scale_data(args.integers))
|
# -*- coding: utf-8 -*-
from __future__ import division
import argparse
ticks = ('▁', '▂', '▃', '▄', '▅', '▆', '▇', '█')
def scale_data(data):
m = min(data)
n = (max(data) - m) / (len(ticks) - 1)
return [ ticks[int((t - m) / n)] for t in data ]
def print_ansi_spark(d):
print ''.join(d)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
args = parser.parse_args()
print_ansi_spark(scale_data(args.integers))
|
Switch developement to production check
|
/* jshint node: true */
'use strict';
module.exports = {
name: 'ember-cli-hot-loader',
serverMiddleware: function (config){
// If in production, don't add reloader
if (config.options.environment === 'production') {
return;
}
var lsReloader = require('./lib/hot-reloader')(config.options);
lsReloader.run();
},
included: function (app) {
this._super.included(app);
// If in production, don't add ember-template-compiler
if (app.env === 'production') {
return;
}
var bowerPath = app.bowerDirectory + '/ember/ember-template-compiler.js';
var npmPath = app.project.nodeModulesPath + '/ember-source/dist/ember-template-compiler.js';
// Require template compiler as in CLI this is only used in build, we need it at runtime
if (fs.existsSync(bowerPath)) {
app.import(bowerPath);
} else if (fs.existsSync(npmPath)) {
app.import(npmPath);
} else {
throw new Error('Unable to locate ember-template-compiler.js. ember/ember-source not found in either bower_components or node_modules');
}
}
};
|
/* jshint node: true */
'use strict';
module.exports = {
name: 'ember-cli-hot-loader',
serverMiddleware: function (config){
if (config.options.environment === 'development') {
var lsReloader = require('./lib/hot-reloader')(config.options);
lsReloader.run();
}
},
included: function (app) {
this._super.included(app);
// If not in dev, bail
if (app.env !== 'development') {
return;
}
var bowerPath = app.bowerDirectory + '/ember/ember-template-compiler.js';
var npmPath = app.project.nodeModulesPath + '/ember-source/dist/ember-template-compiler.js';
// Require template compiler as in CLI this is only used in build, we need it at runtime
if (fs.existsSync(bowerPath)) {
app.import(bowerPath);
} else if (fs.existsSync(npmPath)) {
app.import(npmPath);
} else {
throw new Error('Unable to locate ember-template-compiler.js. ember/ember-source not found in either bower_components or node_modules');
}
}
};
|
Use promise for api request, taskrunner
|
const low = require("lowdb");
const userDb = low('./data/userdb.json');
const dataDb = low('./data/datadb.json');
const Requester = require('../controllers/requester');
const Parser = require('../controllers/parser');
const TIME_SECOND = 1000;
const TIME_MIN = 60 * TIME_SECOND;
const TIME_HOUR = 60 * TIME_MIN;
var updateLoop = function updateLoop(functionToRun) {
functionToRun();
setTimeout(updateLoop, 5 * TIME_MIN, functionToRun);
}
var TaskRunner = {
init: function() {
updateModuleIds();
// Initialise app
// obtains ids
// announcements, forum, webcast, files
},
run: function() {
updateLoop(Parser.getAnnouncements);
}
};
var updateModuleIds = function updateModuleIds() {
// Obtain data from IVLE
Requester.requestJson("Modules", {
"Duration": "0",
"IncludeAllInfo": "false"
}).then(
function(data) {
let modulesObj = filterModuleIds(data);
storeModuleIds(modulesObj);
},
function(error) {
console.error(error);
}
);
function filterModuleIds(data) {
let modulesArray = data["Results"];
let modulesObj = {};
modulesArray.forEach(function(moduleObj, index, array) {
let moduleId = moduleObj["ID"];
modulesObj[moduleId] = {};
});
return modulesObj;
}
function storeModuleIds(modulesObj) {
userDb.set("modules", modulesObj);
}
}
module.exports = TaskRunner;
|
const low = require("lowdb");
const dataDb = low('./data/datadb.json');
const Requester = require('../controllers/requester');
const Parser = require('../controllers/parser');
const TIME_SECOND = 1000;
const TIME_MIN = 60 * TIME_SECOND;
const TIME_HOUR = 60 * TIME_MIN;
var initialiseDataSet = function initialiseDataSet() {
// Initialise app
// obtains ids
// announcements, forum, webcast, files
}
var retrieveDataSet = function retrieveDataSet() {
updateLoop(function() {
console.log("fetching data");
Parser.getAnnouncements();
});
}
var updateLoop = function updateLoop(functionToRun) {
functionToRun();
setTimeout(requestLoop, 5 * TIME_MIN);
}
var TaskRunner = {
init: function() {
initialiseDataSet();
},
run: function() {
retrieveDataSet();
}
};
module.exports = TaskRunner;
|
Remove \Throwable support deprecation layer
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\DataCollector;
use Symfony\Bundle\FrameworkBundle\Controller\RedirectController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\DataCollector\RouterDataCollector as BaseRouterDataCollector;
/**
* RouterDataCollector.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @final
*/
class RouterDataCollector extends BaseRouterDataCollector
{
public function guessRoute(Request $request, $controller)
{
if (\is_array($controller)) {
$controller = $controller[0];
}
if ($controller instanceof RedirectController) {
return $request->attributes->get('_route');
}
return parent::guessRoute($request, $controller);
}
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\DataCollector;
use Symfony\Bundle\FrameworkBundle\Controller\RedirectController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\DataCollector\RouterDataCollector as BaseRouterDataCollector;
/**
* RouterDataCollector.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @final since Symfony 4.4
*/
class RouterDataCollector extends BaseRouterDataCollector
{
public function guessRoute(Request $request, $controller)
{
if (\is_array($controller)) {
$controller = $controller[0];
}
if ($controller instanceof RedirectController) {
return $request->attributes->get('_route');
}
return parent::guessRoute($request, $controller);
}
}
|
Add offerings to the courses when fetching
|
var _ = require('lodash')
var Promise = require("bluebird")
var time = require('../helpers/time')
window.courseCache = {}
function getCourse(clbid) {
return new Promise(function(resolve, reject) {
if (_.contains(courseCache, clbid)) {
console.log('course cached:', clbid)
resolve(window.courseCache[clbid])
} else {
window.server.courses.get(clbid)
.then(function(course) {
if (course) {
course = time.convertTimeStringsToOfferings(course)
console.log('course retrieved:', course)
window.courseCache[clbid] = course
resolve(course)
} else {
console.error('course retrieval failed for: ' + clbid)
reject(new Error('course retrieval failed for: ' + clbid))
}
})
}
})
}
function getCourses(clbids) {
// Takes a list of clbids, and returns a list of the course objects for
// those clbids.
console.log('called getCourses with', clbids)
return Promise.all(_.map(clbids, getCourse))
}
module.exports.getCourses = getCourses
module.exports.getCourse = getCourse
|
var _ = require('lodash')
var Promise = require("bluebird")
window.courseCache = {}
function getCourse(clbid) {
return new Promise(function(resolve, reject) {
if (_.contains(courseCache, clbid)) {
console.log('course cached:', clbid)
resolve(window.courseCache[clbid])
} else {
window.server.courses.get(clbid)
.then(function(course) {
if (course) {
console.log('course retrieved:', course)
window.courseCache[clbid] = course
resolve(course)
} else {
console.error('course retrieval failed for: ' + clbid)
reject(new Error('course retrieval failed for: ' + clbid))
}
})
}
})
}
function getCourses(clbids) {
// Takes a list of clbids, and returns a list of the course objects for
// those clbids.
console.log('called getCourses with', clbids)
return Promise.all(_.map(clbids, getCourse))
}
module.exports.getCourses = getCourses
module.exports.getCourse = getCourse
|
Change in API RequestBody/ ObjectFactory signature to allow different prototype objects based on http request (content-type)
|
package api
import (
"net/http"
)
type AuthScope int
type AuthScopes map[AuthScope]string
type ServiceMethod int
type EventKey string
type ObjectFactory func(*http.Request) interface{}
type HttpMethod string
type QueryDefault interface{}
type UrlQueries map[string]QueryDefault
type HttpHeaders map[string]string
var (
GET HttpMethod = HttpMethod("GET")
POST HttpMethod = HttpMethod("POST")
PUT HttpMethod = HttpMethod("PUT")
DELETE HttpMethod = HttpMethod("DELETE")
MULTIPART HttpMethod = HttpMethod("POST")
)
type MethodSpec struct {
Doc string
UrlRoute string
HttpHeaders HttpHeaders
HttpMethod HttpMethod
UrlQueries UrlQueries
ContentTypes []string
RequestBody ObjectFactory
ResponseBody ObjectFactory
CallbackEvent EventKey
CallbackBodyTemplate string
AuthScope string
}
type ServiceMethods map[ServiceMethod]MethodSpec
|
package api
type AuthScope int
type AuthScopes map[AuthScope]string
type ServiceMethod int
type EventKey string
type ObjectFactory func() interface{}
type HttpMethod string
type QueryDefault interface{}
type UrlQueries map[string]QueryDefault
type HttpHeaders map[string]string
var (
GET HttpMethod = HttpMethod("GET")
POST HttpMethod = HttpMethod("POST")
PUT HttpMethod = HttpMethod("PUT")
DELETE HttpMethod = HttpMethod("DELETE")
MULTIPART HttpMethod = HttpMethod("POST")
)
type MethodSpec struct {
Doc string
UrlRoute string
HttpHeaders HttpHeaders
HttpMethod HttpMethod
UrlQueries UrlQueries
ContentTypes []string
RequestBody ObjectFactory
ResponseBody ObjectFactory
CallbackEvent EventKey
CallbackBodyTemplate string
AuthScope string
}
type ServiceMethods map[ServiceMethod]MethodSpec
|
Clean up and document Contractor class
|
/**
* @fileOverview Class representing all relevant information about the contractor being onboarded
*/
let crypto = require('crypto');
module.exports =
class Contractor {
constructor(firstName, lastName, isResident, privateEmail, override) {
this.firstName = firstName;
this.lastName = lastName;
this.isResident = isResident;
this.privateEmail = privateEmail;
this.override = override;
}
getFullName() {
return this.firstName + ' ' + this.lastName;
}
/**
* If a local-part override was provided, uses that otherwise generates a sanitized local-part
* @returns {string} The complete generated e-mail address
*/
getEmail() {
if (this.override) {
return this.override.replace(" ", "") + '@7hci.com';
} else {
let pattern = /[^a-zA-Z]/g;
let sanitizedFirst = this.firstName.replace(pattern, '').toLowerCase();
let sanitizedLast = this.lastName.replace(pattern, '').toLowerCase();
return sanitizedFirst + '.' + sanitizedLast + '@7hci.com';
}
}
/**
* @returns {string} A password for the contractor's new e-mail account
*/
getPassword() {
return crypto.createHash('md5').update(this.getFullName()).digest('hex');
}
};
|
var crypto = require('crypto');
module.exports =
class Contractor {
constructor(firstName, lastName, isResident, privateEmail, override) {
this.firstName = firstName;
this.lastName = lastName;
this.isResident = isResident;
this.privateEmail = privateEmail;
this.override = override;
}
getFullName() {
return this.firstName + ' ' + this.lastName;
}
getEmail() {
if (this.override) {
return this.override.replace(" ", "") + '@7hci.com';
} else {
var pattern = /[^a-zA-Z]/g;
var sanitizedFirst = this.firstName.replace(pattern, '').toLowerCase();
var sanitizedLast = this.lastName.replace(pattern, '').toLowerCase();
return sanitizedFirst + '.' + sanitizedLast + '@7hci.com';
}
}
getPassword() {
return crypto.createHash('md5').update(this.getFullName()).digest('hex');
}
};
|
Add commented-out permission guards. Part of UIU-197.
|
import _ from 'lodash';
import React from 'react';
import Settings from '@folio/stripes-components/lib/Settings';
import PermissionSets from './permissions/PermissionSets';
import PatronGroupsSettings from './PatronGroupsSettings';
import AddressTypesSettings from './AddressTypesSettings';
const pages = [
{
route: 'perms',
label: 'Permission sets',
component: PermissionSets,
perm: 'ui-users.editpermsets',
},
{
route: 'groups',
label: 'Patron groups',
component: PatronGroupsSettings,
// perm: 'settings.usergroups.all',
},
{
route: 'addresstypes',
label: 'Address Types',
component: AddressTypesSettings,
// perm: 'settings.addresstypes.all',
},
];
export default props => <Settings {...props} pages={_.sortBy(pages, ['label'])} paneTitle="Users" />;
|
import _ from 'lodash';
import React from 'react';
import Settings from '@folio/stripes-components/lib/Settings';
import PermissionSets from './permissions/PermissionSets';
import PatronGroupsSettings from './PatronGroupsSettings';
import AddressTypesSettings from './AddressTypesSettings';
const pages = [
{
route: 'perms',
label: 'Permission sets',
component: PermissionSets,
perm: 'ui-users.editpermsets',
},
{
route: 'groups',
label: 'Patron groups',
component: PatronGroupsSettings,
// No perm needed yet
},
{
route: 'addresstypes',
label: 'Address Types',
component: AddressTypesSettings,
// No perm needed yet
},
];
export default props => <Settings {...props} pages={_.sortBy(pages, ['label'])} paneTitle="Users" />;
|
Fix flask version after vulnerability
No ambiguity left to ensure version is above vulnerable one
|
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='Flask-RESTful',
version='0.2.5',
url='https://www.github.com/twilio/flask-restful/',
author='Kyle Conroy',
author_email='help@twilio.com',
description='Simple framework for creating REST APIs',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
platforms='any',
test_suite = 'nose.collector',
#setup_requires=[
# 'nose==1.3.1',
# 'mock==1.0.1',
# 'six==1.5.2',
# 'blinker==1.3',
#],
install_requires=[
'Flask==0.12.3',
],
# Install these with "pip install -e '.[paging]'" or '.[docs]'
extras_require={
'paging': 'pycrypto>=2.6',
'docs': 'sphinx',
}
)
|
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='Flask-RESTful',
version='0.2.5',
url='https://www.github.com/twilio/flask-restful/',
author='Kyle Conroy',
author_email='help@twilio.com',
description='Simple framework for creating REST APIs',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
platforms='any',
test_suite = 'nose.collector',
#setup_requires=[
# 'nose==1.3.1',
# 'mock==1.0.1',
# 'six==1.5.2',
# 'blinker==1.3',
#],
install_requires=[
'Flask>=0.10.1',
],
# Install these with "pip install -e '.[paging]'" or '.[docs]'
extras_require={
'paging': 'pycrypto>=2.6',
'docs': 'sphinx',
}
)
|
Fix test for empty summation.
|
package org.clafer.ir;
import org.clafer.ir.IrQuickTest.Solution;
import static org.clafer.ir.Irs.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chocosolver.solver.constraints.Constraint;
import org.chocosolver.solver.constraints.ICF;
import org.chocosolver.solver.variables.IntVar;
/**
*
* @author jimmy
*/
@RunWith(IrQuickTest.class)
public class IrAddTest {
@Test(timeout = 60000)
public IrBoolExpr setup(IrIntVar[] is, IrIntVar sum) {
return equal(add(is), sum);
}
@Solution
public Constraint setup(IntVar[] is, IntVar sum) {
return is.length > 0 ? ICF.sum(is, sum) : ICF.arithm(sum, "=", 0);
}
}
|
package org.clafer.ir;
import org.clafer.ir.IrQuickTest.Solution;
import static org.clafer.ir.Irs.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chocosolver.solver.constraints.Constraint;
import org.chocosolver.solver.constraints.ICF;
import org.chocosolver.solver.variables.IntVar;
/**
*
* @author jimmy
*/
@RunWith(IrQuickTest.class)
public class IrAddTest {
@Test(timeout = 60000)
public IrBoolExpr setup(IrIntVar[] is, IrIntVar sum) {
return equal(add(is), sum);
}
@Solution
public Constraint setup(IntVar[] is, IntVar sum) {
return ICF.sum(is, sum);
}
}
|
Replace deprecated API usage with non-deprecated for junit.Assert.
|
package org.wildfly.swarm.container.runtime;
import java.net.URL;
import java.util.List;
import org.junit.Assert;
import org.jboss.dmr.ModelNode;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* @author Heiko Braun
* @since 26/11/15
*/
public class ParserTestCase {
private static URL xml;
@BeforeClass
public static void init() {
ClassLoader cl = ParserTestCase.class.getClassLoader();
xml = cl.getResource("standalone.xml");
}
@Test
public void testDelegatingParser() throws Exception {
StandaloneXmlParser parser = new StandaloneXmlParser();
List<ModelNode> operations = parser.parse(xml);
Assert.assertEquals(28, operations.size());
}
}
|
package org.wildfly.swarm.container.runtime;
import java.net.URL;
import java.util.List;
import junit.framework.Assert;
import org.jboss.dmr.ModelNode;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* @author Heiko Braun
* @since 26/11/15
*/
public class ParserTestCase {
private static URL xml;
@BeforeClass
public static void init() {
ClassLoader cl = ParserTestCase.class.getClassLoader();
xml = cl.getResource("standalone.xml");
}
@Test
public void testDelegatingParser() throws Exception {
StandaloneXmlParser parser = new StandaloneXmlParser();
List<ModelNode> operations = parser.parse(xml);
Assert.assertEquals(28, operations.size());
}
}
|
Add backwards compatibility for Node 0.x series
|
/**
* Terminal client for the Ma3Route REST API
*/
"use strict";
// npm-installed modules
var decamelize = require("decamelize");
var parser = require("simple-argparse");
// own modules
var lib = require("../lib");
var pkg = require("../package.json");
parser
.version(pkg.version)
.description("ma3route", "terminal client for the Ma3Route REST API v2")
.epilog("See https://github.com/GochoMugo/ma3route-cli for source code and license")
.option("c", "config", "run configuration setup", lib.config.run)
.prerun(function() {
if (this.debug) {
process.env.DEBUG = process.env.DEBUG || 1;
delete this.debug;
}
});
// add options
for (var name in lib.options) {
var option = lib.options[name];
parser.option(option.descriptor.short, decamelize(name, "-"), option.description, option.run);
}
parser.parse();
|
/**
* Terminal client for the Ma3Route REST API
*/
"use strict";
// npm-installed modules
var decamelize = require("decamelize");
var parser = require("simple-argparse");
// own modules
var lib = require(".");
var pkg = require("../package.json");
parser
.version(pkg.version)
.description("ma3route", "terminal client for the Ma3Route REST API v2")
.epilog("See https://github.com/GochoMugo/ma3route-cli for source code and license")
.option("c", "config", "run configuration setup", lib.config.run)
.prerun(function() {
if (this.debug) {
process.env.DEBUG = process.env.DEBUG || 1;
delete this.debug;
}
});
// add options
for (var name in lib.options) {
var option = lib.options[name];
parser.option(option.descriptor.short, decamelize(name, "-"), option.description, option.run);
}
parser.parse();
|
Make event sorting stable and deterministic
|
import moment from 'moment-timezone';
import { Frontpage } from 'app/actions/ActionTypes';
import { fetching } from 'app/utils/createEntityReducer';
import { sortBy } from 'lodash';
import { createSelector } from 'reselect';
import { selectArticles } from './articles';
import { selectEvents } from './events';
export default fetching(Frontpage.FETCH);
export const selectFrontpage = createSelector(
selectArticles,
selectEvents,
(articles, events) => {
articles = articles.map(article => ({
...article,
documentType: 'article'
}));
events = events.map(event => ({ ...event, documentType: 'event' }));
const now = moment();
return sortBy(articles.concat(events), [
// Always sort pinned items first:
item => !item.pinned,
item => {
// For events we care about when the event starts, whereas for articles
// we look at when it was written:
const timeField = item.eventType ? item.startTime : item.createdAt;
return Math.abs(now.diff(timeField));
},
item => item.id
]);
}
);
|
import moment from 'moment-timezone';
import { Frontpage } from 'app/actions/ActionTypes';
import { fetching } from 'app/utils/createEntityReducer';
import { sortBy } from 'lodash';
import { createSelector } from 'reselect';
import { selectArticles } from './articles';
import { selectEvents } from './events';
export default fetching(Frontpage.FETCH);
export const selectFrontpage = createSelector(
selectArticles,
selectEvents,
(articles, events) => {
articles = articles.map(article => ({
...article,
documentType: 'article'
}));
events = events.map(event => ({ ...event, documentType: 'event' }));
return sortBy(articles.concat(events), [
// Always sort pinned items first:
item => !item.pinned,
item => {
// For events we care about when the event starts, whereas for articles
// we look at when it was written:
const timeField = item.eventType ? item.startTime : item.createdAt;
return Math.abs(moment().diff(timeField));
},
item => item.id
]);
}
);
|
Enable SSL in (staging) config file.
|
<?php
/* -----------------------------------------------------------------------------
Direct access protection
--------------------------------------------------------------------------------
*/
if(!defined('KIRBY')) die('Direct access is not allowed');
/* -----------------------------------------------------------------------------
Environment
--------------------------------------------------------------------------------
Add server-specific settings to this file that are needed for the environment
this Kirby instance is running on (e.g. local, staging or production).
*/
c::set('environment', 'stage');
/* -----------------------------------------------------------------------------
Troubleshooting
--------------------------------------------------------------------------------
*/
c::set('troubleshoot', false);
/* -----------------------------------------------------------------------------
Debug
--------------------------------------------------------------------------------
*/
c::set('debug', true);
c::set('whoops', true);
/* -----------------------------------------------------------------------------
URL
--------------------------------------------------------------------------------
*/
c::set('url', 'https://altair.artlantis.nl');
c::set('ssl', true);
/* -----------------------------------------------------------------------------
Timezone
--------------------------------------------------------------------------------
*/
c::set('timezone', 'UTC');
/* -----------------------------------------------------------------------------
Home folder
--------------------------------------------------------------------------------
*/
c::set('home', 'home');
/* -----------------------------------------------------------------------------
Cache
--------------------------------------------------------------------------------
*/
c::set('cache', false);
c::set('cache.driver', 'file');
// c::set('cache.options', array('prefix' => 'altair_'));
/* -----------------------------------------------------------------------------
Analytics, tracking, site stats
--------------------------------------------------------------------------------
*/
c::set('google.analytics', false);
|
<?php
/* -----------------------------------------------------------------------------
Direct access protection
--------------------------------------------------------------------------------
*/
if(!defined('KIRBY')) die('Direct access is not allowed');
/* -----------------------------------------------------------------------------
Environment
--------------------------------------------------------------------------------
Add server-specific settings to this file that are needed for the environment
this Kirby instance is running on (e.g. local, staging or production).
*/
c::set('environment', 'stage');
/* -----------------------------------------------------------------------------
Troubleshooting
--------------------------------------------------------------------------------
*/
c::set('troubleshoot', false);
/* -----------------------------------------------------------------------------
Debug
--------------------------------------------------------------------------------
*/
c::set('debug', true);
c::set('whoops', true);
/* -----------------------------------------------------------------------------
URL
--------------------------------------------------------------------------------
*/
c::set('url', false);
c::set('ssl', false);
/* -----------------------------------------------------------------------------
Timezone
--------------------------------------------------------------------------------
*/
c::set('timezone', 'UTC');
/* -----------------------------------------------------------------------------
Home folder
--------------------------------------------------------------------------------
*/
c::set('home', 'home');
/* -----------------------------------------------------------------------------
Cache
--------------------------------------------------------------------------------
*/
c::set('cache', false);
c::set('cache.driver', 'file');
// c::set('cache.options', array('prefix' => 'altair_'));
/* -----------------------------------------------------------------------------
Analytics, tracking, site stats
--------------------------------------------------------------------------------
*/
c::set('google.analytics', false);
|
Bump the api version to 1.2
Big change with the removal of topics, lets increment the API version
we expect accordingly.
|
/* eslint-env node */
module.exports = function(deployTarget) {
var ENV = {
build: {},
exclude: ['.DS_Store', '*-test.js']
};
ENV.s3 = {
acl: 'public-read',
region: 'us-west-2',
bucket: 'ilios-frontend-assets'
};
ENV['s3-index'] = {
region: 'us-west-2',
filePattern: 'index.json',
bucket: 'frontend-json-config',
};
ENV.gzip = {
//dont gzip JSON files
filePattern: '**/*.{js,css,ico,map,xml,txt,svg,eot,ttf,woff,woff2}'
};
if (deployTarget === 'staging') {
ENV.build.environment = 'production';
ENV['s3-index'].prefix = 'stage-v1.2';
}
if (deployTarget === 'production') {
ENV.build.environment = 'production';
ENV['s3-index'].prefix = 'prod-v1.2';
}
// Note: if you need to build some configuration asynchronously, you can return
// a promise that resolves with the ENV object instead of returning the
// ENV object synchronously.
return ENV;
};
|
/* eslint-env node */
module.exports = function(deployTarget) {
var ENV = {
build: {},
exclude: ['.DS_Store', '*-test.js']
};
ENV.s3 = {
acl: 'public-read',
region: 'us-west-2',
bucket: 'ilios-frontend-assets'
};
ENV['s3-index'] = {
region: 'us-west-2',
filePattern: 'index.json',
bucket: 'frontend-json-config',
};
ENV.gzip = {
//dont gzip JSON files
filePattern: '**/*.{js,css,ico,map,xml,txt,svg,eot,ttf,woff,woff2}'
};
if (deployTarget === 'staging') {
ENV.build.environment = 'production';
ENV['s3-index'].prefix = 'stage-v1.1';
}
if (deployTarget === 'production') {
ENV.build.environment = 'production';
ENV['s3-index'].prefix = 'prod-v1.1';
}
// Note: if you need to build some configuration asynchronously, you can return
// a promise that resolves with the ENV object instead of returning the
// ENV object synchronously.
return ENV;
};
|
Remove unused ability to use custom newrelic.ini
|
# flake8: noqa
# newrelic import & initialization must come first
# https://docs.newrelic.com/docs/agents/python-agent/installation/python-agent-advanced-integration#manual-integration
try:
import newrelic.agent
except ImportError:
newrelic = False
else:
newrelic.agent.initialize()
import os
from bedrock.base.config_manager import config
IS_HTTPS = os.environ.get('HTTPS', '').strip() == 'on'
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bedrock.settings')
# must be imported after env var is set above.
from django.core.handlers.wsgi import WSGIRequest
from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise
from raven.contrib.django.raven_compat.middleware.wsgi import Sentry
class WSGIHTTPSRequest(WSGIRequest):
def _get_scheme(self):
if IS_HTTPS:
return 'https'
return super(WSGIHTTPSRequest, self)._get_scheme()
application = get_wsgi_application()
application.request_class = WSGIHTTPSRequest
application = DjangoWhiteNoise(application)
application = Sentry(application)
if newrelic:
application = newrelic.agent.wsgi_application()(application)
|
# flake8: noqa
# newrelic import & initialization must come first
# https://docs.newrelic.com/docs/agents/python-agent/installation/python-agent-advanced-integration#manual-integration
try:
import newrelic.agent
except ImportError:
newrelic = False
if newrelic:
newrelic_ini = config('NEWRELIC_PYTHON_INI_FILE', default='')
if newrelic_ini:
newrelic.agent.initialize(newrelic_ini)
else:
newrelic = False
import os
from bedrock.base.config_manager import config
IS_HTTPS = os.environ.get('HTTPS', '').strip() == 'on'
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bedrock.settings')
# must be imported after env var is set above.
from django.core.handlers.wsgi import WSGIRequest
from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise
from raven.contrib.django.raven_compat.middleware.wsgi import Sentry
class WSGIHTTPSRequest(WSGIRequest):
def _get_scheme(self):
if IS_HTTPS:
return 'https'
return super(WSGIHTTPSRequest, self)._get_scheme()
application = get_wsgi_application()
application.request_class = WSGIHTTPSRequest
application = DjangoWhiteNoise(application)
application = Sentry(application)
if newrelic:
application = newrelic.agent.wsgi_application()(application)
|
Add site footer to each documentation generator
|
var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-heights/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-heights/tachyons-heights.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_heights.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var siteFooter = fs.readFileSync('./templates/footer.html', 'utf8')
var template = fs.readFileSync('./templates/docs/heights/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs,
siteFooter: siteFooter
})
fs.writeFileSync('./docs/layout/heights/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-heights/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-heights/tachyons-heights.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_heights.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var template = fs.readFileSync('./templates/docs/heights/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs
})
fs.writeFileSync('./docs/layout/heights/index.html', html)
|
Fix bug where document element would never be allowed as valid element
|
'use strict';
// Holds the selected target. We need to fetch this from either contextmenu (obviously the best),
// or the mousedown event (filtered by button). The contextmenu event doesn't always provide us
// with the selected element, instead just giving us the HTML element, so we need to check that.
var target;
function getBackgroundImage(element) {
while (element) {
var bg = getComputedStyle(element).getPropertyValue('background-image');
if (bg !== 'none') {
return bg.match(/url\("?(.+?)"?\)/)[1];
}
element = element.parentElement;
}
}
function setTarget(e) {
var isDocument = e.target === window.document.documentElement;
var isMouseEvent = e.type === 'mousedown';
var isRightClick = isMouseEvent && e.which === 3;
// The `contextmenu` event has a thing where it returns the document
// element as the target instead of the one we actually want
if (!isMouseEvent && isDocument) {
return;
}
// Disregard left-clicks/middle-clicks
if (isMouseEvent && !isRightClick) {
return;
}
target = e.target;
}
function addListeners(frame) {
frame.addEventListener('mousedown', setTarget, false);
frame.document.addEventListener('contextmenu', setTarget, false);
}
addListeners(window);
// Listen for "get background image" requests, perform lookup and return the result
chrome.runtime.onMessage.addListener(function onMessage(msg, sender, sendResponse) {
sendResponse(getBackgroundImage(target));
});
|
'use strict';
// Holds the selected target. We need to fetch this from either contextmenu (obviously the best),
// or the mousedown event (filtered by button). The contextmenu event doesn't always provide us
// with the selected element, instead just giving us the HTML element, so we need to check that.
var target;
function getBackgroundImage(element) {
while (element) {
var bg = getComputedStyle(element).getPropertyValue('background-image');
if (bg !== 'none') {
return bg.match(/url\("?(.+?)"?\)/)[1];
}
element = element.parentElement;
}
}
function setTarget(e) {
var isActualTarget = e.target !== window.document.documentElement;
var isMouseEvent = e.type === 'mousedown';
var isRightClick = isMouseEvent && e.which === 3;
if (!isActualTarget || (isMouseEvent && isRightClick)) {
return;
}
target = e.target;
}
function addListeners(frame) {
frame.addEventListener('mousedown', setTarget, false);
frame.document.addEventListener('contextmenu', setTarget, false);
}
addListeners(window);
// Listen for "get background image" requests, perform lookup and return the result
chrome.runtime.onMessage.addListener(function onMessage(msg, sender, sendResponse) {
sendResponse(getBackgroundImage(target));
});
|
Set image sizes based on settings
* modified slidethis.js
|
/* SlideThis
Copyright (c) 2013 Liam Keene
Available under the MIT License
*/
(function($) {
$.fn.slidethis = function(options) {
// Default settings
var settings = $.extend({
'auto': true, // Boolean: automatically animate slides (true)
'pager': true, // Boolean: show pager for slides (true)
'speed': 500, // Integer: time (in ms) of transition (500)
'timeout': 5000, // Integer: time (in ms) between transitions (5000)
'width': 600, // Integer: width (in px) of the slideshow (600)
'height': 300, // Integer: height (in px) of the slideshow (300)
}, options);
return this.each(function() {
// Find some frequently used elements
var $this = $(this);
var $slides = $this.find('ul li');
var $images = $this.find('img');
// Hide slides except first
$slides.not(':first').hide();
// Set the dimensions of the images
$images.width(settings.width).height(settings.height);
});
};
}(jQuery));
|
/* SlideThis
Copyright (c) 2013 Liam Keene
Available under the MIT License
*/
(function($) {
$.fn.slidethis = function(options) {
// Default settings
var settings = $.extend({
'auto': true, // Boolean: automatically animate slides (true)
'pager': true, // Boolean: show pager for slides (true)
'speed': 500, // Integer: time (in ms) of transition (500)
'timeout': 5000, // Integer: time (in ms) between transitions (5000)
'width': 600, // Integer: width (in px) of the slideshow (600)
'height': 300, // Integer: height (in px) of the slideshow (300)
}, options);
return this.each(function() {
var $this = $(this);
var $slides = $('#slideshow li');
// Only show first image
$slides.not(':first').hide();
});
};
}(jQuery));
|
Add migration to backfill recipient counts
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('msgs', '0036_auto_20151103_1014'),
]
def backfill_recipient_counts(apps, schema):
Broadcast = apps.get_model('msgs', 'Broadcast')
Msg = apps.get_model('msgs', 'Msg')
# get all broadcasts with 0 recipients
for broadcast in Broadcast.objects.filter(recipient_count=0):
# set to # of msgs
broadcast.recipient_count = Msg.objects.filter(broadcast=broadcast).count()
if broadcast.recipient_count > 0:
broadcast.save()
print "Updated %d to %d recipients" % (broadcast.id, broadcast.recipient_count)
operations = [
migrations.RunPython(backfill_recipient_counts)
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('msgs', '0036_auto_20151103_1014'),
]
def backfill_recipient_counts(apps, schema):
Broadcast = apps.get_model('msgs', 'Broadcast')
Msg = apps.get_model('msgs', 'Msg')
# get all broadcasts with 0 recipients
for broadcast in Broadcast.objects.filter(recipient_count=0):
# set to # of msgs
broadcast.recipient_count = Msg.objects.filter(broadcast=broadcast).count()
if recipient_count > 0:
broadcast.save()
print "Updated %d to %d recipients" % (broadcast.id, broadcast.recipient_count)
operations = [
migrations.RunPython(backfill_recipient_counts)
]
|
Apply Canny edge detection to grayscale. No big difference with colored Canny edge detection.
|
""" Apply different filters here """
import cv2 # import OpenCV 3 module
camera = cv2.VideoCapture(0) # get default camera
mode = 2 # default mode, apply Canny edge detection
while True:
ok, frame = camera.read() # read frame
if ok: # frame is read correctly
if mode == 2:
frame = cv2.Canny(frame, 100, 200) # Canny edge detection
if mode == 3:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # convert to grayscale
frame = cv2.Canny(frame, 100, 200) # Canny edge detection
cv2.imshow('My camera', frame) # show frame
key = cv2.waitKey(1) & 0xff # read keystroke
if key == 27: break # <Escape> key pressed, exit from cycle
if key == ord('1'): mode = 1 # show unchanged frame
if key == ord('2'): mode = 2 # apply Canny edge detection
if key == ord('3'): mode = 3 # apply Canny to gray frame
camera.release() # release web camera
cv2.destroyAllWindows()
|
""" Apply different filters here """
import cv2 # import OpenCV 3 module
camera = cv2.VideoCapture(0) # get default camera
mode = 2 # default mode, apply Canny edge detection
while True:
ok, frame = camera.read() # read frame
if ok: # frame is read correctly
if mode == 2:
frame = cv2.Canny(frame, 100, 200) # Canny edge detection
cv2.imshow('My camera', frame) # show frame
key = cv2.waitKey(1) & 0xff # read keystroke
if key == 27: break # <Escape> key pressed, exit from cycle
if key == ord('1'): mode = 1 # show unchanged frame
if key == ord('2'): mode = 2 # apply Canny edge detection
camera.release() # release web camera
cv2.destroyAllWindows()
|
fix: Fix persisten menu command fail.
|
<?php
/**
* User: casperlai
* Date: 2016/9/2
* Time: 下午9:34
*/
namespace Casperlaitw\LaravelFbMessenger\Messages;
use Casperlaitw\LaravelFbMessenger\Contracts\Messages\Message;
use Casperlaitw\LaravelFbMessenger\Contracts\Messages\ThreadInterface;
/**
* Class PersistentMenuMessage
* @package Casperlaitw\LaravelFbMessenger\Messages
*/
class PersistentMenuMessage extends Message implements ThreadInterface
{
use Deletable;
/**
* @var
*/
private $buttons;
/**
* PersistentMenuMessage constructor.
*
* @param $buttons
*/
public function __construct($buttons = [])
{
parent::__construct(null);
$this->buttons = $buttons;
}
/**
* Message to send
* @return array
*/
public function toData()
{
$buttons = collect($this->buttons);
return [
'setting_type' => 'call_to_actions',
'thread_state' => 'existing_thread',
'call_to_actions' => $buttons->map(function (Button $item) {
return $item->toData();
})->toArray(),
];
}
}
|
<?php
/**
* User: casperlai
* Date: 2016/9/2
* Time: 下午9:34
*/
namespace Casperlaitw\LaravelFbMessenger\Messages;
use Casperlaitw\LaravelFbMessenger\Contracts\Messages\Message;
use Casperlaitw\LaravelFbMessenger\Contracts\Messages\ThreadInterface;
use pimax\Messages\MessageButton;
/**
* Class PersistentMenuMessage
* @package Casperlaitw\LaravelFbMessenger\Messages
*/
class PersistentMenuMessage extends Message implements ThreadInterface
{
use Deletable;
/**
* @var
*/
private $buttons;
/**
* PersistentMenuMessage constructor.
*
* @param $buttons
*/
public function __construct($buttons = [])
{
parent::__construct(null);
$this->buttons = $buttons;
}
/**
* Message to send
* @return array
*/
public function toData()
{
$buttons = collect($this->buttons);
return [
'setting_type' => 'call_to_actions',
'thread_state' => 'existing_thread',
'call_to_actions' => $buttons->map(function (MessageButton $item) {
return $item->getData();
})->toArray(),
];
}
}
|
Add a start and end method to MockRequest
|
#!/usr/bin/python2.5
#
# Copyright 2008 the Melange 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.
"""Common testing utilities.
"""
__authors__ = [
'"Augie Fackler" <durin42@gmail.com>',
'"Sverre Rabbelier" <sverre@rabbelier.nl>',
]
from soc.modules import callback
class MockRequest(object):
"""Shared dummy request object to mock common aspects of a request.
Before using the object, start should be called, when done (and
before calling start on a new request), end should be called.
"""
def __init__(self, path=None):
"""Creates a new empty request object.
self.REQUEST, self.GET and self.POST are set to an empty
dictionary, and path to the value specified.
"""
self.REQUEST = {}
self.GET = {}
self.POST = {}
self.path = path
def start(self):
"""Readies the core for a new request.
"""
core = callback.getCore()
core.startNewRequest(self)
def end(self):
"""Finishes up the current request.
"""
core = callback.getCore()
core.endRequest(self, False)
|
#!/usr/bin/python2.5
#
# Copyright 2008 the Melange 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.
"""Common testing utilities.
"""
__authors__ = [
'"Augie Fackler" <durin42@gmail.com>',
]
class MockRequest(object):
"""Shared dummy request object to mock common aspects of a request.
"""
def __init__(self, path=None):
self.REQUEST = self.GET = self.POST = {}
self.path = path
|
Throw an error when getting common name instead of FALSE
CNAME or common/resource name is needed to construct instances of
Aurora/Model/Collection. Throwing an error will help us debug our code
sooner.
|
<?php
defined('SYSPATH') or die('No direct script access.');
/**
* Helper class to work with Kohana Profiler
*
* @package Aurora
* @author Samuel Demirdjian
* @copyright (c) 2013, Samuel Demirdjian
* @license http://license.enov.ws/mit MIT
*
*/
class Aurora_Aurora_Profiler
{
/**
* @var string The profiling category under which benchmarks will appear
*/
protected static $category = 'Aurora';
/**
* Add a profiling mark and start counter
*
* @param Aurora $aurora
* @param string $function
* @return string benchmark id in Profiler
*/
public static function start($aurora, $function) {
if (empty($aurora) OR empty($function))
return FALSE;
$name = Aurora_Type::cname($aurora) . '::' . $function;
$benchmark =
(Kohana::$profiling === TRUE) ?
Profiler::start(static::$category, $name) :
FALSE;
return $benchmark;
}
/**
* Stop a profiling mark
*
* @param string $benchmark
*/
public static function stop($benchmark) {
if (!empty($benchmark)) {
// Stop the benchmark
Profiler::stop($benchmark);
}
}
/**
* Delete a profiling mark
*
* @param string $benchmark
*/
public static function delete($benchmark) {
if (!empty($benchmark)) {
// Delete the benchmark
Profiler::delete($benchmark);
}
}
}
|
<?php
defined('SYSPATH') or die('No direct script access.');
/**
* Helper class to work with Kohana Profiler
*
* @package Aurora
* @author Samuel Demirdjian
* @copyright (c) 2013, Samuel Demirdjian
* @license http://license.enov.ws/mit MIT
*
*/
class Aurora_Aurora_Profiler
{
/**
* @var string The profiling category under which benchmarks will appear
*/
protected static $category = 'Aurora';
/**
* Add a profiling mark and start counter
*
* @param Aurora $aurora
* @param string $function
* @return string benchmark id in Profiler
*/
public static function start($aurora, $function) {
$name = Aurora_Type::cname($aurora) . '::' . $function;
$benchmark =
(Kohana::$profiling === TRUE) ?
Profiler::start(static::$category, $name) :
FALSE;
return $benchmark;
}
/**
* Stop a profiling mark
*
* @param string $benchmark
*/
public static function stop($benchmark) {
if (!empty($benchmark)) {
// Stop the benchmark
Profiler::stop($benchmark);
}
}
/**
* Delete a profiling mark
*
* @param string $benchmark
*/
public static function delete($benchmark) {
if (!empty($benchmark)) {
// Delete the benchmark
Profiler::delete($benchmark);
}
}
}
|
Revert "Revert "Upgrade to jenkinsapi==0.2.29""
This reverts commit 35ffadfd1adb1a02875e0e0cfcf1c67f229e2ba9.
|
from setuptools import setup
from webhooks import __version__
with open('README.rst') as f:
long_description = f.read()
setup(
name='webhooks',
version=__version__,
description='Flask app for triggering Jenkins builds by GitHub webhooks',
long_description=long_description,
url='https://github.com/Wikia/jenkins-webhooks',
author='macbre',
author_email='macbre@wikia-inc.com',
packages=['webhooks'],
install_requires=[
'Flask==0.10.1',
'jenkinsapi==0.2.29',
'pytest==2.6.0',
'pyyaml==3.11',
'mock==1.0.1',
'gunicorn==19.4.5'
],
include_package_data=True,
entry_points={
'console_scripts': [
'webhooks-server=webhooks.app:run'
],
},
)
|
from setuptools import setup
from webhooks import __version__
with open('README.rst') as f:
long_description = f.read()
setup(
name='webhooks',
version=__version__,
description='Flask app for triggering Jenkins builds by GitHub webhooks',
long_description=long_description,
url='https://github.com/Wikia/jenkins-webhooks',
author='macbre',
author_email='macbre@wikia-inc.com',
packages=['webhooks'],
install_requires=[
'Flask==0.10.1',
'jenkinsapi==0.2.25',
'pytest==2.6.0',
'pyyaml==3.11',
'mock==1.0.1',
'gunicorn==19.4.5'
],
include_package_data=True,
entry_points={
'console_scripts': [
'webhooks-server=webhooks.app:run'
],
},
)
|
Mark relative imports as a rabbit hole discussion
|
"""
_
___ __ _ | | ___
/ __|/ _` || | / __|
| (__| (_| || || (__
\___|\__,_||_| \___|
Rabbit hole:
The relative imports here (noted by the . prefix) are done as a convenience
so that the consumers of the ``calc`` package can directly use objects
belonging to the ``calc.calc`` module. Essentially this enables the consumer
to do
>>> from calc import INTEGER
instead of having to use the slightly longer
>>> from calc.calc import INTEGER
"""
__author__ = 'Reilly Tucker Siemens, Alex LordThorsen'
__email__ = 'reilly@tuckersiemens.com, alexlordthorsen@gmail.com'
__version__ = '0.1.0'
from .calc import Calc, CalcError
from .token import INTEGER, EOF, PLUS, Token
|
"""
_
___ __ _ | | ___
/ __|/ _` || | / __|
| (__| (_| || || (__
\___|\__,_||_| \___|
Note:
The relative imports here (noted by the . prefix) are done as a convenience
so that the consumers of the ``calc`` package can directly use objects
belonging to the ``calc.calc`` module. Essentially this enables the consumer
to do
>>> from calc import INTEGER
instead of having to use the slightly longer
>>> from calc.calc import INTEGER
"""
__author__ = 'Reilly Tucker Siemens, Alex LordThorsen'
__email__ = 'reilly@tuckersiemens.com, alexlordthorsen@gmail.com'
__version__ = '0.1.0'
from .calc import Calc, CalcError
from .token import INTEGER, EOF, PLUS, Token
|
[SMALLFIX] Use static imports for standard test utilities
[SMALLFIX] Use static imports for standard test utilities
pr-link: Alluxio/alluxio#8823
change-id: cid-8d5f96ba6dd7d80c6f8c61a6d4698083a91ee043
|
/*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.retry;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
/**
* Tests for the {@link TimeoutRetry} class.
*/
public final class TimeoutRetryTest {
/**
* Tests that the provided timeout is respected.
*/
@Test
public void timeout() {
final long timeoutMs = 50;
final int sleepMs = 10;
int attempts = 0;
TimeoutRetry timeoutRetry = new TimeoutRetry(timeoutMs, sleepMs);
assertEquals(0, timeoutRetry.getAttemptCount());
long startMs = System.currentTimeMillis();
while (timeoutRetry.attempt()) {
attempts++;
}
long endMs = System.currentTimeMillis();
assertTrue(attempts > 0);
assertTrue((endMs - startMs) >= timeoutMs);
assertEquals(attempts, timeoutRetry.getAttemptCount());
assertTrue(attempts <= (timeoutMs / sleepMs) + 1);
}
}
|
/*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.retry;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests for the {@link TimeoutRetry} class.
*/
public final class TimeoutRetryTest {
/**
* Tests that the provided timeout is respected.
*/
@Test
public void timeout() {
final long timeoutMs = 50;
final int sleepMs = 10;
int attempts = 0;
TimeoutRetry timeoutRetry = new TimeoutRetry(timeoutMs, sleepMs);
Assert.assertEquals(0, timeoutRetry.getAttemptCount());
long startMs = System.currentTimeMillis();
while (timeoutRetry.attempt()) {
attempts++;
}
long endMs = System.currentTimeMillis();
Assert.assertTrue(attempts > 0);
Assert.assertTrue((endMs - startMs) >= timeoutMs);
Assert.assertEquals(attempts, timeoutRetry.getAttemptCount());
Assert.assertTrue(attempts <= (timeoutMs / sleepMs) + 1);
}
}
|
Change scrapper trigger to http request
|
const Datastore = require('@google-cloud/datastore')
const projectId = 'pirula-time'
const datastore = Datastore({
projectId: projectId
})
const kind = 'time'
const averageKey = datastore.key([kind, 'average'])
function scrape() {
const data = {
average: 1800,
}
return data
}
exports.doIt = function doIt(req, res) {
console.log("DOIN' IT!")
const message = req.body.message
const data = scrape()
const saveData = {
key: averageKey,
data: {
val: data.average
}
}
datastore.save(saveData)
.then(() => {
res.status(200).send(`Saved ${JSON.stringify(saveData)}`)
})
.catch((err) => {
res.status(500).send('Error: ' + err.toString())
})
}
|
// Imports the Google Cloud client library
const Datastore = require('@google-cloud/datastore')
// Your Google Cloud Platform project ID
const projectId = 'pirula-time'
// Instantiates a client
const datastore = Datastore({
projectId: projectId
})
// The kind for the new entity
const kind = 'time'
// The name/ID for the new entity
const name = 'average'
// The Cloud Datastore key for the new entity
const key = datastore.key([kind, name])
function scrape() {
const data = {
average: 3200,
}
return data
}
/**
* Triggered from a message on a Cloud Pub/Sub topic.
*
* @param {!Object} event The Cloud Functions event.
* @param {!Function} The callback function.
*/
exports.subscribe = function subscribe(event, callback) {
console.log("START")
// The Cloud Pub/Sub Message object.
const pubsubMessage = event.data
const data = scrape()
// Prepares the new entity
const average = {
key: key,
data: {
val: data.average
}
}
// Saves the entity
datastore.save(average)
.then(() => {
console.log(`Saved ${average.key.name}: ${average.data}`)
})
.catch((err) => {
console.error('ERROR:', err)
})
// Don't forget to call the callback.
callback()
};
|
Set up Travis tests with pytest for all versions
|
import setuptools
setuptools.setup(
name='ChatExchange6',
version='0.0.1',
url='https://github.com/ByteCommander/ChatExchange6',
packages=[
'chatexchange6'
],
install_requires=[
'beautifulsoup4>=4.3.2',
'requests>=2.2.1',
'websocket-client>=0.13.0',
# only for dev:
'coverage>=3.7.1',
'epydoc>=3.0.1',
'httmock>=1.2.2',
'pytest-capturelog>=0.7',
'pytest-timeout>=0.3',
'pytest>=2.7.3',
'py>=1.4.29'
]
)
|
import setuptools
setuptools.setup(
name='ChatExchange6',
version='0.0.1',
url='https://github.com/ByteCommander/ChatExchange6',
packages=[
'chatexchange6'
],
install_requires=[
'beautifulsoup4>=4.3.2',
'requests>=2.2.1',
'websocket-client>=0.13.0',
# only for dev:
'coverage>=3.7.1',
'epydoc>=3.0.1',
'httmock>=1.2.2',
'pytest-capturelog>=0.7',
'pytest-timeout>=0.3',
'pytest>=2.7.3'
]
)
|
Change contructor parameter in migrations
|
var NeufundTestToken = artifacts.require("./NeufundTestToken.sol");
var Crowdsale = artifacts.require("./Crowdsale.sol");
module.exports = function (deployer) {
/**
* address ifSuccessfulSendTo,
* uint fundingGoalInEthers,
* uint durationInMinutes,
* uint weiCostOfEachToken,
* Token addressOfTokenUsedAsReward
*/
deployer.then(()=> {
return NeufundTestToken.deployed();
}).then((instance)=> {
console.log(instance.address);
var ifSuccessfulSendTo = "0xb67fb67eb9e4700c90f2ab65c8ecbb3b687d49c7";
var fundingGoalInEthers = 1;
var durationInMinutes = 1;
var weiCostOfEachToken = 1;
var addressOfTokenUsedAsReward = instance.address;
return deployer.deploy(Crowdsale,
ifSuccessfulSendTo,
fundingGoalInEthers,
durationInMinutes,
weiCostOfEachToken,
addressOfTokenUsedAsReward);
});
};
|
var NeufundTestToken = artifacts.require("./NeufundTestToken.sol");
var Crowdsale = artifacts.require("./Crowdsale.sol");
module.exports = function (deployer) {
/**
* address ifSuccessfulSendTo,
* uint fundingGoalInEthers,
* uint durationInMinutes,
* uint etherCostOfEachToken,
* Token addressOfTokenUsedAsReward
*/
deployer.then(()=> {
return NeufundTestToken.deployed();
}).then((instance)=> {
console.log(instance.address);
var ifSuccessfulSendTo = "0xb67fb67eb9e4700c90f2ab65c8ecbb3b687d49c7";
var fundingGoalInEthers = 1;
var durationInMinutes = 1;
var weiCostOfEachToken = 1;
var addressOfTokenUsedAsReward = instance.address;
return deployer.deploy(Crowdsale,
ifSuccessfulSendTo,
fundingGoalInEthers,
durationInMinutes,
weiCostOfEachToken,
addressOfTokenUsedAsReward);
});
};
|
test: Add comments explaining slightly obtuse test code.
|
import reactify from '../../src/index';
let x = 0;
function createComponent() {
return reactify(document.registerElement(`x-webcomponent-proto-funcs-${x++}`, {
prototype: Object.create(HTMLElement.prototype, {
prop: {
value: 'prop',
},
foo: {
value() {
return 'bar';
},
},
getProp: {
value() {
return this.prop;
},
},
getter: {
get() {
throw new Error('should not throw when reactifying');
},
},
}),
}));
}
describe('Webcomponent prototype functions', () => {
it('should be callable on React component', () => {
const Comp = createComponent();
expect(Comp.prototype.foo()).to.equal('bar');
});
it('should return prop', () => {
const Comp = createComponent();
expect(Comp.prototype.getProp()).to.equal('prop');
});
it('should not invoke getters', () => {
// If this functionality fails, calling createComponent() should cause the error to be thrown.
const Comp = createComponent();
// We expect it to throw here to make sure we've written our test correctly.
expect(() => Comp.prototype.getter).to.throw();
});
});
|
import reactify from '../../src/index';
let x = 0;
function createComponent() {
return reactify(document.registerElement(`x-webcomponent-proto-funcs-${x++}`, {
prototype: Object.create(HTMLElement.prototype, {
prop: {
value: 'prop',
},
foo: {
value() {
return 'bar';
},
},
getProp: {
value() {
return this.prop;
},
},
getter: {
get() {
throw new Error('should not throw when reactifying');
},
},
}),
}));
}
describe('Webcomponent prototype functions', () => {
it('should be callable on React component', () => {
const Comp = createComponent();
expect(Comp.prototype.foo()).to.equal('bar');
});
it('should return prop', () => {
const Comp = createComponent();
expect(Comp.prototype.getProp()).to.equal('prop');
});
it('should not invoke getters', () => {
const Comp = createComponent();
expect(() => Comp.prototype.getter).to.throw();
});
});
|
Fix unexpected var, use let or const instead
|
'use strict'
const markdownIt = require('markdown-it')
exports.name = 'markdown-it'
exports.outputFormat = 'html'
exports.inputFormats = ['markdown-it', 'markdown', 'md']
exports.render = function (str, options) {
options = Object.assign({}, options || {})
// Copy render rules from options, and remove them from options, since
// they're invalid.
let renderRules = Object.assign({}, options.renderRules || {})
delete options.renderRules
const md = markdownIt(options)
// Enable render rules.
Object.assign(md.renderer.rules, renderRules);
// Parse the plugins.
(options.plugins || []).forEach(plugin => {
if (!Array.isArray(plugin)) {
plugin = [plugin]
}
if (typeof plugin[0] === 'string') {
// eslint-disable-next-line import/no-dynamic-require
plugin[0] = require(plugin[0])
}
md.use.apply(md, plugin)
});
// Parse enable/disable rules.
(options.enable || []).forEach(rule => {
md.enable.apply(md, Array.isArray(rule) ? rule : [rule])
});
(options.disable || []).forEach(rule => {
md.disable.apply(md, Array.isArray(rule) ? rule : [rule])
})
// Render the markdown.
if (options.inline) {
return md.renderInline(str)
}
return md.render(str)
}
|
'use strict'
const markdownIt = require('markdown-it')
exports.name = 'markdown-it'
exports.outputFormat = 'html'
exports.inputFormats = ['markdown-it', 'markdown', 'md']
exports.render = function (str, options) {
options = Object.assign({}, options || {})
// Copy render rules from options, and remove them from options, since
// they're invalid.
var renderRules = Object.assign({}, options.renderRules || {})
delete options.renderRules
var md = markdownIt(options)
// Enable render rules.
Object.assign(md.renderer.rules, renderRules);
// Parse the plugins.
(options.plugins || []).forEach(plugin => {
if (!Array.isArray(plugin)) {
plugin = [plugin]
}
if (typeof plugin[0] === 'string') {
// eslint-disable-next-line import/no-dynamic-require
plugin[0] = require(plugin[0])
}
md.use.apply(md, plugin)
});
// Parse enable/disable rules.
(options.enable || []).forEach(rule => {
md.enable.apply(md, Array.isArray(rule) ? rule : [rule])
});
(options.disable || []).forEach(rule => {
md.disable.apply(md, Array.isArray(rule) ? rule : [rule])
})
// Render the markdown.
if (options.inline) {
return md.renderInline(str)
}
return md.render(str)
}
|
Fix unit test build failure
We didn't catch the failure because we tested against the fork instead
of master. I think.
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.action;
import org.elasticsearch.action.DocWriteResponse.Operation;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.test.ESTestCase;
public class DocWriteResponseTests extends ESTestCase {
public void testGetLocation() {
DocWriteResponse response = new DocWriteResponse(new ShardId("index", "uuid", 0), "type", "id", 0, Operation.CREATE) {
// DocWriteResponse is abstract so we have to sneak a subclass in here to test it.
};
assertEquals("/index/type/id", response.getLocation(null));
assertEquals("/index/type/id?routing=test_routing", response.getLocation("test_routing"));
}
}
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.action;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.test.ESTestCase;
public class DocWriteResponseTests extends ESTestCase {
public void testGetLocation() {
DocWriteResponse response = new DocWriteResponse(new ShardId("index", "uuid", 0), "type", "id", 0) {
// DocWriteResponse is abstract so we have to sneak a subclass in here to test it.
};
assertEquals("/index/type/id", response.getLocation(null));
assertEquals("/index/type/id?routing=test_routing", response.getLocation("test_routing"));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.