text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Fix parameter parsing in gaussian lda preprocessing.
|
import argparse
from codecs import open
import logging
import os
from gensim.models import Word2Vec
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
if __name__ == "__main__":
parser = argparse.ArgumentParser("Prepare model for Gaussian LDA")
parser.add_argument("--topic-model", type=str)
parser.add_argument("--embedding-model", type=str)
args = parser.parse_args()
word2vec = Word2Vec.load_word2vec_format(args.embedding_model, binary=True)
embedding_name = os.path.basename(args.embedding_model)
with open(args.topic_model + "." + embedding_name + ".gaussian-lda", "w", encoding="utf-8") as output:
with open(args.topic_model + "." + embedding_name + ".restricted.alphabet", "r", encoding="utf-8") as f:
for line in f:
word = line.split("#")[0]
output.write(word + " ")
output.write(" ".join(map(str, word2vec[word])))
output.write("\n")
|
import argparse
import logging
import os
from gensim.models import Word2Vec
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
if __name__ == "__main__":
parser = argparse.ArgumentParser("Prepare model for Gaussian LDA")
parser.add_argument("--topic_model", type=str)
parser.add_argument("--embedding_model", type=str)
args = parser.parse_args()
word2vec = Word2Vec.load_word2vec_format(args.embedding_model, binary=True)
embedding_name = os.path.basename(args.embedding_model)
with open(args.topic_model + "." + embedding_name + ".gaussian-lda", "w") as output:
with open(args.topic_model + ".restricted.alphabet", "r") as f:
for line in f:
word = line.split("#")[0]
output.write(word + " ")
output.write(" ".join(word2vec[word]))
output.write("\n")
|
Fix WebDAV integration tests initialization
|
'use strict';
var webdavd = require('test/integration/utils/webdavd');
var scenarios = require('test/integration/scenarios');
var transfer = require('lib/file-transfer');
describe('WebDAV', function () {
var instances = {
server: null,
client: null
};
before('start the server', function (done) {
webdavd({
username: 'foo',
password: 'bar'
}, function (error, _server) {
if (error) {
return done(error);
}
instances.server = _server;
instances.server.listen(20001, '127.0.0.1', done);
});
});
before('connect to the server', function () {
return transfer.connect('webdav', {
host: '127.0.0.1',
port: 20001,
username: 'foo',
password: 'bar'
}).then(function (_client) {
instances.client = _client;
});
});
scenarios.forEach(function (scenario) {
scenario(instances);
});
after('disconnect from the server', function () {
instances.client.disconnect();
});
after('close the server', function (done) {
instances.server.close(done);
});
});
|
'use strict';
var webdavd = require('test/integration/utils/webdavd');
var scenarios = require('test/integration/scenarios');
var transfer = require('lib/file-transfer');
describe('WebDAV', function () {
var instances = {
server: null,
client: null
};
before('start the server', function (done) {
webdavd({
username: 'foo',
password: 'bar'
}, function (error, _server) {
if (error) {
return done(error);
}
instances.server = _server;
instances.server.listen(20001, '127.0.0.1', done);
});
});
before('connect to the server', function () {
transfer.connect('webdav', {
host: '127.0.0.1',
port: 20001,
username: 'foo',
password: 'bar'
}).then(function (_client) {
instances.client = _client;
});
});
scenarios.forEach(function (scenario) {
scenario(instances);
});
after('disconnect from the server', function () {
instances.client.disconnect();
});
after('close the server', function (done) {
instances.server.close(done);
});
});
|
Change regex, added some non-catching groups
|
import re
import urllib2
import traceback
try:
import simplejson as json
except ImportError:
import json
class Twitter(object):
"""Checks incoming messages for Twitter urls and calls the Twitter API to
retrieve the tweet.
TODO:
Implement commands for Twitter functionality
"""
pattern = re.compile("http(?:s|)://(?:mobile\.|)(?:www\.|)twitter.com/(?:#!/|)[^/]+/status/([0-9]+)")
def __init__(self, *args, **kwargs):
"""Constructor."""
pass
def handle(self, match, **kwargs):
try:
data = self.fetch (match.group(1))
return '\x02%s\x02 tweets "%s"' % (data['user']['name'], ''.join(data['text'].splitlines()))
except:
print "Problem fetching tweet"
print traceback.print_exc()
def fetch(self, status_id):
"""Use Twitter's REST API to fetch a status."""
api_url = 'http://api.twitter.com/1/statuses/show.json?id=%s&include_entities=true' % (status_id)
req = urllib2.Request(api_url)
response = urllib2.urlopen(req)
page = response.read()
decoded = json.loads(page)
return decoded
|
import re
import urllib2
import traceback
try:
import simplejson as json
except ImportError:
import json
class Twitter(object):
"""Checks incoming messages for Twitter urls and calls the Twitter API to
retrieve the tweet.
TODO:
Implement commands for Twitter functionality
"""
pattern = re.compile("http(s|)://(www\.|)twitter.com/(?:#!/|)[^/]+/status/([0-9]+)")
def __init__(self, *args, **kwargs):
"""Constructor."""
pass
def handle(self, match, **kwargs):
try:
data = self.fetch (match.group(3))
return '\x02%s\x02 tweets "%s"' % (data['user']['name'], ''.join(data['text'].splitlines()))
except:
print "Problem fetching tweet"
print traceback.print_exc()
def fetch(self, status_id):
"""Use Twitter's REST API to fetch a status."""
api_url = 'http://api.twitter.com/1/statuses/show.json?id=%s&include_entities=true' % (status_id)
req = urllib2.Request(api_url)
response = urllib2.urlopen(req)
page = response.read()
decoded = json.loads(page)
return decoded
|
Refresh the proxy example list
|
"""
Proxy Server "Phone Book".
Simplify running browser tests through a proxy server
by adding your frequently-used proxies here.
Now you can do something like this on the command line:
"pytest SOME_TEST.py --proxy=proxy1"
Format of PROXY_LIST server entries:
* "ip_address:port" OR "username:password@ip_address:port"
* "server:port" OR "username:password@server:port"
(Do NOT include the http:// or https:// in your proxy string!)
Example proxies in PROXY_LIST below are not guaranteed to be active or secure.
If you don't already have a proxy server to connect to,
you can try finding one from one of following sites:
* https://www.us-proxy.org/
"""
PROXY_LIST = {
"example1": "52.187.121.7:3128", # (Example) - set your own proxy here
"example2": "193.32.6.6:8080", # (Example) - set your own proxy here
"proxy1": None,
"proxy2": None,
"proxy3": None,
"proxy4": None,
"proxy5": None,
}
|
"""
Proxy Server "Phone Book".
Simplify running browser tests through a proxy server
by adding your frequently-used proxies here.
Now you can do something like this on the command line:
"pytest SOME_TEST.py --proxy=proxy1"
Format of PROXY_LIST server entries:
* "ip_address:port" OR "username:password@ip_address:port"
* "server:port" OR "username:password@server:port"
(Do NOT include the http:// or https:// in your proxy string!)
Example proxies in PROXY_LIST below are not guaranteed to be active or secure.
If you don't already have a proxy server to connect to,
you can try finding one from one of following sites:
* https://www.us-proxy.org/
"""
PROXY_LIST = {
"example1": "52.187.121.7:3128", # (Example) - set your own proxy here
"example2": "193.32.6.6:8080", # (Example) - set your own proxy here
"example3": "185.204.208.78:8080", # (Example) - set your own proxy here
"proxy1": None,
"proxy2": None,
"proxy3": None,
"proxy4": None,
"proxy5": None,
}
|
Add whitespace for git's enjoyment
|
var express = require('express'),
app = express(),
path = require('path'),
port = (process.argv[2] || 8000);
app.get('/api/:file.json', function(req, res) {
console.log(req.params.file);
var response = [
{
"id": 1,
"title": "SUPER",
"description": "Salesforce Upcoming Projects Evaluation Rankings",
"favorite": false
},
{
"id": 2,
"title": "Über",
"description": "Ünderständing better external resources",
"favorite": false
}
];
res.json(response);
});
app.use(express.static(__dirname));
app.listen(port);
console.log("Running on http://localhost:" + port + " \nCTRL + C to shutdown");
|
var express = require('express'),
app = express(),
path = require('path'),
port = (process.argv[2] || 8000);
app.get('/api/:file.json', function(req, res) {
console.log(req.params.file);
var response = [
{
"id": 1,
"title": "SUPER",
"description": "Salesforce Upcoming Projects Evaluation Rankings",
"favorite": false
},
{
"id": 2,
"title": "Über",
"description": "Ünderständing better external resources",
"favorite": false
}
];
res.json(response);
});
app.use(express.static(__dirname));
app.listen(port);
console.log("Running on http://localhost:" + port + " \nCTRL + C to shutdown");
|
Test twitter image size bump
|
const environment = require('./environment');
const globals = {
subreddits: {
'funny': 'funny',
'cute': 'aww',
'pics': 'pics',
'gifs': 'gifs',
'gaming': 'gaming',
'earth': 'earthPorn',
},
defaultLink: {
text: "Uh oh! We couldn't find the picture you were looking for. We'll try to fix it on our end :)",
href: 'http://imgur.com/PbcZq8t.jpg',
linkId: 47378
},
defaultFilename: __dirname + '/renderedSharedLinks/defaultLink.html',
linkRefreshInterval: '30 * * * *', // hourly on the **:30
fileCleanupInterval: '1 0 * * * *', // daily at 12:01am
renderedSubredditsDir: __dirname + '/renderedSubreddits/',
renderedSharedLinksDir: __dirname + '/renderedSharedLinks/',
stylesheetDir: __dirname + '/style.css',
staticFileDir: __dirname + '/static',
maxFbThumbnailBytes: 8000000, // < 8 MB
maxTwThumbnailBytes: 10000000, // < 10 MB
defaultThumbnailUrl: "http://www.pic.fish/logo.png",
maxValidationRequestTime: 20000, // 10 s
}
if (environment.mode === "dev" && process.argv.indexOf('short')) {
globals.subreddits = { 'cute': 'aww' };
}
module.exports = globals;
|
const environment = require('./environment');
const globals = {
subreddits: {
'funny': 'funny',
'cute': 'aww',
'pics': 'pics',
'gifs': 'gifs',
'gaming': 'gaming',
'earth': 'earthPorn',
},
defaultLink: {
text: "Uh oh! We couldn't find the picture you were looking for. We'll try to fix it on our end :)",
href: 'http://imgur.com/PbcZq8t.jpg',
linkId: 47378
},
defaultFilename: __dirname + '/renderedSharedLinks/defaultLink.html',
linkRefreshInterval: '30 * * * *', // hourly on the **:30
fileCleanupInterval: '1 0 * * * *', // daily at 12:01am
renderedSubredditsDir: __dirname + '/renderedSubreddits/',
renderedSharedLinksDir: __dirname + '/renderedSharedLinks/',
stylesheetDir: __dirname + '/style.css',
staticFileDir: __dirname + '/static',
maxFbThumbnailBytes: 8000000, // < 8 MB
maxTwThumbnailBytes: 1000000, // < 1 MB
defaultThumbnailUrl: "http://www.pic.fish/logo.png",
maxValidationRequestTime: 20000, // 10 s
}
if (environment.mode === "dev" && process.argv.indexOf('short')) {
globals.subreddits = { 'cute': 'aww' };
}
module.exports = globals;
|
chore(fixture-tests): Improve app test and silence pylint
|
"""
Test fixtures.
:copyright: (c) 2017 Derek M. Frank
:license: MPL-2.0
"""
from flask import Flask # type: ignore
def test_simple_app(app):
"""Verify basic application."""
assert isinstance(app, Flask)
def test_simple_config(config):
"""Verify basic application configuration."""
assert isinstance(config, dict)
def test_webdriver_current_url(webdriver):
"""
Verify data URL.
Chrome: 'data:,'
Firefox: 'about:blank'
"""
assert webdriver.current_url in ['data:,', 'about:blank']
def test_webdriver_valid_service(webdriver, services=('chrome', 'firefox')):
"""Make sure valid service is being used."""
assert webdriver.name in services
def test_webdriver_get_google(webdriver):
"""If google is down, something bad has happened."""
webdriver.get('http://google.com/')
assert 'Google' in webdriver.title
def test_page_proxies_webdriver(page):
"""Verify webdriver proxying."""
assert page.title == page.driver.title
assert page.current_url == page.driver.current_url
assert page.get == page.driver.get
|
"""
Test fixtures.
:copyright: (c) 2017 Derek M. Frank
:license: MPL-2.0
"""
def test_simple_app(app):
"""Verify basic application."""
assert app
def test_simple_config(config):
"""Verify basic application configuration."""
assert isinstance(config, dict)
def test_webdriver_current_url(webdriver):
"""
Verify data URL.
Chrome: 'data:,'
Firefox: 'about:blank'
"""
assert webdriver.current_url in ['data:,', 'about:blank']
def test_webdriver_valid_service(webdriver, services=('chrome', 'firefox')):
"""Make sure valid service is being used."""
assert webdriver.name in services
def test_webdriver_get_google(webdriver):
"""If google is down, something bad has happened."""
webdriver.get('http://google.com/')
assert 'Google' in webdriver.title
def test_page_proxies_webdriver(page):
"""Verify webdriver proxying."""
assert page.title == page.driver.title
assert page.current_url == page.driver.current_url
assert page.get == page.driver.get
|
Clean up task file source
|
'use strict';
// Load our modules
const logger = __require('libs/log'),
task = __require('libs/task'),
queue = __require('libs/queue');
// General task file handling
module.exports = function(options) {
// Does the user want to run this?
if ( options.no_task ) {
return;
}
// Let the user know
logger.info('Loading tasks from configuration file');
// Load tasks from file
task.load('tasks.json').then((tasks) => {
// Check for tasks
if ( ! tasks ) {
return new Error('No tasks found');
}
// Variables
let jobs = [];
// Extract jobs from tasks
tasks.forEach((t) => { t.jobs.forEach((j, i) => { jobs.push(j); }); });
// Add jobs into queue and convert
return queue.add({jobs: jobs});
// Conversion queue complete
}).then((complete) => {
logger.info('Completed available tasks');
// Error handler
}).catch((err) => {
logger.error(err);
});
};
|
'use strict';
// Load our modules
const logger = __require('libs/log'),
task = __require('libs/task'),
queue = __require('libs/queue');
// General task file handling
module.exports = function(options) {
// Does the user want to run this?
if ( options.no_task ) {
return;
}
// Variables
let count = 0;
// Load tasks from file
task.load('tasks.json').then((tasks) => {
// Check for tasks
if ( ! tasks ) {
return new Error('No tasks found');
}
// Variables
let jobs = [];
// Extract jobs from tasks
tasks.forEach((t) => { t.jobs.forEach((j, i) => { jobs.push(j); }); });
// Update count
count = jobs.length;
// Add jobs into queue and convert
return queue.add({jobs: jobs});
// Conversion queue complete
}).then((complete) => {
logger.info('Completed %s tasks', count);
// Error handler
}).catch((err) => {
logger.error(err);
});
};
|
Debug and quiet have short keys.
|
#!/usr/bin/env node
'use strict';
/**
* Binary to run a pg server.
* (C) 2015 Alex Fernández.
*/
// requires
var Log = require('log');
var stdio = require('stdio');
var server = require('../lib/server.js');
var packageJson = require(__dirname + '/../package.json');
// globals
var log = new Log('info');
// constants
var PORT = 5433;
// init
var options = stdio.getopt({
version: {key: 'v', description: 'Display version and quit'},
port: {key: 'p', args: 1, description: 'Port to connect to', default: PORT},
host: {key: 'h', args: 1, description: 'Host to connect to'},
quiet: {key: 'q', description: 'Do not log any messages'},
debug: {key: 'd', description: 'Show debug messages'},
});
if (options.version)
{
console.log('Loadtest version: %s', packageJson.version);
process.exit(0);
}
if (options.args && options.args.length > 0)
{
console.error('Too many arguments: %s', options.args);
options.printHelp();
process.exit(1);
}
server.start(options, function(error)
{
if (error)
{
return console.error('Could not start server on port %s: %s', options.port, error);
}
log.info('Pooled PostgreSQL server started on port %s', options.port);
});
|
#!/usr/bin/env node
'use strict';
/**
* Binary to run a pg server.
* (C) 2015 Alex Fernández.
*/
// requires
var stdio = require('stdio');
var server = require('../lib/server.js');
var packageJson = require(__dirname + '/../package.json');
// constants
var PORT = 5433;
// init
var options = stdio.getopt({
version: {key: 'v', description: 'Display version and quit'},
port: {key: 'p', args: 1, description: 'Port to connect to', default: PORT},
host: {key: 'h', args: 1, description: 'Host to connect to'},
quiet: {description: 'Do not log any messages'},
debug: {description: 'Show debug messages'},
});
if (options.version)
{
console.log('Loadtest version: %s', packageJson.version);
process.exit(0);
}
if (options.args && options.args.length > 0)
{
console.error('Too many arguments: %s', options.args);
options.printHelp();
process.exit(1);
}
server.start(options, function(error)
{
if (error)
{
return console.error('Could not start server on port %s: %s', options.port, error);
}
console.log('Pooled PostgreSQL server started on port %s', options.port);
});
|
Add completion for miscellaneous flags.
|
#!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var tab = require('tabalot');
var noop = function() {}
var homedir = path.resolve(process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'], '.grunt-init');
if (process.argv.indexOf('completion') !== -1 && process.argv.indexOf('--') === -1) {
process.argv.push('--bin');
process.argv.push('grunt-init');
process.argv.push('--completion');
process.argv.push('grunt-init-completion');
}
tab()
('--help', '-h')
('--no-color')
('--debug', '-d')
('--stack')
('--force', '-f')
('--no-write')
('--verbose', '-v')
('--version', '-V')
fs.readdir(path.join(homedir), function(err, files) {
if (err) process.exit(2);
files = files.filter(function(file) {
return fs.statSync(path.join(homedir, file)).isDirectory();
});
files.forEach(function(file) {
tab(file)(noop);
});
tab.parse();
});
|
#!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var tab = require('tabalot');
var noop = function() {}
var homedir = path.resolve(process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'], '.grunt-init');
if (process.argv.indexOf('completion') !== -1 && process.argv.indexOf('--') === -1) {
process.argv.push('--bin');
process.argv.push('grunt-init');
process.argv.push('--completion');
process.argv.push('grunt-init-completion');
}
fs.readdir(path.join(homedir), function(err, files) {
if (err) process.exit(2);
files = files.filter(function(file) {
return fs.statSync(path.join(homedir, file)).isDirectory();
});
files.forEach(function(file) {
tab(file)(noop);
});
tab.parse();
});
|
Remove --dev from composer install.
--dev is the default.
|
#!/usr/bin/env php
<?php
chdir(__DIR__);
$returnStatus = null;
passthru('composer install', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
require 'vendor/autoload.php';
$phpcsCLI = new PHP_CodeSniffer_CLI();
$phpcsArguments = array(
'standard' => array(__DIR__ . '/vendor/dominionenterprises/dws-coding-standard/DWS'),
'files' => array('src', 'tests', 'build.php'),
'warningSeverity' => 0,
);
$phpcsViolations = $phpcsCLI->process($phpcsArguments);
if ($phpcsViolations > 0) {
exit(1);
}
$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration);
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
exit(1);
}
$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
exit(1);
}
echo "Code coverage was 100%\n";
|
#!/usr/bin/env php
<?php
chdir(__DIR__);
$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
require 'vendor/autoload.php';
$phpcsCLI = new PHP_CodeSniffer_CLI();
$phpcsArguments = array(
'standard' => array(__DIR__ . '/vendor/dominionenterprises/dws-coding-standard/DWS'),
'files' => array('src', 'tests', 'build.php'),
'warningSeverity' => 0,
);
$phpcsViolations = $phpcsCLI->process($phpcsArguments);
if ($phpcsViolations > 0) {
exit(1);
}
$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration);
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
exit(1);
}
$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
exit(1);
}
echo "Code coverage was 100%\n";
|
Update format of the timestamp properties in the reaction response
|
<?php
namespace Rogue\Http\Transformers;
use Rogue\Models\Reaction;
use League\Fractal\TransformerAbstract;
class ReactionTransformer extends TransformerAbstract
{
/**
* Transform the resource data.
*
* @param \Rogue\Models\Reaction $reaction
* @return array
*/
public function transform(Reaction $reaction)
{
return [
'northstar_id' => $reaction->northstar_id,
'post_id' => (string) $reaction->post_id,
'created_at' => $reaction->created_at->toIso8601String(),
'updated_at' => $reaction->updated_at->toIso8601String(),
'deleted_at' => is_null($reaction->deleted_at) ? null : $reaction->deleted_at->toIso8601String(),
];
}
}
|
<?php
namespace Rogue\Http\Transformers;
use Rogue\Models\Reaction;
use League\Fractal\TransformerAbstract;
class ReactionTransformer extends TransformerAbstract
{
/**
* Transform the resource data.
*
* @param \Rogue\Models\Reaction $reaction
* @return array
*/
public function transform(Reaction $reaction)
{
return [
'northstar_id' => $reaction->northstar_id,
'post_id' => (string) $reaction->post_id,
'created_at' => $reaction->created_at,
'updated_at' => $reaction->updated_at,
'deleted_at' => $reaction->deleted_at,
];
}
}
|
Fix for calling super during exception logging
|
# -*- coding: utf-8 -*-
"""
Provides a custom unit test base class which will log to sentry.
:copyright: (c) 2010 by Tim Sutton
:license: GPLv3, see LICENSE for more details.
"""
import unittest
import logging
from reporter import setup_logger
setup_logger()
LOGGER = logging.getLogger('osm-reporter')
class LoggedTestCase(unittest.TestCase):
"""A test class that logs to sentry on failure."""
def failureException(self, msg):
"""Overloaded failure exception that will log to sentry.
:param msg: String containing a message for the log entry.
:type msg: str
:returns: delegates to TestCase and returns the exception generated
by it.
:rtype: Exception
See unittest.TestCase to see what gets raised.
"""
LOGGER.exception(msg)
return super(LoggedTestCase, self).failureException(msg)
|
# -*- coding: utf-8 -*-
"""
Provides a custom unit test base class which will log to sentry.
:copyright: (c) 2010 by Tim Sutton
:license: GPLv3, see LICENSE for more details.
"""
import unittest
import logging
from reporter import setup_logger
setup_logger()
LOGGER = logging.getLogger('osm-reporter')
class LoggedTestCase(unittest.TestCase):
"""A test class that logs to sentry on failure."""
def failureException(self, msg):
"""Overloaded failure exception that will log to sentry.
Args:
msg: str - a string containing a message for the log entry.
Returns:
delegates to TestCase and returns the exception generated by it.
Raises:
see unittest.TestCase
"""
LOGGER.exception(msg)
return self.super(LoggedTestCase, self).failureException(msg)
|
Update French Translation for Media modules
|
<?php
return [
'title' => [
'media' => 'Média',
'edit media' => 'Edition de média',
],
'breadcrumb' => [
'media' => 'Média',
],
'table' => [
'filename' => 'Nom de fichier',
'width' => 'Largeur',
'height' => 'Hauteur',
],
'form' => [
'alt_attribute' => 'Attribut alt',
'description' => 'Description',
'keywords' => 'Mots clés',
],
'validation' => [
'max_size' => 'Taille maximale (:size) du dossier Media atteint.',
],
'file-sizes' => [
'B' => 'Octet',
'KB' => 'Ko',
'MB' => 'Mo',
'GB' => 'Go',
'TB' => 'To',
],
'choose file' => 'Choissisez un fichier',
'insert' => 'Sélectionner ce fichier',
'file picker' => 'Sélectionneur de fichier',
'Browse' => 'Parcourir ...',
];
|
<?php
return [
'title' => [
'media' => 'Média',
'edit media' => 'Edition de média',
],
'breadcrumb' => [
'media' => 'Média',
],
'table' => [
'filename' => 'Nom de fichier',
'width' => 'Largeur',
'height' => 'Hauteur',
],
'validation' => [
'max_size' => 'Taille maximale (:size) du dossier Media atteint.',
],
'file-sizes' => [
'B' => 'Octet',
'KB' => 'Ko',
'MB' => 'Mo',
'GB' => 'Go',
'TB' => 'To',
],
'choose file' => 'Choissisez un fichier',
'insert' => 'Sélectionner ce fichier',
'file picker' => 'Sélectionneur de fichier',
'Browse' => 'Parcourir ...',
];
|
Fix deprecation and removal date
|
<?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
namespace Flarum\Event;
use Flarum\User\User;
/**
* @deprecated beta 14, remove in beta 15. Use the User extender instead.
* The `PrepareUserGroups` event.
*/
class PrepareUserGroups
{
/**
* @var User
*/
public $user;
/**
* @var array
*/
public $groupIds;
/**
* @param User $user
* @param array $groupIds
*/
public function __construct(User $user, array &$groupIds)
{
$this->user = $user;
$this->groupIds = &$groupIds;
}
}
|
<?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
namespace Flarum\Event;
use Flarum\User\User;
/**
* @deprecated beta 13, remove in beta 14. Use the User extender instead.
* The `PrepareUserGroups` event.
*/
class PrepareUserGroups
{
/**
* @var User
*/
public $user;
/**
* @var array
*/
public $groupIds;
/**
* @param User $user
* @param array $groupIds
*/
public function __construct(User $user, array &$groupIds)
{
$this->user = $user;
$this->groupIds = &$groupIds;
}
}
|
Fix the case when hashtag parser getting not a string
|
import _ from 'lodash';
import URLFinder from 'ff-url-finder';
const finder = new URLFinder();
finder.withHashTags = true;
/**
* Extract all hashtags with their start and end indices
* from the given text
* @param {string} text
* @return {{hashtag: string, indices: number[]}[]}
*/
export function extractHashtagsWithIndices(text) {
if (typeof text !== 'string' || text === '') {
return [];
}
const parsed = finder.parse(text);
const hashtags = [];
let pos = 0;
for (const p of parsed) {
if (p.type === 'hashtag') {
hashtags.push({
hashtag: p.hashTag,
indices: [pos + 1, pos + p.text.length],
});
}
pos += p.text.length
}
return hashtags;
}
/**
* Extract all hashtags as strings from the given text
* @param {string} text
* @return {string[]}
*/
export function extractHashtags(text) {
const hashtags = extractHashtagsWithIndices(text);
return _.map(hashtags, 'hashtag');
}
|
import _ from 'lodash';
import URLFinder from 'ff-url-finder';
const finder = new URLFinder();
finder.withHashTags = true;
/**
* Extract all hashtags with their start and end indices
* from the given text
* @param {string} text
* @return {{hashtag: string, indices: number[]}[]}
*/
export function extractHashtagsWithIndices(text) {
const parsed = finder.parse(text);
const hashtags = [];
let pos = 0;
for (const p of parsed) {
if (p.type === 'hashtag') {
hashtags.push({
hashtag: p.hashTag,
indices: [pos + 1, pos + p.text.length],
});
}
pos += p.text.length
}
return hashtags;
}
/**
* Extract all hashtags as strings from the given text
* @param {string} text
* @return {string[]}
*/
export function extractHashtags(text) {
const hashtags = extractHashtagsWithIndices(text);
return _.map(hashtags, 'hashtag');
}
|
Update nav background-color change from 50px to 110px trigger
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
$(function() {
$(window).on("scroll", function() {
if($(window).scrollTop() > 110) {
$("#nav").addClass("active");
} else {
//remove the background property so it comes transparent again (defined in your css)
$("#nav").removeClass("active");
}
});
});
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
$(function() {
$(window).on("scroll", function() {
if($(window).scrollTop() > 50) {
$("#nav").addClass("active");
} else {
//remove the background property so it comes transparent again (defined in your css)
$("#nav").removeClass("active");
}
});
});
|
Fix bug in like validator
|
def is_quick_button(messaging_event):
if 'message' not in messaging_event:
return False
if 'quick_reply' not in messaging_event['message']:
return False
return True
def is_talk_ask_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'ask talk' in messaging_event['postback']['payload']
def is_talk_info_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'info talk' in messaging_event['postback']['payload']
def is_talk_rate_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'rate talk' in messaging_event['postback']['payload']
def is_talk_like_command(messaging_event):
if not is_quick_button(messaging_event):
return False
return 'like talk' in messaging_event['message']['quick_reply']['payload']
def has_sender_id(messaging_event):
return 'sender' in messaging_event and 'id' in messaging_event['sender']
|
def is_quick_button(messaging_event):
if 'message' not in messaging_event:
return False
if 'quick_reply' not in messaging_event['message']:
return False
return True
def is_talk_ask_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'ask talk' in messaging_event['postback']['payload']
def is_talk_info_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'info talk' in messaging_event['postback']['payload']
def is_talk_rate_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'rate talk' in messaging_event['postback']['payload']
def is_talk_like_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'like talk' in messaging_event['postback']['payload']
def has_sender_id(messaging_event):
return 'sender' in messaging_event and 'id' in messaging_event['sender']
|
Remove outdated Python 3.4 classifier.
|
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
setup(
name='django-session-cleanup',
version='2.0.0',
description=('A periodic task for removing expired Django sessions '
'with Celery.'),
long_description=readme,
author='Elijah Rutschman',
author_email='elijahr+django-session-cleanup@gmail.com',
maintainer='Martey Dodoo',
maintainer_email='martey+django-session-cleanup@mobolic.com',
url='https://github.com/mobolic/django-session-cleanup',
classifiers=[
'Framework :: Django :: 1.11',
'Framework :: Django :: 2.0',
'Framework :: Django :: 2.1',
'Framework :: Django :: 2.2',
'Framework :: Django :: 3.0',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
packages=find_packages(exclude=('tests',))
)
|
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
setup(
name='django-session-cleanup',
version='2.0.0',
description=('A periodic task for removing expired Django sessions '
'with Celery.'),
long_description=readme,
author='Elijah Rutschman',
author_email='elijahr+django-session-cleanup@gmail.com',
maintainer='Martey Dodoo',
maintainer_email='martey+django-session-cleanup@mobolic.com',
url='https://github.com/mobolic/django-session-cleanup',
classifiers=[
'Framework :: Django :: 1.11',
'Framework :: Django :: 2.0',
'Framework :: Django :: 2.1',
'Framework :: Django :: 2.2',
'Framework :: Django :: 3.0',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
packages=find_packages(exclude=('tests',))
)
|
Fix class name of test.
|
import unittest2
from google.appengine.ext import testbed
from models.account import Account
from models.suggestion import Suggestion
from helpers.suggestions.suggestion_fetcher import SuggestionFetcher
class TestSuggestionFetcher(unittest2.TestCase):
def setUp(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_datastore_v3_stub()
self.testbed.init_memcache_stub()
account = Account.get_or_insert(
"123",
email="user@example.com",
registered=True).put()
suggestion = Suggestion(
author=account,
review_state=Suggestion.REVIEW_PENDING,
target_key="2012cmp",
target_model="event").put()
def testCount(self):
self.assertEqual(SuggestionFetcher.count(Suggestion.REVIEW_PENDING, "event"), 1)
self.assertEqual(SuggestionFetcher.count(Suggestion.REVIEW_PENDING, "media"), 0)
|
import unittest2
from google.appengine.ext import testbed
from models.account import Account
from models.suggestion import Suggestion
from helpers.suggestions.suggestion_fetcher import SuggestionFetcher
class TestEventTeamRepairer(unittest2.TestCase):
def setUp(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_datastore_v3_stub()
self.testbed.init_memcache_stub()
account = Account.get_or_insert(
"123",
email="user@example.com",
registered=True).put()
suggestion = Suggestion(
author=account,
review_state=Suggestion.REVIEW_PENDING,
target_key="2012cmp",
target_model="event").put()
def testCount(self):
self.assertEqual(SuggestionFetcher.count(Suggestion.REVIEW_PENDING, "event"), 1)
self.assertEqual(SuggestionFetcher.count(Suggestion.REVIEW_PENDING, "media"), 0)
|
Add a test for default config settings.
|
import os
import stat
from nose.tools import *
from lctools import config
class TestConfig(object):
test_filename = "bebebe"
def setup(self):
fd = open(self.test_filename, 'w')
fd.write("[default]\n")
fd.write("foo = bar\n")
fd.close()
os.chmod(self.test_filename, stat.S_IRUSR)
def test_basic_functionality(self):
config.LC_CONFIG = self.test_filename
conf = config.get_config("default")
assert_true("default" in conf.sections())
assert_equal(conf.get("foo"), "bar")
@raises(RuntimeError)
def test_get_config_permission_checks(self):
os.chmod(self.test_filename, stat.S_IRWXG | stat.S_IRWXO)
config.LC_CONFIG = self.test_filename
config.get_config("default")
def test_defaults(self):
config.LC_CONFIG = self.test_filename
conf = config.get_config("default")
print conf.get("verify_ssl_certs")
def teardown(self):
os.unlink(self.test_filename)
|
import os
import stat
from nose.tools import *
from lctools import config
class TestConfig(object):
test_filename = "bebebe"
def setup(self):
fd = open(self.test_filename, 'w')
fd.write("[default]\n")
fd.write("foo = bar\n")
fd.close()
os.chmod(self.test_filename, stat.S_IRUSR)
def test_basic_functionality(self):
config.LC_CONFIG = self.test_filename
conf = config.get_config("default")
assert_true("default" in conf.sections())
assert_equal(conf.get("foo"), "bar")
@raises(RuntimeError)
def test_get_config_permission_checks(self):
os.chmod(self.test_filename, stat.S_IRWXG | stat.S_IRWXO)
config.LC_CONFIG = self.test_filename
config.get_config("default")
def teardown(self):
os.unlink(self.test_filename)
|
Fix boolean conversion of StackedObjectProxy in Python 3
|
from paste.registry import StackedObjectProxy as PasteSOP
class StackedObjectProxy(PasteSOP):
# override b/c of
# http://trac.pythonpaste.org/pythonpaste/ticket/482
def _pop_object(self, obj=None):
"""Remove a thread-local object.
If ``obj`` is given, it is checked against the popped object and an
error is emitted if they don't match.
"""
try:
popped = self.____local__.objects.pop()
if obj is not None and popped is not obj:
raise AssertionError(
'The object popped (%s) is not the same as the object '
'expected (%s)' % (popped, obj))
except AttributeError:
raise AssertionError('No object has been registered for this thread')
def __bool__(self):
return bool(self._current_obj())
|
from paste.registry import StackedObjectProxy as PasteSOP
class StackedObjectProxy(PasteSOP):
# override b/c of
# http://trac.pythonpaste.org/pythonpaste/ticket/482
def _pop_object(self, obj=None):
"""Remove a thread-local object.
If ``obj`` is given, it is checked against the popped object and an
error is emitted if they don't match.
"""
try:
popped = self.____local__.objects.pop()
if obj is not None and popped is not obj:
raise AssertionError(
'The object popped (%s) is not the same as the object '
'expected (%s)' % (popped, obj))
except AttributeError:
raise AssertionError('No object has been registered for this thread')
|
Clear unnecessary code, add comments on sorting
|
#!/dls_sw/prod/tools/RHEL6-x86_64/defaults/bin/dls-python
from utilities import get_pv_names, write_pvs_to_file
import argparse
parser = argparse.ArgumentParser('optional named arguments')
parser.add_argument("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE", default = 'test.txt')
requiredArgv = parser.add_argument_group('required arguments')
requiredArgv.add_argument("-m", "--mode", dest="mode",
help="Machine MODE to use", metavar="MODE", required = True)
argv = parser.parse_args()
mode_pvs = get_pv_names(argv.mode)
# File appears to be already sorted, so no need for next line
# sorted(mode_pvs)
write_pvs_to_file(argv.filename, mode_pvs)
|
#!/dls_sw/prod/tools/RHEL6-x86_64/defaults/bin/dls-python
from utilities import get_pv_names, write_pvs_to_file
import argparse
parser = argparse.ArgumentParser('optional named arguments')
parser.add_argument("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE", default = 'test.txt')
requiredArgv = parser.add_argument_group('required arguments')
requiredArgv.add_argument("-m", "--mode", dest="mode",
help="Machine MODE to use", metavar="MODE", required = True)
argv = parser.parse_args()
mode_pvs = get_pv_names(argv.mode)
write_pvs_to_file(argv.filename, mode_pvs)
print argv.filename
|
Fix issue with config file not loading correctly
|
/*
* Copyright 2015 The ISTLab. Use of this source code is governed by a GNU AFFERO GPL 3.0 license
* that can be found in the LICENSE file.
*/
package gr.aueb.dmst.istlab.unixtools.plugin;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
import gr.aueb.dmst.istlab.unixtools.util.LoggerUtil;
import gr.aueb.dmst.istlab.unixtools.util.PropertiesLoader;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractUIPlugin {
/** The plug-in ID */
public static final String PLUGIN_ID = "gr.aueb.dmst.istlab.unixtools.plugin";
/** The shared instance */
private static Activator plugin;
public Activator() {}
@Override
public void start(BundleContext context) throws Exception {
// load plugin's properties
super.start(context);
plugin = this;
LoggerUtil.configureLogger();
PropertiesLoader.loadPropertiesFile();
}
@Override
public void stop(BundleContext context) throws Exception {
plugin = null;
// close properties file
PropertiesLoader.closePropertiesFile();
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
}
|
/*
* Copyright 2015 The ISTLab. Use of this source code is governed by a GNU AFFERO GPL 3.0 license
* that can be found in the LICENSE file.
*/
package gr.aueb.dmst.istlab.unixtools.plugin;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
import gr.aueb.dmst.istlab.unixtools.util.PropertiesLoader;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractUIPlugin {
/** The plug-in ID */
public static final String PLUGIN_ID = "gr.aueb.dmst.istlab.unixtools.plugin";
/** The shared instance */
private static Activator plugin;
public Activator() {}
@Override
public void start(BundleContext context) throws Exception {
// load plugin's properties
PropertiesLoader.loadPropertiesFile();
super.start(context);
plugin = this;
}
@Override
public void stop(BundleContext context) throws Exception {
plugin = null;
// close properties file
PropertiesLoader.closePropertiesFile();
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
}
|
Add a method to regenerate a token
|
import random
import re
from django.contrib.auth.models import User
from django.db import models
from instances.models import InstanceMixin
NUMBER_OF_TOKEN_WORDS = 3
def generate_token():
def useful_word(w):
# FIXME: should try to exclude offensive words
if len(w) < 4:
return False
if re.search('^[a-z]*$', w):
return True
words = []
with open('/usr/share/dict/words') as fp:
for line in fp:
word = line.strip()
if useful_word(word):
words.append(word)
return " ".join(random.choice(words)
for i in range(NUMBER_OF_TOKEN_WORDS))
class LoginToken(InstanceMixin, models.Model):
'''Represents a readable login token for mobile devices
To enable logging in to a SayIt instance as a particular user, we
ask the user to type in a three word phrase; this model records
tokens that allow login for a particular instance by a particular
user.'''
user = models.ForeignKey(User)
token = models.TextField(max_length=255,
default=generate_token)
def regenerate_token(self):
token = generate_token()
token.save()
|
import random
import re
from django.contrib.auth.models import User
from django.db import models
from instances.models import InstanceMixin
NUMBER_OF_TOKEN_WORDS = 3
def generate_token():
def useful_word(w):
# FIXME: should try to exclude offensive words
if len(w) < 4:
return False
if re.search('^[a-z]*$', w):
return True
words = []
with open('/usr/share/dict/words') as fp:
for line in fp:
word = line.strip()
if useful_word(word):
words.append(word)
return " ".join(random.choice(words)
for i in range(NUMBER_OF_TOKEN_WORDS))
class LoginToken(InstanceMixin, models.Model):
'''Represents a readable login token for mobile devices
To enable logging in to a SayIt instance as a particular user, we
ask the user to type in a three word phrase; this model records
tokens that allow login for a particular instance by a particular
user.'''
user = models.ForeignKey(User)
token = models.TextField(max_length=255,
default=generate_token)
|
Configure a simple index page
For now, this is a place-holder.
|
"""Memoir URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from django.http import HttpResponse
urlpatterns = [
url(r'^$', lambda request: HttpResponse('<h1>Memoir</h1>'), name = 'index'),
url(r'^admin/', admin.site.urls),
]
|
"""Memoir URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
]
|
Make sure to keep certain report fields out of resources
|
from scrapi.processing.osf import crud
from scrapi.processing.osf import collision
from scrapi.processing.base import BaseProcessor
class OSFProcessor(BaseProcessor):
NAME = 'osf'
def process_normalized(self, raw_doc, normalized):
if crud.is_event(normalized):
crud.create_event(normalized)
return
normalized['collisionCategory'] = crud.get_collision_cat(normalized['source'])
report_norm = normalized
resource_norm = crud.clean_report(normalized)
report_hash = collision.generate_report_hash_list(report_norm)
resource_hash = collision.generate_resource_hash_list(resource_norm)
report = collision.detect_collisions(report_hash)
resource = collision.detect_collisions(resource_hash)
if not resource:
resource = crud.create_resource(resource_norm, resource_hash)
elif not crud.is_claimed(resource):
crud.update_resource(resource_norm, resource)
if not report:
crud.create_report(report_norm, resource, report_hash)
else:
crud.update_report(report_norm, report)
|
from scrapi.processing.osf import crud
from scrapi.processing.osf import collision
from scrapi.processing.base import BaseProcessor
class OSFProcessor(BaseProcessor):
NAME = 'osf'
def process_normalized(self, raw_doc, normalized):
if crud.is_event(normalized):
crud.create_event(normalized)
return
report_hash = collision.generate_report_hash_list(normalized)
resource_hash = collision.generate_resource_hash_list(normalized)
report = collision.detect_collisions(report_hash)
resource = collision.detect_collisions(resource_hash)
if not resource:
resource = crud.create_resource(normalized, resource_hash)
elif not crud.is_claimed(resource):
crud.update_resource(normalized, resource)
if not report:
crud.create_report(normalized, resource, report_hash)
else:
crud.update_report(normalized, report)
|
Change the ToggleButton helpers test to ToggleButton:Helpers
|
import { expect } from 'chai';
import { isButtonSelected } from '../helpers.js';
describe('ToggleButton:Helpers', () => {
describe('isButtonSelected', () => {
it('should return false when the value or the candidate is null', () => {
expect(isButtonSelected(null, 'xyz')).be.false;
expect(isButtonSelected([], null)).be.false;
});
it('should return true when the candidate is equal to the value', () => {
expect(isButtonSelected('test', 'test')).be.true;
});
it('should return false when the candidate is not equal to the value', () => {
expect(isButtonSelected('test', 'tesy')).be.false;
});
it('should return true when the value is an array and contains the candidate', () => {
expect(isButtonSelected(['test-1', 'test-2'], 'test-1')).be.true;
});
it('should return false when the value is an array and does not contain the candidate', () => {
expect(isButtonSelected(['test-1', 'test-2'], 'test-3')).be.false;
});
});
});
|
import { expect } from 'chai';
import { isButtonSelected } from '../helpers.js';
describe('isButtonSelected', () => {
it('should return false when the value or the candidate is null', () => {
expect(isButtonSelected(null, 'xyz')).be.false;
expect(isButtonSelected([], null)).be.false;
});
it('should return true when the candidate is equal to the value', () => {
expect(isButtonSelected('test', 'test')).be.true;
});
it('should return false when the candidate is not equal to the value', () => {
expect(isButtonSelected('test', 'tesy')).be.false;
});
it('should return true when the value is an array and contains the candidate', () => {
expect(isButtonSelected(['test-1', 'test-2'], 'test-1')).be.true;
});
it('should return false when the value is an array and does not contain the candidate', () => {
expect(isButtonSelected(['test-1', 'test-2'], 'test-3')).be.false;
});
});
|
Fix server side error on navigator object
|
export function getInterfaceLanguage() {
const defaultLang = 'en-US';
// Check if it's running on server side
if (typeof window === 'undefined') {
return defaultLang;
}
if (!!navigator && !!navigator.language) {
return navigator.language;
} else if (!!navigator && !!navigator.languages && !!navigator.languages[0]) {
return navigator.languages[0];
} else if (!!navigator && !!navigator.userLanguage) {
return navigator.userLanguage;
} else if (!!navigator && !!navigator.browserLanguage) {
return navigator.browserLanguage;
}
return defaultLang;
}
export function validateTranslationKeys(translationKeys) {
const reservedNames = [
'_interfaceLanguage',
'_language',
'_defaultLanguage',
'_defaultLanguageFirstLevelKeys',
'_props',
];
translationKeys.forEach(key => {
if (reservedNames.indexOf(key) !== -1) {
throw new Error(`${key} cannot be used as a key. It is a reserved word.`);
}
});
}
|
export function getInterfaceLanguage() {
if (!!navigator && !!navigator.language) {
return navigator.language;
} else if (!!navigator && !!navigator.languages && !!navigator.languages[0]) {
return navigator.languages[0];
} else if (!!navigator && !!navigator.userLanguage) {
return navigator.userLanguage;
} else if (!!navigator && !!navigator.browserLanguage) {
return navigator.browserLanguage;
}
return 'en-US';
}
export function validateTranslationKeys(translationKeys) {
const reservedNames = [
'_interfaceLanguage',
'_language',
'_defaultLanguage',
'_defaultLanguageFirstLevelKeys',
'_props',
];
translationKeys.forEach(key => {
if (reservedNames.indexOf(key) !== -1) {
throw new Error(`${key} cannot be used as a key. It is a reserved word.`);
}
});
}
|
[FIX] Update test url for gls web api v1
|
"""Implementation for Laposte."""
from roulier.carrier_action import CarrierGetLabel
from roulier.roulier import factory
from .api import GlsEuApiParcel
from .encoder import GlsEuEncoder
from .decoder import GlsEuDecoderGetLabel
from .transport import GlsEuTransport
class GlsEuGetabel(CarrierGetLabel):
"""Implementation for GLS via it's REST WebService."""
ws_url = "https://api.gls-group.eu/public/v1/shipments"
ws_test_url = "https://api-qs1.gls-group.eu/public/v1/shipments"
encoder = GlsEuEncoder
decoder = GlsEuDecoderGetLabel
transport = GlsEuTransport
api = GlsEuApiParcel
manage_multi_label = True
factory.register_builder("gls_fr_rest", "get_label", GlsEuGetabel)
|
"""Implementation for Laposte."""
from roulier.carrier_action import CarrierGetLabel
from roulier.roulier import factory
from .api import GlsEuApiParcel
from .encoder import GlsEuEncoder
from .decoder import GlsEuDecoderGetLabel
from .transport import GlsEuTransport
class GlsEuGetabel(CarrierGetLabel):
"""Implementation for GLS via it's REST WebService."""
ws_url = "https://api.gls-group.eu/public/v1/shipments"
ws_test_url = "https://api-qs.gls-group.eu/public/v1/shipments"
encoder = GlsEuEncoder
decoder = GlsEuDecoderGetLabel
transport = GlsEuTransport
api = GlsEuApiParcel
manage_multi_label = True
factory.register_builder("gls_fr_rest", "get_label", GlsEuGetabel)
|
Use `application/x-bat` MIME type for .bat extension
Fixes #121.
|
"use strict";
/**
MIME type definitions consisting of those in `mime-db` plus custom additions and
overrides.
See <https://github.com/jshttp/mime-db> for details on the format.
**/
const db = require('mime-db');
// If you add a new type here, make sure its extensions are also in the
// extension whitelist in ./index.js or RawGit won't proxy requests for that
// type. Please keep definitions in alphabetical order.
db['application/n-triples'] = {
charset : 'utf-8',
compressible: true,
extensions : ['nt']
};
db['application/rdf+xml'] = {
compressible: true,
extensions : ['rdf', 'owl']
};
db['application/vnd.geo+json'] = {
charset : 'utf-8',
compressible: true,
extensions : ['geojson']
};
db['application/x-bat'] = {
charset : 'utf-8',
compressible: true,
extensions : ['bat']
};
db['text/x-handlebars-template'] = {
charset : 'utf-8',
compressible: true,
extensions : ['handlebars', 'hbs']
};
module.exports = db;
|
"use strict";
/**
MIME type definitions consisting of those in `mime-db` plus custom additions and
overrides.
See <https://github.com/jshttp/mime-db> for details on the format.
**/
const db = require('mime-db');
// If you add a new type here, make sure its extensions are also in the
// extension whitelist in ./index.js or RawGit won't proxy requests for that
// type. Please keep definitions in alphabetical order.
db['application/n-triples'] = {
charset : 'utf-8',
compressible: true,
extensions : ['nt']
};
db['application/rdf+xml'] = {
compressible: true,
extensions : ['rdf', 'owl']
};
db['application/vnd.geo+json'] = {
charset : 'utf-8',
compressible: true,
extensions : ['geojson']
};
db['text/x-handlebars-template'] = {
charset : 'utf-8',
compressible: true,
extensions : ['handlebars', 'hbs']
};
module.exports = db;
|
Add QOS_SIZE setting to allow ack messages being removed from queue as fatch size is set to 1
|
<?php
/**
* mbc-transactional-digest
*
* Collect transactional campaign sign up message requests in a certain time period and
* compose a single digest message request.
*/
date_default_timezone_set('America/New_York');
define('CONFIG_PATH', __DIR__ . '/messagebroker-config');
define('QOS_SIZE', 1);
// Load up the Composer autoload magic
require_once __DIR__ . '/vendor/autoload.php';
use DoSomething\ MBC_TransactionalDigest\MBC_TransactionalDigest_Consumer;
// Load configuration settings specific to this application
require_once __DIR__ . '/mbc-transactional-digest.config.inc';
// Kick off
echo '------- mbc-transactional-digest START - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;
$mb = $mbConfig->getProperty('messageBroker_transactionalDigest');
$mb->consumeMessage([new MBC_TransactionalDigest_Consumer('messageBroker_transactionalDigest'), 'consumeQueue'], QOS_SIZE);
echo '------- mbc-transactional-digest END - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;
|
<?php
/**
* mbc-transactional-digest
*
* Collect transactional campaign sign up message requests in a certain time period and
* compose a single digest message request.
*/
date_default_timezone_set('America/New_York');
define('CONFIG_PATH', __DIR__ . '/messagebroker-config');
// Load up the Composer autoload magic
require_once __DIR__ . '/vendor/autoload.php';
use DoSomething\ MBC_TransactionalDigest\MBC_TransactionalDigest_Consumer;
// Load configuration settings specific to this application
require_once __DIR__ . '/mbc-transactional-digest.config.inc';
// Kick off
echo '------- mbc-transactional-digest START - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;
$mb = $mbConfig->getProperty('messageBroker_transactionalDigest');
$mb->consumeMessage(array(new MBC_TransactionalDigest_Consumer('messageBroker_transactionalDigest'), 'consumeQueue'));
echo '------- mbc-transactional-digest END - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;
|
Remove the unnecessary capturing group.
|
# -*- coding: utf-8 -*-
import re
from . import export
@export
def fuzzyfinder(text, collection):
"""
Args:
text (str): A partial string which is typically entered by a user.
collection (iterable): A collection of strings which will be filtered
based on the input `text`.
Returns:
suggestions (generator): A generator object that produces a list of
suggestions narrowed down from `collections` using the `text`
input.
"""
suggestions = []
regex = '.*?'.join(map(re.escape, text))
pat = re.compile('%s' % regex)
for item in sorted(collection):
r = pat.search(item)
if r:
suggestions.append((len(r.group()), r.start(), item))
return (z for _, _, z in sorted(suggestions))
|
# -*- coding: utf-8 -*-
import re
from . import export
@export
def fuzzyfinder(text, collection):
"""
Args:
text (str): A partial string which is typically entered by a user.
collection (iterable): A collection of strings which will be filtered
based on the input `text`.
Returns:
suggestions (generator): A generator object that produces a list of
suggestions narrowed down from `collections` using the `text`
input.
"""
suggestions = []
regex = '.*?'.join(map(re.escape, text))
pat = re.compile('(%s)' % regex)
for item in sorted(collection):
r = pat.search(item)
if r:
suggestions.append((len(r.group()), r.start(), item))
return (z for _, _, z in sorted(suggestions))
|
Use AWS ARN structure - aws_billing_service_account data source.
|
package aws
import (
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/hashicorp/terraform/helper/schema"
)
// See http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-getting-started.html#step-2
var billingAccountId = "386209384616"
func dataSourceAwsBillingServiceAccount() *schema.Resource {
return &schema.Resource{
Read: dataSourceAwsBillingServiceAccountRead,
Schema: map[string]*schema.Schema{
"arn": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAwsBillingServiceAccountRead(d *schema.ResourceData, meta interface{}) error {
d.SetId(billingAccountId)
arn := arn.ARN{
Partition: meta.(*AWSClient).partition,
Service: "iam",
AccountID: billingAccountId,
Resource: "root",
}
d.Set("arn", arn.String())
return nil
}
|
package aws
import (
"fmt"
"github.com/hashicorp/terraform/helper/schema"
)
// See http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-getting-started.html#step-2
var billingAccountId = "386209384616"
func dataSourceAwsBillingServiceAccount() *schema.Resource {
return &schema.Resource{
Read: dataSourceAwsBillingServiceAccountRead,
Schema: map[string]*schema.Schema{
"arn": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceAwsBillingServiceAccountRead(d *schema.ResourceData, meta interface{}) error {
d.SetId(billingAccountId)
d.Set("arn", fmt.Sprintf("arn:%s:iam::%s:root", meta.(*AWSClient).partition, billingAccountId))
return nil
}
|
Clean dist dir before starting generate
|
var gulp = require('gulp'),
babel = require('gulp-babel'),
runSequence = require('run-sequence'),
rename = require('gulp-rename'),
del = require('del'),
exec = require('child_process').exec;
gulp.task('transpile:app', function() {
return gulp.src('./src/main/index.es6.js')
.pipe(babel())
.pipe(rename('index.js'))
.pipe(gulp.dest('./src/main'));
});
gulp.task('clean', function() {
return del(['dist'], {force: true});
});
gulp.task('generate', ['clean', 'transpile:app'], function(cb) {
exec('npm run-script generate', function(err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
cb(err);
});
});
gulp.task('run', ['transpile:app'], function() {
exec('npm start', function(err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
});
});
gulp.task('package', function(cb) {
exec('npm run-script package', function(err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
});
});
gulp.task('default', function() {
return runSequence('clean', 'transpile:app', 'generate');
});
|
var gulp = require('gulp'),
babel = require('gulp-babel'),
runSequence = require('run-sequence'),
rename = require('gulp-rename'),
del = require('del'),
exec = require('child_process').exec;
gulp.task('transpile:app', function() {
return gulp.src('./src/main/index.es6.js')
.pipe(babel())
.pipe(rename('index.js'))
.pipe(gulp.dest('./src/main'));
});
gulp.task('clean', function() {
return del(['dist'], {force: true});
});
gulp.task('generate', ['transpile:app'], function(cb) {
exec('npm run-script generate', function(err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
cb(err);
});
});
gulp.task('run', ['transpile:app'], function() {
exec('npm start', function(err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
});
});
gulp.task('package', function(cb) {
exec('npm run-script package', function(err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
});
});
gulp.task('default', function() {
return runSequence('clean', 'transpile:app', 'generate');
});
|
Use MutableAddress instead of Address
|
# This file is part of Shoop Gifter Demo.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from django import forms
from shoop.front.views.basket import DefaultBasketView
from shoop.core.models import MutableAddress
class AddressForm(forms.ModelForm):
class Meta:
model = MutableAddress
fields = (
"name", "phone", "email", "street",
"street2", "postal_code", "city",
"region", "country"
)
def __init__(self, *args, **kwargs):
super(AddressForm, self).__init__(*args, **kwargs)
for field_name in ("email", "postal_code"):
self.fields[field_name].required = True
class B2bBasketView(DefaultBasketView):
shipping_address_form_class = AddressForm
billing_address_form_class = AddressForm
|
# This file is part of Shoop Gifter Demo.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from django import forms
from shoop.core.models import Address
from shoop.front.views.basket import DefaultBasketView
class AddressForm(forms.ModelForm):
class Meta:
model = Address
fields = (
"name", "phone", "email", "street",
"street2", "postal_code", "city",
"region", "country"
)
def __init__(self, *args, **kwargs):
super(AddressForm, self).__init__(*args, **kwargs)
for field_name in ("email", "postal_code"):
self.fields[field_name].required = True
class B2bBasketView(DefaultBasketView):
shipping_address_form_class = AddressForm
billing_address_form_class = AddressForm
|
Remove redundant index declaration from Event
The updated at index is already declared in ChangeTracked mixin which is
included in the Base mixin.
|
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
from ggrc import db
from ggrc.models.mixins import Base
class Event(Base, db.Model):
__tablename__ = 'events'
action = db.Column(
db.Enum(u'POST', u'PUT', u'DELETE', u'BULK', u'GET'),
nullable=False,
)
resource_id = db.Column(db.Integer)
resource_type = db.Column(db.String)
revisions = db.relationship(
'Revision',
backref='event',
cascade='all, delete-orphan',
)
_publish_attrs = [
'action',
'resource_id',
'resource_type',
'revisions',
]
_include_links = [
'revisions',
]
@staticmethod
def _extra_table_args(class_):
return (
db.Index('events_modified_by', 'modified_by_id'),
)
@classmethod
def eager_query(cls):
from sqlalchemy import orm
query = super(Event, cls).eager_query()
return query.options(
orm.subqueryload('revisions').undefer_group('Revision_complete'),
)
|
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
from ggrc import db
from ggrc.models.mixins import Base
class Event(Base, db.Model):
__tablename__ = 'events'
action = db.Column(
db.Enum(u'POST', u'PUT', u'DELETE', u'BULK', u'GET'),
nullable=False,
)
resource_id = db.Column(db.Integer)
resource_type = db.Column(db.String)
revisions = db.relationship(
'Revision',
backref='event',
cascade='all, delete-orphan',
)
_publish_attrs = [
'action',
'resource_id',
'resource_type',
'revisions',
]
_include_links = [
'revisions',
]
@staticmethod
def _extra_table_args(class_):
return (
db.Index('events_modified_by', 'modified_by_id'),
db.Index(
'ix_{}_updated_at'.format(class_.__tablename__),
'updated_at',
),
)
@classmethod
def eager_query(cls):
from sqlalchemy import orm
query = super(Event, cls).eager_query()
return query.options(
orm.subqueryload('revisions').undefer_group('Revision_complete'),
)
|
Allow the render only a limited number of tweets
|
<?php
namespace Knp\Bundle\LastTweetsBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Knp\Bundle\LastTweetsBundle\Twitter\Exception\TwitterException;
use Symfony\Component\HttpFoundation\Response;
class TwitterController extends Controller
{
public function lastTweetsAction($username, $limit = 10, $age = null)
{
$twitter = $this->get('knp_last_tweets.last_tweets_fetcher');
try {
$tweets = $twitter->fetch($username, $limit);
} catch (TwitterException $e) {
$tweets = array();
}
$response = $this->render('KnpLastTweetsBundle:Tweet:lastTweets.html.twig', array(
'username' => $username . date('H:i:s'),
'tweets' => $tweets,
));
if ($age) {
$response->setSharedMaxAge($age);
}
return $response;
}
}
|
<?php
namespace Knp\Bundle\LastTweetsBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Knp\Bundle\LastTweetsBundle\Twitter\Exception\TwitterException;
use Symfony\Component\HttpFoundation\Response;
class TwitterController extends Controller
{
public function lastTweetsAction($username, $age = null)
{
$twitter = $this->get('knp_last_tweets.last_tweets_fetcher');
try {
$tweets = $twitter->fetch($username);
} catch (TwitterException $e) {
$tweets = array();
}
$response = $this->render('KnpLastTweetsBundle:Tweet:lastTweets.html.twig', array(
'username' => $username . date('H:i:s'),
'tweets' => $tweets,
));
if ($age) {
$response->setSharedMaxAge($age);
}
return $response;
}
}
|
Use tileSize direct from options
|
(function(previousMethods){
if (typeof previousMethods === 'undefined') {
// Defining previously that object allows you to use that plugin even if you have overridden L.map
previousMethods = {
getTiledPixelBounds: L.GridLayer.prototype._getTiledPixelBounds
};
}
L.GridLayer.include({
_getTiledPixelBounds : function(center, zoom, tileZoom) {
var pixelBounds = previousMethods.getTiledPixelBounds.call(this, center, zoom, tileZoom);
if (this.options.edgeBufferTiles > 0) {
var pixelEdgeBuffer = this.options.edgeBufferTiles * this.options.tileSize;
pixelBounds = new L.Bounds(pixelBounds.min.subtract([pixelEdgeBuffer, pixelEdgeBuffer]), pixelBounds.max.add([pixelEdgeBuffer, pixelEdgeBuffer]));
}
return pixelBounds;
}
});
})(window.leafletEdgeBufferPreviousMethods);
|
(function(previousMethods){
if (typeof previousMethods === 'undefined') {
// Defining previously that object allows you to use that plugin even if you have overridden L.map
previousMethods = {
getTiledPixelBounds: L.GridLayer.prototype._getTiledPixelBounds
};
}
L.GridLayer.include({
_getTiledPixelBounds : function(center, zoom, tileZoom) {
var pixelBounds = previousMethods.getTiledPixelBounds.call(this, center, zoom, tileZoom);
if (this.options.edgeBufferTiles > 0) {
var pixelEdgeBuffer = this.options.edgeBufferTiles * this._getTileSize();
pixelBounds = new L.Bounds(pixelBounds.min.subtract([pixelEdgeBuffer, pixelEdgeBuffer]), pixelBounds.max.add([pixelEdgeBuffer, pixelEdgeBuffer]));
}
return pixelBounds;
}
});
})(window.leafletEdgeBufferPreviousMethods);
|
Make sure some results were returned to avoid error.
Change-Id: Ic788bd1be6711e8c9475909562514d66c6a26d4c
|
$( function() {
if ( !mw.pageTriage ) {
mw.pageTriage = {};
}
mw.pageTriage.viewUtil = {
// fetch and compile a template, then return it.
// args: view, template
template: function( arg ) {
apiRequest = {
'action': 'pagetriagetemplate',
'view': arg.view,
'format': 'json'
};
var templateText;
if( arg.template instanceof Array ) {
apiRequest.template = arg.template.join('|');
} else {
apiRequest.template = arg.template;
}
$.ajax( {
type: 'post',
url: mw.util.wikiScript( 'api' ),
data: apiRequest,
dataType: 'json',
async: false,
success: function( result ) {
if ( result.pagetriagetemplate !== undefined && result.pagetriagetemplate.result === 'success' ) {
templateText = result.pagetriagetemplate.template;
}
}
} );
return _.template( templateText );
}
};
} );
|
$( function() {
if ( !mw.pageTriage ) {
mw.pageTriage = {};
}
mw.pageTriage.viewUtil = {
// fetch and compile a template, then return it.
// args: view, template
template: function( arg ) {
apiRequest = {
'action': 'pagetriagetemplate',
'view': arg.view,
'format': 'json'
};
var templateText;
if( arg.template instanceof Array ) {
apiRequest.template = arg.template.join('|');
} else {
apiRequest.template = arg.template;
}
$.ajax( {
type: 'post',
url: mw.util.wikiScript( 'api' ),
data: apiRequest,
dataType: 'json',
async: false,
success: function( result ) {
if( result.pagetriagetemplate.result == 'success' ) {
templateText = result.pagetriagetemplate.template;
}
}
} );
return _.template( templateText );
}
};
} );
|
Make OAuth path hack platform independent.
|
# -*- coding: utf-8 -*-
"""
requests._oauth
~~~~~~~~~~~~~~~
This module comtains the path hack neccesary for oauthlib to be vendored into requests
while allowing upstream changes.
"""
import os
import sys
try:
from oauthlib.oauth1 import rfc5849
from oauthlib.common import extract_params
from oauthlib.oauth1.rfc5849 import (Client, SIGNATURE_HMAC, SIGNATURE_TYPE_AUTH_HEADER)
except ImportError:
directory = os.path.dirname(__file__)
path = os.path.join(directory, 'packages')
sys.path.insert(0, path)
from oauthlib.oauth1 import rfc5849
from oauthlib.common import extract_params
from oauthlib.oauth1.rfc5849 import (Client, SIGNATURE_HMAC, SIGNATURE_TYPE_AUTH_HEADER)
|
# -*- coding: utf-8 -*-
"""
requests._oauth
~~~~~~~~~~~~~~~
This module comtains the path hack neccesary for oauthlib to be vendored into requests
while allowing upstream changes.
"""
import os
import sys
try:
from oauthlib.oauth1 import rfc5849
from oauthlib.common import extract_params
from oauthlib.oauth1.rfc5849 import (Client, SIGNATURE_HMAC, SIGNATURE_TYPE_AUTH_HEADER)
except ImportError:
path = os.path.abspath('/'.join(__file__.split('/')[:-1]+['packages']))
sys.path.insert(0, path)
from oauthlib.oauth1 import rfc5849
from oauthlib.common import extract_params
from oauthlib.oauth1.rfc5849 import (Client, SIGNATURE_HMAC, SIGNATURE_TYPE_AUTH_HEADER)
|
feat: Add isRunning, start and stop method
|
'use strict';
var polyfills = require('famous-polyfills');
var rAF = polyfills.requestAnimationFrame;
function Engine() {
this._updates = [];
var _this = this;
this.looper = function(time) {
_this.loop(time);
};
this._looper = this.loop.bind(this);
this.start();
}
Engine.prototype.start = function start() {
this._running = true;
this._looper();
return this;
};
Engine.prototype.stop = function stop() {
this._running = false;
return this;
};
Engine.prototype.isRunning = function isRunning() {
return this._running;
};
Engine.prototype.step = function step (time) {
for (var i = 0, len = this._updates.length ; i < len ; i++) {
this._updates[i].update(time);
}
return this;
};
Engine.prototype.loop = function loop(time) {
this.step(time);
if (this._running) {
rAF(this._looper);
}
return this;
};
Engine.prototype.update = function update(item) {
this._updates.push(item);
return this;
};
Engine.prototype.noLongerUpdate = function noLongerUpdate(item) {
this._updates.splice(this._updates.indexOf(item), 1);
return this;
};
module.exports = Engine;
|
'use strict';
var polyfills = require('famous-polyfills');
var rAF = polyfills.requestAnimationFrame;
function Engine () {
this.updates = [];
var _this = this;
this.looper = function(time) {
_this.loop(time);
};
this.looper();
}
Engine.prototype.step = function step (time) {
for (var i = 0, len = this.updates.length ; i < len ; i++) {
this.updates[i].update(time);
}
};
Engine.prototype.loop = function loop (time) {
this.step(time);
rAF(this.looper);
};
Engine.prototype.update = function update (item) {
this.updates.push(item);
return this;
};
Engine.prototype.noLongerUpdate = function noLongerUpdate (item) {
this.updates.splice(this.updates.indexOf(item), 1);
return this;
};
module.exports = Engine;
|
Fix for error reporting email
|
var Log = require("log4js");
var Utils = require("./Utils");
Log.configure({
"replaceConsole": true,
"appenders": process.env.DEBUG ? [{"type": "console"}] :
[
{
"type": "console"
},
{
"type": "logLevelFilter",
"level": "ERROR",
"appender": {
"type": "smtp",
"recipients": process.env.EMAIL,
"sender": process.env.EMAIL,
"sendInterval": process.env.LOG_EMAIL_INTERVAL || 30,
"transport": "SMTP",
"SMTP": Utils.getEmailConfig()
}
}
]
});
module.exports = Log.getLogger();
|
var Log = require("log4js");
var Utils = require("./Utils");
Log.configure({
"replaceConsole": true,
"appenders": process.env.DEBUG ? [{"type": "console"}] :
[
{
"type": "console"
},
{
"type": "logLevelFilter",
"level": "ERROR",
"appender": {
"type": "smtp",
"recipients": process.env.EMAIL,
"sender": "info@ideacolorthemes.org",
"sendInterval": process.env.LOG_EMAIL_INTERVAL || 30,
"transport": "SMTP",
"SMTP": Utils.getEmailConfig()
}
}
]
});
module.exports = Log.getLogger();
|
[Stitching] Add MP’s Artist type to Convection’s Submission type.
|
import { mergeSchemas, introspectSchema, makeRemoteExecutableSchema } from "graphql-tools"
import { createHttpLink } from "apollo-link-http"
import fetch from "node-fetch"
import localSchema from "./schema"
export default async function mergedSchema() {
const convectionLink = createHttpLink({
fetch,
uri: process.env.CONVECTION_GRAPH_URL,
headers: {
Authorization: `Bearer ${process.env.CONVECTION_TOKEN}`,
},
})
const convectionSchema = await makeRemoteExecutableSchema({
schema: await introspectSchema(convectionLink),
link: convectionLink,
})
const linkTypeDefs = `
extend type Submission {
artist: Artist
}
`
return mergeSchemas({
schemas: [localSchema, convectionSchema, linkTypeDefs],
// Prefer others over the local MP schema.
onTypeConflict: (_leftType, rightType) => {
// console.warn(`[!] Type collision ${rightType}`)
return rightType
},
resolvers: mergeInfo => ({
Submission: {
artist: {
fragment: `fragment SubmissionArtist on Submission { artist_id }`,
resolve: (parent, args, context, info) => {
const id = parent.artist_id
return mergeInfo.delegate("query", "artist", { id }, context, info)
},
},
},
}),
})
}
|
import { mergeSchemas, introspectSchema, makeRemoteExecutableSchema } from "graphql-tools"
import { createHttpLink } from "apollo-link-http"
import fetch from "node-fetch"
import localSchema from "./schema"
export default async function mergedSchema() {
const convectionLink = createHttpLink({
fetch,
uri: process.env.CONVECTION_GRAPH_URL,
headers: {
Authorization: `Bearer ${process.env.CONVECTION_TOKEN}`,
},
})
const convectionSchema = await makeRemoteExecutableSchema({
schema: await introspectSchema(convectionLink),
link: convectionLink,
})
return mergeSchemas({
schemas: [localSchema, convectionSchema],
// Prefer others over the local MP schema.
onTypeConflict: (_leftType, rightType) => {
console.warn(`[!] Type collision ${rightType}`)
return rightType
},
})
}
|
Remove useless argument passed in watch
|
var Component = require('../core/Component');
var Loop = new Component('loop', {
templateName: 'component/loop',
data: { audio: null },
methods: {
play: function () {
var self = this;
if (!this.audio) { return; }
this.audio.play();
this.audio.addEventListener('ended', function () {
self.play();
});
}
},
created: function () {
this.$watch('audio', function () {
this.play();
});
}
});
module.exports = Loop;
|
var Component = require('../core/Component');
var Loop = new Component('loop', {
templateName: 'component/loop',
data: { audio: null },
methods: {
play: function () {
var self = this;
if (!this.audio) { return; }
this.audio.play();
this.audio.addEventListener('ended', function () {
self.play();
});
}
},
created: function () {
this.$watch('audio', function (a) {
this.play();
});
}
});
module.exports = Loop;
|
Add own class for each article attribute.
|
@if($article->param('show_title'))
<h3 class="article-title">
<a href="{{ url($article->alias) }}">{{ $article->present()->title }}</a>
</h3>
@endif
<div class="article-details">
@if($article->param('show_author'))
<p class="article-author">Written by: {{ $article->present()->author }}</p>
@endif
@if($article->param('show_create_date'))
<p class="article-created">
<i class="fa fa-calendar"></i> Published: {{ $article->present()->datePublished }}
</p>
@endif
@if($article->param('show_modify_date'))
<p class="article-modified">
<i class="fa fa-calendar"></i> Modified: {{ $article->present()->dateModified }}
</p>
@endif
@if($article->param('show_hits'))
<p class="article-hits">
<i class="fa fa-eye"></i> Hits: {{ $article->present()->hits }}
</p>
@endif
</div>
<div class="article-content">
{!! $article->present()->content !!}
</div>
|
@if($article->param('show_title'))
<h3 class="article-title">
<a href="{{ url($article->alias) }}">{{ $article->present()->title }}</a>
</h3>
@endif
<div class="article-details">
@if($article->param('show_author'))
<small class="inline-help">Written by: {{ $article->present()->author }}</small>
<br>
@endif
@if($article->param('show_create_date'))
<small class="inline-help">
<i class="fa fa-calendar"></i> Published: {{ $article->present()->datePublished }}
</small>
<br>
@endif
@if($article->param('show_modify_date'))
<small class="inline-help">
<i class="fa fa-calendar"></i> Modified: {{ $article->present()->dateModified }}
</small>
<br>
@endif
@if($article->param('show_hits'))
<small class="inline-help">
<i class="fa fa-eye"></i> Hits: {{ $article->present()->hits }}
</small>
@endif
</div>
<div class="article-content">
{!! $article->present()->content !!}
</div>
|
Increase the max buffer so it never errors on that
Even with huge output.
|
'use strict';
const childProcess = require('child_process');
const dargs = require('dargs');
const resolveCwd = require('resolve-cwd');
const BIN = require.resolve('ava/cli.js');
const HUNDRED_MEGABYTES = 1000 * 1000 * 100;
module.exports = grunt => {
grunt.registerMultiTask('ava', 'Run AVA tests', function () {
const cb = this.async();
const opts = this.options();
const args = [BIN].concat(this.filesSrc, '--color', dargs(opts, {excludes: ['nyc']}));
if (opts.nyc) {
const nycBin = resolveCwd('nyc/bin/nyc.js');
if (nycBin) {
args.unshift(nycBin);
} else {
grunt.warn('Couldn\'t find the `nyc` binary');
cb();
return;
}
}
childProcess.execFile(process.execPath, args, {
maxBuffer: HUNDRED_MEGABYTES
}, (err, stdout, stderr) => {
if (err) {
grunt.warn(stderr || stdout || err);
cb();
return;
}
grunt.log.write(stderr + stdout);
cb();
});
});
};
|
'use strict';
const childProcess = require('child_process');
const dargs = require('dargs');
const resolveCwd = require('resolve-cwd');
const BIN = require.resolve('ava/cli.js');
module.exports = grunt => {
grunt.registerMultiTask('ava', 'Run AVA tests', function () {
const cb = this.async();
const opts = this.options();
const args = [BIN].concat(this.filesSrc, '--color', dargs(opts, {excludes: ['nyc']}));
if (opts.nyc) {
const nycBin = resolveCwd('nyc/bin/nyc.js');
if (nycBin) {
args.unshift(nycBin);
} else {
grunt.warn('Couldn\'t find the `nyc` binary');
cb();
return;
}
}
childProcess.execFile(process.execPath, args, (err, stdout, stderr) => {
if (err) {
grunt.warn(stderr || stdout || err);
cb();
return;
}
grunt.log.write(stderr + stdout);
cb();
});
});
};
|
Fix bug in CookingPreference plugin
The cooking preference could not really be changed,
it only looked like it was changed since the fact
was added, not changed correctly.
|
// SPDX-License-Identifier: MIT
package mealplaner.plugins.preference.mealextension;
import static mealplaner.commons.BundleStore.BUNDLES;
import static mealplaner.commons.gui.tables.TableColumnBuilder.withEnumContent;
import static mealplaner.model.meal.MealBuilder.from;
import java.util.List;
import mealplaner.commons.gui.buttonpanel.ButtonPanelEnabling;
import mealplaner.commons.gui.tables.FlexibleTableBuilder;
import mealplaner.model.meal.Meal;
import mealplaner.plugins.api.MealEditExtension;
public class MealEditCookingPreference implements MealEditExtension {
@Override
public FlexibleTableBuilder addTableColumns(
FlexibleTableBuilder table, List<Meal> meals, ButtonPanelEnabling buttonPanelEnabling) {
return table.addColumn(withEnumContent(CookingPreference.class)
.withColumnName(BUNDLES.message("popularityColumn"))
.setValueToOrderedImmutableList(meals,
(meal, preference) -> from(meal).changeFact(new CookingPreferenceFact(preference))
.create())
.getValueFromOrderedList(
meals, meal -> meal.getTypedMealFact(CookingPreferenceFact.class).getCookingPreference())
.isEditable()
.onChange(buttonPanelEnabling::enableButtons)
.buildWithOrderNumber(50));
}
}
|
// SPDX-License-Identifier: MIT
package mealplaner.plugins.preference.mealextension;
import static mealplaner.commons.BundleStore.BUNDLES;
import static mealplaner.commons.gui.tables.TableColumnBuilder.withEnumContent;
import static mealplaner.model.meal.MealBuilder.from;
import java.util.List;
import mealplaner.commons.gui.buttonpanel.ButtonPanelEnabling;
import mealplaner.commons.gui.tables.FlexibleTableBuilder;
import mealplaner.model.meal.Meal;
import mealplaner.plugins.api.MealEditExtension;
public class MealEditCookingPreference implements MealEditExtension {
@Override
public FlexibleTableBuilder addTableColumns(
FlexibleTableBuilder table, List<Meal> meals, ButtonPanelEnabling buttonPanelEnabling) {
return table.addColumn(withEnumContent(CookingPreference.class)
.withColumnName(BUNDLES.message("popularityColumn"))
.setValueToOrderedImmutableList(meals,
(meal, preference) -> from(meal).addFact(new CookingPreferenceFact(preference))
.create())
.getValueFromOrderedList(
meals, meal -> meal.getTypedMealFact(CookingPreferenceFact.class).getCookingPreference())
.isEditable()
.onChange(buttonPanelEnabling::enableButtons)
.buildWithOrderNumber(50));
}
}
|
Add notification config for wcloud
|
package main
import (
"time"
)
// Deployment describes a deployment
type Deployment struct {
ID string `json:"id"`
CreatedAt time.Time `json:"created_at"`
ImageName string `json:"image_name"`
Version string `json:"version"`
Priority int `json:"priority"`
State string `json:"status"`
LogKey string `json:"-"`
}
// Config for the deployment system for a user.
type Config struct {
RepoURL string `json:"repo_url" yaml:"repo_url"`
RepoPath string `json:"repo_path" yaml:"repo_path"`
RepoKey string `json:"repo_key" yaml:"repo_key"`
KubeconfigPath string `json:"kubeconfig_path" yaml:"kubeconfig_path"`
Notifications []NotificationConfig `json:"notification" yaml:"notification"`
}
// NotificationConfig describes how to send notifications
type NotificationConfig struct {
SlackWebhookURL string `json:"slack_webhook_url" yaml:"slack_webhook_url"`
SlackUsername string `json:"slack_username" yaml:"slack_username"`
}
|
package main
import (
"time"
)
// Deployment describes a deployment
type Deployment struct {
ID string `json:"id"`
CreatedAt time.Time `json:"created_at"`
ImageName string `json:"image_name"`
Version string `json:"version"`
Priority int `json:"priority"`
State string `json:"status"`
LogKey string `json:"-"`
}
// Config for the deployment system for a user.
type Config struct {
RepoURL string `json:"repo_url" yaml:"repo_url"`
RepoPath string `json:"repo_path" yaml:"repo_path"`
RepoKey string `json:"repo_key" yaml:"repo_key"`
KubeconfigPath string `json:"kubeconfig_path" yaml:"kubeconfig_path"`
}
|
Allow to search items by description.
|
# -*- coding:utf-8 -*-
from django.contrib import admin
from sorl.thumbnail.admin import AdminImageMixin
from .models import Section, Group, Item, Image, Area
class ImageInline(AdminImageMixin, admin.StackedInline):
model = Image
extra = 5
class ItemAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',), }
list_display = ('title', 'group', 'area', 'user', 'is_active', 'posted', 'updated')
list_filter = ('area', 'group', 'is_active', 'posted',)
search_fields = ('title', 'description', 'user__email')
inlines = [ImageInline]
class GroupAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',), }
list_display = ('title', 'slug', 'section', 'count')
list_filter = ('section',)
search_fields = ('title', 'section__title')
class SectionAdmin(admin.ModelAdmin):
list_display = ('title',)
class AreaAdmin(admin.ModelAdmin):
list_display = (
'title',
)
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Area, AreaAdmin)
admin.site.register(Section, SectionAdmin)
admin.site.register(Group, GroupAdmin)
admin.site.register(Item, ItemAdmin)
|
# -*- coding:utf-8 -*-
from django.contrib import admin
from sorl.thumbnail.admin import AdminImageMixin
from .models import Section, Group, Item, Image, Area
class ImageInline(AdminImageMixin, admin.StackedInline):
model = Image
extra = 5
class ItemAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',), }
list_display = ('title', 'group', 'area', 'user', 'is_active', 'posted', 'updated')
list_filter = ('area', 'group', 'is_active', 'posted',)
search_fields = ('title', 'user__email')
inlines = [ImageInline]
class GroupAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',), }
list_display = ('title', 'slug', 'section', 'count')
list_filter = ('section',)
search_fields = ('title', 'section__title')
class SectionAdmin(admin.ModelAdmin):
list_display = ('title',)
class AreaAdmin(admin.ModelAdmin):
list_display = (
'title',
)
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Area, AreaAdmin)
admin.site.register(Section, SectionAdmin)
admin.site.register(Group, GroupAdmin)
admin.site.register(Item, ItemAdmin)
|
Implement flags via third-party package
|
package main
import (
"fmt"
"os"
"github.com/jessevdk/go-flags"
"github.com/sosedoff/musicbot/bot"
)
var options struct {
MopidyHost string `long:"mopidy" description:"Mopidy server host:port" env:"MOPIDY_HOST"`
SlackToken string `long:"slack-token" description:"Slack integration token" env:"SLACK_TOKEN"`
SlackChannel string `long:"slack-channel" description:"Slack channel name" default:"general" env:"SLACK_CHANNEL"`
Debug bool `short:"d" long:"debug" description:"Enable debugging mode" default:"false"`
}
func init() {
_, err := flags.ParseArgs(&options, os.Args)
if err != nil {
os.Exit(1)
}
if options.MopidyHost == "" {
fmt.Println("Error: Mopidy host is not provided")
os.Exit(1)
}
if options.SlackToken == "" {
fmt.Println("Error: Slack token is not provided")
os.Exit(1)
}
}
func main() {
bot := bot.NewBot(bot.BotConfig{
MopidyHost: options.MopidyHost,
SlackToken: options.SlackToken,
Channel: options.SlackChannel,
})
bot.Run()
// dummy
chexit := make(chan bool)
<-chexit
}
|
package main
import (
"fmt"
"os"
"github.com/sosedoff/musicbot/bot"
)
func main() {
if os.Getenv("MOPIDY_HOST") == "" {
fmt.Println("MOPIDY_HOST is not provided")
return
}
if os.Getenv("SLACK_TOKEN") == "" {
fmt.Println("SLACK_TOKEN is not provided")
return
}
if os.Getenv("SLACK_CHANNEL") == "" {
fmt.Println("SLACK_CHANNEL is not provided")
return
}
bot := bot.NewBot(bot.BotConfig{
MopidyHost: os.Getenv("MOPIDY_HOST"),
SlackToken: os.Getenv("SLACK_TOKEN"),
Channel: os.Getenv("SLACK_CHANNEL"),
})
bot.Run()
// dummy
chexit := make(chan bool)
<-chexit
}
|
Fix membership async loading for tasks
|
import Ember from 'ember';
const {
get,
inject: { service },
Route,
RSVP
} = Ember;
export default Route.extend({
projectTaskBoard: service(),
async model() {
let project = this.modelFor('project');
let memberPromises = await get(project, 'organization.organizationMemberships').then((memberships) => {
return memberships.map((membership) => get(membership, 'member'));
});
return RSVP.hash({ project, members: RSVP.all(memberPromises) });
},
setupController(controller, models) {
controller.setProperties(models);
},
actions: {
didTransition() {
this._super(...arguments);
get(this, 'projectTaskBoard').activate();
return true;
},
willTransition() {
this._super(...arguments);
get(this, 'projectTaskBoard').deactivate();
return true;
},
transitionToTask(task) {
let project = get(task, 'project');
let organizationSlug = get(project, 'organization.slug');
let projectSlug = get(project, 'slug');
let taskNumber = get(task, 'number');
this.transitionTo('project.tasks.task', organizationSlug, projectSlug, taskNumber);
}
}
});
|
import Ember from 'ember';
const {
get,
inject: { service },
Route,
RSVP
} = Ember;
export default Route.extend({
projectTaskBoard: service(),
model() {
let project = this.modelFor('project');
let members = RSVP.all(get(project, 'organization.organizationMemberships').mapBy('member'));
return RSVP.hash({ project, members });
},
setupController(controller, models) {
controller.setProperties(models);
},
actions: {
didTransition() {
this._super(...arguments);
get(this, 'projectTaskBoard').activate();
return true;
},
willTransition() {
this._super(...arguments);
get(this, 'projectTaskBoard').deactivate();
return true;
},
transitionToTask(task) {
let project = get(task, 'project');
let organizationSlug = get(project, 'organization.slug');
let projectSlug = get(project, 'slug');
let taskNumber = get(task, 'number');
this.transitionTo('project.tasks.task', organizationSlug, projectSlug, taskNumber);
}
}
});
|
Return initial state when stat is undefined.
|
import thunk from 'redux-thunk'
import createLogger from 'redux-logger'
import createBrowserHistory from 'history/lib/createBrowserHistory'
import { compose, createStore, applyMiddleware } from 'redux'
import { reduxReactRouter, routerStateReducer } from 'redux-router'
import { analytics, uploader, requester } from './middleware'
import { autoRehydrate } from 'redux-persist'
import routes from './routes'
import * as reducers from './reducers'
const logger = createLogger({ collapsed: true })
function reducer(state = {}, action) {
if (!state && window.__INITIAL_STATE__) { return window.__INITIAL_STATE__ }
return {
json: reducers.json(state.json, action, state.router),
devtools: reducers.devtools(state.devtools, action),
modals: reducers.modals(state.modals, action),
profile: reducers.profile(state.profile, action),
router: routerStateReducer(state.router, action),
stream: reducers.stream(state.stream, action),
}
}
const store = compose(
autoRehydrate(),
applyMiddleware(thunk, uploader, requester, analytics, logger),
reduxReactRouter({routes: routes, createHistory: createBrowserHistory})
)(createStore)(reducer)
export default store
|
import thunk from 'redux-thunk'
import createLogger from 'redux-logger'
import createBrowserHistory from 'history/lib/createBrowserHistory'
import { compose, createStore, applyMiddleware } from 'redux'
import { reduxReactRouter, routerStateReducer } from 'redux-router'
import { analytics, uploader, requester } from './middleware'
import { autoRehydrate } from 'redux-persist'
import routes from './routes'
import * as reducers from './reducers'
const logger = createLogger({ collapsed: true })
function reducer(state = {}, action) {
return {
json: reducers.json(state.json, action, state.router),
devtools: reducers.devtools(state.devtools, action),
modals: reducers.modals(state.modals, action),
profile: reducers.profile(state.profile, action),
router: routerStateReducer(state.router, action),
stream: reducers.stream(state.stream, action),
}
}
const store = compose(
autoRehydrate(),
applyMiddleware(thunk, uploader, requester, analytics, logger),
reduxReactRouter({routes: routes, createHistory: createBrowserHistory})
)(createStore)(reducer)
export default store
|
Fix broken install caused by broadcast message
|
<div class='container'>
@if(\App\HorizontCMS::isInstalled() && \Auth::check() && \Settings::get('admin_broadcast') != '')
<div class="alert alert-info alert-dismissible" role="alert">
<span class='glyphicon glyphicon-info-sign' aria-hidden='true'></span>
<strong>Broadcast message: </strong> {{ \Settings::get('admin_broadcast') }}
</div>
@endif
@if(session()->has('message'))
@foreach(session()->get('message') as $key => $value)
<div class="alert alert-{{ $key }} alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
@if($key == 'success')
<span class='glyphicon glyphicon-ok' aria-hidden='true'></span>
@elseif($key == 'danger')
<span class='glyphicon glyphicon-exclamation-sign' aria-hidden='true'></span>
@elseif($key == 'warning')
<span class='glyphicon glyphicon-warning-sign' aria-hidden='true'></span>
@elseif($key == 'info')
<span class='glyphicon glyphicon-info-sign' aria-hidden='true'></span>
@endif
<strong>{{ ucfirst($key) }}!</strong> {{ $value }}
</div>
@endforeach
@endif
</div>
|
<div class='container'>
@if(\App\HorizontCMS::isInstalled() && \Settings::get('admin_broadcast') != '')
<div class="alert alert-info alert-dismissible" role="alert">
<span class='glyphicon glyphicon-info-sign' aria-hidden='true'></span>
<strong>Broadcast message: </strong> {{ \Settings::get('admin_broadcast') }}
</div>
@endif
@if(session()->has('message'))
@foreach(session()->get('message') as $key => $value)
<div class="alert alert-{{ $key }} alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
@if($key == 'success')
<span class='glyphicon glyphicon-ok' aria-hidden='true'></span>
@elseif($key == 'danger')
<span class='glyphicon glyphicon-exclamation-sign' aria-hidden='true'></span>
@elseif($key == 'warning')
<span class='glyphicon glyphicon-warning-sign' aria-hidden='true'></span>
@elseif($key == 'info')
<span class='glyphicon glyphicon-info-sign' aria-hidden='true'></span>
@endif
<strong>{{ ucfirst($key) }}!</strong> {{ $value }}
</div>
@endforeach
@endif
</div>
|
Add support for multi-way pots.
|
# usage: python one_time_eval.py hole_cards [board_cards]
# examples:
# python one_time_eval.py as8sqdtc
# python one_time_eval.py as8sqdtc 2skskd
# python one_time_eval.py as8sqdtc3d3c 2skskd
# python one_time_eval.py as8sqdtc3d3c 2skskd3h5s
from convenience import find_pcts_multi, pr, str2cards
import sys
## argv to strings
hole_cards_str = sys.argv[1]
board_str = ''
if len(sys.argv) > 2:
board_str = sys.argv[2]
## strings to lists of Card objects
hole_cards = str2cards(hole_cards_str)
board = str2cards(board_str)
## hole card list to player list-of-lists
assert len(hole_cards) % 2 == 0
n_players = len(hole_cards) / 2
assert n_players > 1
p = []
for i in range(n_players):
pi = hole_cards[i * 2 : i * 2 + 2]
pr(pi)
p.append(pi)
print "Board",
pr(board)
percents = find_pcts_multi(p, board, iter = 10000)
print [round(x, 4) for x in percents]
|
# usage: python one_time_eval.py as8sqdtc
# usage: python one_time_eval.py as8sqdtc 2skskd
from convenience import find_pcts, pr, str2cards
import sys
## argv to strings
hole_cards_str = sys.argv[1]
board_str = ''
if len(sys.argv) > 2:
board_str = sys.argv[2]
## strings to lists of Card objects
hole_cards = str2cards(hole_cards_str)
board = str2cards(board_str)
## card list to player list-of-lists
assert len(hole_cards) % 2 == 0
n_players = len(hole_cards) / 2
assert n_players > 1
p = []
for i in range(n_players):
pi = hole_cards[i * 2 : i * 2 + 2]
pr(pi)
p.append(pi)
print "Board",
pr(board)
print find_pcts(p[0], p[1], board, iter = 10000)
|
Add return on specific value
|
package main
import (
"fmt"
"log"
"net"
"strings"
)
func main() {
l, err := net.Listen("tcp", ":2000")
if err != nil {
log.Fatal(err)
}
defer l.Close()
for {
conn, err := l.Accept()
if err != nil {
log.Fatal(err)
}
go func(c net.Conn) {
buf := make([]byte, 4096)
for {
fmt.Println("here")
n, err := c.Read(buf)
if err != nil || n == 0 {
c.Close()
break
}
b := buf[:n]
s := string(b)
s = strings.TrimSpace(s)
if s == "hello" {
c.Write([]byte("Hello user\n"))
} else {
n, err = c.Write(b)
}
if err != nil {
c.Close()
break
}
}
}(conn)
}
}
|
package main
import (
"fmt"
"log"
"net"
"strings"
)
func main() {
l, err := net.Listen("tcp", ":2000")
if err != nil {
log.Fatal(err)
}
defer l.Close()
for {
conn, err := l.Accept()
if err != nil {
log.Fatal(err)
}
go func(c net.Conn) {
buf := make([]byte, 4096)
for {
n, err := c.Read(buf)
if err != nil || n == 0 {
c.Close()
break
}
b := buf[:n]
s := string(b)
s = strings.TrimSpace(s)
fmt.Print(s)
fmt.Println("------")
n, err = c.Write(b)
if err != nil {
c.Close()
break
}
}
}(conn)
}
}
|
Mark version as beta
Remove pytest plugin entrypoint (not ready)
|
from setuptools import setup
setup(
name='pytest-ui',
description='Text User Interface for running python tests',
version='0.1b',
license='MIT',
platforms=['linux', 'osx', 'win32'],
packages=['pytui'],
url='https://github.com/martinsmid/pytest-ui',
author_email='martin.smid@gmail.com',
author='Martin Smid',
entry_points={
'console_scripts': [
'pytui = pytui.ui:main',
]
},
install_requires=['urwid>=1.3.1', 'pytest>=3.0.5'],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Operating System :: POSIX',
'Operating System :: Microsoft :: Windows',
'Operating System :: MacOS :: MacOS X',
'Topic :: Software Development :: Testing',
'Topic :: Utilities',
'Programming Language :: Python', ],
)
|
from setuptools import setup
setup(
name='pytest-ui',
description='Text User Interface for running python tests',
version='0.1',
license='MIT',
platforms=['linux', 'osx', 'win32'],
packages=['pytui'],
url='https://github.com/martinsmid/pytest-ui',
author_email='martin.smid@gmail.com',
author='Martin Smid',
entry_points={
'pytest11': [
'pytui = pytui.plugin',
],
'console_scripts': [
'pytui = pytui.ui:main',
]
},
install_requires=['urwid>=1.3.1', 'pytest>=3.0.5'],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Operating System :: POSIX',
'Operating System :: Microsoft :: Windows',
'Operating System :: MacOS :: MacOS X',
'Topic :: Software Development :: Testing',
'Topic :: Utilities',
'Programming Language :: Python', ],
)
|
Fix race condition that prevented session from being marked as complete
Ember actions are fire and forget (unless using closure actions + return values).
So when the frame next/save action happened, it had the effect of saving the frame payload before the flag got set. This changes the order: it marks the session as complete, then saves the account, instead of tying the two saves together.
This increases the risk of data / state inconsistency slightly (between session and account models) but it's the bets option shy of large internal refactorings.
[#LEI-330]
|
import Ember from 'ember';
import ExpPlayer from 'exp-player/components/exp-player/component';
export default ExpPlayer.extend({
// Show an early exit modal (return non-empty string), but only with browser default message- don't require translation of custom text.
messageEarlyExitModal: ' ',
currentUser: Ember.inject.service(),
actions: {
sessionCompleted() {
// Mark the current user account as having completed a session, then, also update the session model
// If this fails to save the account due to normal network issues, it will still update the session but
// swallow the error
this.get('session').set('completed', true);
return this.get('currentUser').getCurrentUser().then(([account]) => {
// Deal with `extra` field sometimes being undefined
let dest = account.get('extra') || {};
dest['hasCompletedStudy'] = true;
account.set('extra', dest);
return account.save();
}).catch( e => console.error('Could not mark account as having completed study:', e));
}
}
});
|
import Ember from 'ember';
import ExpPlayer from 'exp-player/components/exp-player/component';
export default ExpPlayer.extend({
// Show an early exit modal (return non-empty string), but only with browser default message- don't require translation of custom text.
messageEarlyExitModal: ' ',
currentUser: Ember.inject.service(),
actions: {
sessionCompleted() {
// Mark the current user account as having completed a session, then, also update the session model
// If this fails to save the account due to normal network issues, it will still update the session but
// swallow the error
return this.get('currentUser').getCurrentUser().then(([account]) => {
// Deal with `extra` field sometimes being undefined
let dest = account.get('extra') || {};
dest['hasCompletedStudy'] = true;
account.set('extra', dest);
return account.save();
}).catch( e => console.log('Could not mark account as having completed study:', e)
).finally(() => this._super(...arguments));
},
}
});
|
Annotate build steps for clarity
|
const gulp = require('gulp');
const babel = require('gulp-babel');
// Copy all files except for *.js ones
gulp.task('cp', function() {
gulp.src([
'app/**/!(*.js)',
'MIT-LICENSE.txt',
'README.md',
])
.pipe(gulp.dest('dist'));
});
// Copy the entire lib/ directory; it's vendor, 3rd party stuff
gulp.task('cp-lib', function() {
gulp.src('app/lib/**')
.pipe(gulp.dest('dist/lib'));
});
// Compile app JS with babel
gulp.task('js', function() {
var presets = ['es2015', 'react'];
gulp.src('app/*.js')
.pipe(babel({
presets: presets,
}))
.pipe(gulp.dest('dist'));
gulp.src('app/js/*.js')
.pipe(babel({
presets: presets,
}))
.pipe(gulp.dest('dist/js'));
});
gulp.task('default', ['cp', 'cp-lib', 'js']);
|
const gulp = require('gulp');
const babel = require('gulp-babel');
gulp.task('cp', function() {
gulp.src([
'app/**/!(*.js)',
'MIT-LICENSE.txt',
'README.md',
])
.pipe(gulp.dest('dist'));
});
gulp.task('cp-lib', function() {
gulp.src('app/lib/**')
.pipe(gulp.dest('dist/lib'));
});
gulp.task('js', function() {
var presets = ['es2015', 'react'];
gulp.src('app/*.js')
.pipe(babel({
presets: presets,
}))
.pipe(gulp.dest('dist'));
gulp.src('app/js/*.js')
.pipe(babel({
presets: presets,
}))
.pipe(gulp.dest('dist/js'));
});
gulp.task('default', ['cp', 'cp-lib', 'js']);
|
Fix dashboard panel title when dashboard is undefined
|
function maDashboardPanel($state) {
return {
restrict: 'E',
scope: {
collection: '&',
entries: '&'
},
link: function(scope) {
scope.gotoList = function () {
$state.go($state.get('list'), { entity: scope.collection().entity.name() });
};
},
template:
'<div class="panel-heading">' +
'<a ng-click="gotoList()">{{ collection().title() || collection().entity.label() }}</a>' +
'</div>' +
'<ma-datagrid name="{{ collection().name() }}"' +
' entries="entries()"' +
' fields="::collection().fields()"' +
' entity="::collection().entity"' +
' list-actions="::collection().listActions()">' +
'</ma-datagrid>'
};
}
maDashboardPanel.$inject = ['$state'];
module.exports = maDashboardPanel;
|
function maDashboardPanel($state) {
return {
restrict: 'E',
scope: {
collection: '&',
entries: '&'
},
link: function(scope) {
scope.gotoList = function () {
$state.go($state.get('list'), { entity: scope.collection().entity.name() });
};
},
template:
'<div class="panel-heading">' +
'<a ng-click="gotoList()">{{ collection().title() || collection().entity().label() }}</a>' +
'</div>' +
'<ma-datagrid name="{{ collection().name() }}"' +
' entries="entries()"' +
' fields="::collection().fields()"' +
' entity="::collection().entity"' +
' list-actions="::collection().listActions()">' +
'</ma-datagrid>'
};
}
maDashboardPanel.$inject = ['$state'];
module.exports = maDashboardPanel;
|
feat(users): Fix "signin" promise return warning
|
'use strict';
/**
* Module dependencies.
*/
var path = require('path'),
db = require(path.resolve('./config/lib/sequelize')),
passport = require('passport'),
LocalStrategy = require('passport-local').Strategy;
module.exports = function() {
// Use local strategy
passport.use(new LocalStrategy({
usernameField: 'username',
passwordField: 'password'
},
function(username, password, done) {
db.User.findOne({
where: {
username: username
}
})
.then(function(user) {
if (!user || !user.authenticate(user, password)) {
done(null, false, {
message: 'Invalid username or password'
});
return null;
}
done(null, user);
return null;
})
.catch(function(err) {
done(err);
});
}));
};
|
'use strict';
/**
* Module dependencies.
*/
var path = require('path'),
db = require(path.resolve('./config/lib/sequelize')),
passport = require('passport'),
LocalStrategy = require('passport-local').Strategy;
module.exports = function() {
// Use local strategy
passport.use(new LocalStrategy({
usernameField: 'username',
passwordField: 'password'
},
function(username, password, done) {
db.User.findOne({
where: {
username: username
}
})
.then(function(user) {
if (!user || !user.authenticate(user, password)) {
return done(null, false, {
message: 'Invalid username or password'
});
}
done(null, user);
return null;
})
.catch(function(err) {
done(err);
});
}));
};
|
Add name to logout url.
|
"""bikeshop URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth.views import login, logout_then_login
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from core import urls as core_urls
from registration import urls as member_urls
urlpatterns = [
url(r'^', include(core_urls)),
url(r'^login/', login, {'template_name': 'login.html'}, name='login'),
url(r'^logout/', logout_then_login, name='logout'),
url(r'^member/', include(member_urls)),
url(r'^admin/', admin.site.urls),
]
if getattr(settings, 'DEBUG'):
urlpatterns += staticfiles_urlpatterns()
|
"""bikeshop URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth.views import login, logout_then_login
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from core import urls as core_urls
from registration import urls as member_urls
urlpatterns = [
url(r'^', include(core_urls)),
url(r'^login/', login, {'template_name': 'login.html'}, name='login'),
url(r'^logout/', logout_then_login),
url(r'^member/', include(member_urls)),
url(r'^admin/', admin.site.urls),
]
if getattr(settings, 'DEBUG'):
urlpatterns += staticfiles_urlpatterns()
|
Switch to interface to avoid code coverage issue.
|
package com.greghaskins.spectrum;
import static com.greghaskins.spectrum.Spectrum.describe;
import static com.greghaskins.spectrum.Spectrum.fdescribe;
import static com.greghaskins.spectrum.Spectrum.xdescribe;
/**
* A translation from {@link Spectrum#describe(String, Block)} to the Ginkgo syntax.
* Ginkgo has a <code>Context</code> keyword that can be mapped to <code>describe</code>
* in Spectrum terms. Ginkgo is here - https://onsi.github.io/ginkgo/
*/
public interface GinkgoSyntax {
/**
* Define a test context.
* @param context the description of the context
* @param block the block to execute
*/
public static void context(final String context, final Block block) {
describe(context, block);
}
/**
* Define a focused test context - see {@link Spectrum#fdescribe(String, Block)}.
* @param context the description of the context
* @param block the block to execute
*/
public static void fcontext(final String context, final Block block) {
fdescribe(context, block);
}
/**
* Define an ignored test context - see {@link Spectrum#xdescribe(String, Block)}.
* @param context the description of the context
* @param block the block to execute
*/
public static void xcontext(final String context, final Block block) {
xdescribe(context, block);
}
}
|
package com.greghaskins.spectrum;
import static com.greghaskins.spectrum.Spectrum.describe;
import static com.greghaskins.spectrum.Spectrum.fdescribe;
import static com.greghaskins.spectrum.Spectrum.xdescribe;
/**
* A translation from {@link Spectrum#describe(String, Block)} to the Ginkgo syntax.
* Ginkgo has a <code>Context</code> keyword that can be mapped to <code>describe</code>
* in Spectrum terms. Ginkgo is here - https://onsi.github.io/ginkgo/
*/
public class GinkgoSyntax {
/**
* Define a test context.
* @param context the description of the context
* @param block the block to execute
*/
public static void context(final String context, final Block block) {
describe(context, block);
}
/**
* Define a focused test context - see {@link Spectrum#fdescribe(String, Block)}.
* @param context the description of the context
* @param block the block to execute
*/
public static void fcontext(final String context, final Block block) {
fdescribe(context, block);
}
/**
* Define an ignored test context - see {@link Spectrum#xdescribe(String, Block)}.
* @param context the description of the context
* @param block the block to execute
*/
public static void xcontext(final String context, final Block block) {
xdescribe(context, block);
}
}
|
Change url pattern from /e/ to /entry/
|
from django.conf.urls.defaults import *
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^\+media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
(r'^admin/', include(admin.site.urls)),
url(r'^(?P<id>\d+)$', 'tempel.views.view', {'mode': 'html'}, name='tempel_view'),
url(r'^(?P<id>\d+).html$', 'tempel.views.view', {'mode': 'html'}, name='tempel_html'),
url(r'^(?P<id>\d+).txt$', 'tempel.views.view', {'mode': 'txt'}, name='tempel_raw'),
url(r'^entry/(?P<id>\d+)/download/$', 'tempel.views.download', name='tempel_download'),
url(r'^entry/(?P<id>\d+)/edit/(?P<token>\w{8})/$', 'tempel.views.edit', name='tempel_edit'),
url(r'^$', 'tempel.views.index', name='tempel_index'),
)
|
from django.conf.urls.defaults import *
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^\+media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
(r'^admin/', include(admin.site.urls)),
url(r'^(?P<id>\d+)$', 'tempel.views.view', {'mode': 'html'}, name='tempel_view'),
url(r'^(?P<id>\d+).html$', 'tempel.views.view', {'mode': 'html'}, name='tempel_html'),
url(r'^(?P<id>\d+).txt$', 'tempel.views.view', {'mode': 'txt'}, name='tempel_raw'),
url(r'^e/(?P<id>\d+)/download/$', 'tempel.views.download', name='tempel_download'),
url(r'^e/(?P<id>\d+)/edit/(?P<token>\w{8})/$', 'tempel.views.edit', name='tempel_edit'),
url(r'^$', 'tempel.views.index', name='tempel_index'),
)
|
Make the counter migration safer.
|
import json
from redash import models
if __name__ == '__main__':
for vis in models.Visualization.select():
if vis.type == 'COUNTER':
options = json.loads(vis.options)
print "Before: ", options
if 'rowNumber' in options and options['rowNumber'] is not None:
options['rowNumber'] += 1
else:
options['rowNumber'] = 1
if 'counterColName' not in options:
options['counterColName'] = 'counter'
if 'targetColName' not in options:
options['targetColName'] = 'target'
options['targetRowNumber'] = options['rowNumber']
print "After: ", options
vis.options = json.dumps(options)
vis.save()
|
import json
from redash import models
if __name__ == '__main__':
for vis in models.Visualization.select():
if vis.type == 'COUNTER':
options = json.loads(vis.options)
print "Before: ", options
if 'rowNumber' in options:
options['rowNumber'] += 1
else:
options['rowNumber'] = 1
if 'counterColName' not in options:
options['counterColName'] = 'counter'
if 'targetColName' not in options:
options['targetColName'] = 'target'
options['targetRowNumber'] = options['rowNumber']
print "After: ", options
vis.options = json.dumps(options)
vis.save()
|
Make explicit that MapBuilder is in the global namespace
|
// Create map object
window.MapBuilder = {};
// initialize map
MapBuilder.init = function(id) {
// Create map container
var leafletMap = L.mapbox.map(id, 'codeforamerica.hek4o94g', {maxZoom: 15, minZoom: 10, accessToken: 'pk.eyJ1IjoiY29kZWZvcmFtZXJpY2EiLCJhIjoiSTZlTTZTcyJ9.3aSlHLNzvsTwK-CYfZsG_Q'}).setView([38.042,-84.515], 11);
// Make layer group
var addresses = L.layerGroup();
return {
addToMap: function (data) {
addresses.clearLayers();
var geoJsonResults = L.geoJson(data, {
onEachFeature: function(feature, layer) {
layer.bindPopup(feature.properties.formatted_address);
}
});
addresses.addLayer(geoJsonResults).addTo(leafletMap);
}
}
}
|
// Create map object
var MapBuilder = {};
// initialize map
MapBuilder.init = function(id) {
// Create map container
var leafletMap = L.mapbox.map(id, 'codeforamerica.hek4o94g', {maxZoom: 15, minZoom: 10, accessToken: 'pk.eyJ1IjoiY29kZWZvcmFtZXJpY2EiLCJhIjoiSTZlTTZTcyJ9.3aSlHLNzvsTwK-CYfZsG_Q'}).setView([38.042,-84.515], 11);
// Make layer group
var addresses = L.layerGroup();
return {
addToMap: function (data) {
addresses.clearLayers();
var geoJsonResults = L.geoJson(data, {
onEachFeature: function(feature, layer) {
layer.bindPopup(feature.properties.formatted_address);
}
});
addresses.addLayer(geoJsonResults).addTo(leafletMap);
}
}
}
|
Send correct expiration timing in login email
|
from celery import shared_task
from django.conf import settings
from django.utils import timezone
from agir.people.actions.mailing import send_mosaico_email
def interleave_spaces(s, n=3):
return ' '.join([s[i:i+n] for i in range(0, len(s), n)])
@shared_task
def send_login_email(email, short_code, expiry_time):
utc_expiry_time = timezone.make_aware(timezone.datetime.utcfromtimestamp(expiry_time), timezone.utc)
local_expiry_time = timezone.localtime(utc_expiry_time)
send_mosaico_email(
code='LOGIN_MESSAGE',
subject="Connexion à agir.lafranceinsoumise.fr",
from_email=settings.EMAIL_FROM,
bindings={
'CODE': interleave_spaces(short_code),
'EXPIRY_TIME': local_expiry_time.strftime("%H:%M")
},
recipients=[email]
)
|
from celery import shared_task
from django.conf import settings
from django.utils import timezone
from agir.people.actions.mailing import send_mosaico_email
def interleave_spaces(s, n=3):
return ' '.join([s[i:i+n] for i in range(0, len(s), n)])
@shared_task
def send_login_email(email, short_code, expiry_time):
utc_expiry_time = timezone.make_aware(timezone.datetime.fromtimestamp(expiry_time), timezone.utc)
local_expiry_time = timezone.localtime(utc_expiry_time)
send_mosaico_email(
code='LOGIN_MESSAGE',
subject="Connexion à agir.lafranceinsoumise.fr",
from_email=settings.EMAIL_FROM,
bindings={
'CODE': interleave_spaces(short_code),
'EXPIRY_TIME': local_expiry_time.strftime("%H:%M")
},
recipients=[email]
)
|
Make autodiscover() work with zipped eggs.
|
from django.conf import settings
__all__ = ["autodiscover", "find_related_module"]
def autodiscover():
"""Include tasks for all applications in settings.INSTALLED_APPS."""
return filter(None, [find_related_module(app, "tasks")
for app in settings.INSTALLED_APPS])
def find_related_module(app, related_name):
"""Given an application name and a module name, tries to find that
module in the application, and running handler' if it finds it.
"""
try:
module = __import__(app, {}, {}, [related_name])
except ImportError:
return None
try:
related_module = getattr(module, related_name)
except AttributeError:
return None
return related_module
|
import imp
from django.conf import settings
from django.core import exceptions
__all__ = ["autodiscover", "tasks_for_app", "find_related_module"]
def autodiscover():
"""Include tasks for all applications in settings.INSTALLED_APPS."""
return filter(None, [tasks_for_app(app)
for app in settings.INSTALLED_APPS])
def tasks_for_app(app):
"""Given an application name, imports any tasks.py file for that app."""
def found_tasks_module_handler(app_path, app_basename):
return __import__("%s.tasks" % app)
return find_related_module(app, "tasks", found_tasks_module_handler)
def find_related_module(app, related_name, handler):
"""Given an application name and a module name, tries to find that
module in the application, and running handler' if it finds it.
"""
# See django.contrib.admin.autodiscover for an explanation of this code.
try:
app_basename = app.split('.')[-1]
app_path = __import__(app, {}, {}, app_basename).__path__
except AttributeError:
return None
try:
imp.find_module(related_name, app_path)
except ImportError:
return None
return handler(app_path, app_basename)
|
Fix erors when no plugins
|
<?php
namespace Rudolf\Modules\Plugins\Roll\Admin;
use Rudolf\Component\Plugins\Manager as PluginsManager;
use Rudolf\Framework\Model\BaseModel;
class Model extends BaseModel
{
/**
* Returns total number of modules items.
*
* @param array|string $where
*
* @return int
*/
public function getTotalNumber()
{
return count($modules = (new PluginsManager(MODULES_ROOT))->getCollection()->getAll());
}
/**
* Returns array with modules list.
*
* @return array
*/
public function getList()
{
$modules = (new PluginsManager(MODULES_ROOT))->getCollection()->getAll();
if (empty($modules)) {
return false;
}
$i = 1;
foreach ($modules as $key => $value) {
$array[] = [
'id' => $i++,
'name' => $value->getName(),
'status' => $value->getStatus(),
];
}
return $array;
}
}
|
<?php
namespace Rudolf\Modules\Plugins\Roll\Admin;
use Rudolf\Component\Plugins\Manager as PluginsManager;
use Rudolf\Framework\Model\BaseModel;
class Model extends BaseModel
{
/**
* Returns total number of modules items.
*
* @param array|string $where
*
* @return int
*/
public function getTotalNumber()
{
return count($modules = (new PluginsManager(MODULES_ROOT))->getCollection()->getAll()) - 1;
}
/**
* Returns array with modules list.
*
* @return array
*/
public function getList()
{
$modules = (new PluginsManager(MODULES_ROOT))->getCollection()->getAll();
$i = 1;
foreach ($modules as $key => $value) {
$array[] = [
'id' => $i++,
'name' => $value->getName(),
'status' => $value->getStatus(),
];
}
return $array;
}
}
|
Add missing author tag to nb locale
|
import formatDistance from './_lib/formatDistance/index.js'
import formatLong from './_lib/formatLong/index.js'
import formatRelative from './_lib/formatRelative/index.js'
import localize from './_lib/localize/index.js'
import match from './_lib/match/index.js'
/**
* @type {Locale}
* @category Locales
* @summary Norwegian Bokmål locale.
* @language Norwegian Bokmål
* @iso-639-2 nob
* @author Hans-Kristian Koren [@Hanse]{@link https://github.com/Hanse}
* @author Mikolaj Grzyb [@mikolajgrzyb]{@link https://github.com/mikolajgrzyb}
* @author Dag Stuan [@dagstuan]{@link https://github.com/dagstuan}
*/
var locale = {
formatDistance: formatDistance,
formatLong: formatLong,
formatRelative: formatRelative,
localize: localize,
match: match,
options: {
weekStartsOn: 1 /* Monday */,
firstWeekContainsDate: 4
}
}
export default locale
|
import formatDistance from './_lib/formatDistance/index.js'
import formatLong from './_lib/formatLong/index.js'
import formatRelative from './_lib/formatRelative/index.js'
import localize from './_lib/localize/index.js'
import match from './_lib/match/index.js'
/**
* @type {Locale}
* @category Locales
* @summary Norwegian Bokmål locale.
* @language Norwegian Bokmål
* @iso-639-2 nob
* @author Hans-Kristian Koren [@Hanse]{@link https://github.com/Hanse}
* @author Mikolaj Grzyb [@mikolajgrzyb]{@link https://github.com/mikolajgrzyb}
*/
var locale = {
formatDistance: formatDistance,
formatLong: formatLong,
formatRelative: formatRelative,
localize: localize,
match: match,
options: {
weekStartsOn: 1 /* Monday */,
firstWeekContainsDate: 4
}
}
export default locale
|
Align base exception for test with what pyOpenSSL uses.
|
import time
from unittest import TestCase
from pandora.py2compat import Mock, call
from tests.test_pandora.test_clientbuilder import TestSettingsDictBuilder
class SysCallError(Exception):
pass
class TestTransport(TestCase):
def test_call_should_retry_max_times_on_sys_call_error(self):
with self.assertRaises(SysCallError):
client = TestSettingsDictBuilder._build_minimal()
time.sleep = Mock()
client.transport._make_http_request = Mock(
side_effect=SysCallError("mock_error"))
client.transport._start_request = Mock()
client("method")
client.transport._start_request.assert_has_calls([call("method")])
assert client.transport._start_request.call_count == 5
|
import time
from unittest import TestCase
from pandora.py2compat import Mock, call
from tests.test_pandora.test_clientbuilder import TestSettingsDictBuilder
class SysCallError(IOError):
pass
class TestTransport(TestCase):
def test_call_should_retry_max_times_on_sys_call_error(self):
with self.assertRaises(SysCallError):
client = TestSettingsDictBuilder._build_minimal()
time.sleep = Mock()
client.transport._make_http_request = Mock(
side_effect=SysCallError("mock_error"))
client.transport._start_request = Mock()
client("method")
client.transport._start_request.assert_has_calls([call("method")])
assert client.transport._start_request.call_count == 5
|
[FEATURE] Build default bank account when creating a user.
|
var User = require('../models/user'),
BankAccount = require('../models/bank_account'),
utils = require('../utils');
module.exports = (function() {
function index(req, res) {
User.all().success(function(users) {
res.send(users);
});
}
function create(req, res) {
if (req.body.name && req.body.password) {
var salt = utils.generateSalt();
var passwordHash = utils.saltPassword(req.body.password, salt);
var user = User.build({
name: req.body.name,
salt: salt,
passwordHash: passwordHash,
federationTag: 'federationTag',
federationName: 'federationName'
});
user.save()
.success(function() {
// create a bank account for that user
BankAccount.create({
userId: user.id
})
.success(function(bankAccount){
user.bankAccount = bankAccount;
res.send({ status: 'user created', user: user })
})
.error(function(err){
user.destroy().success(function(){
res.send({ status: 'user not created', error: err });
});
});
})
.error(function(err) {
res.send({ status: 'user not created', error: err });
});
} else {
res.send({ error: 'required params: name, password' });
}
}
return {
index: index,
create: create
}
})();
|
var User = require('../models/user'),
utils = require('../utils');
module.exports = (function() {
function index(req, res) {
User.all().success(function(users) {
res.send(users);
});
}
function create(req, res) {
if (req.body.name && req.body.password) {
var salt = utils.generateSalt();
var passwordHash = utils.saltPassword(req.body.password, salt);
var user = User.build({
name: req.body.name,
salt: salt,
passwordHash: passwordHash,
federationTag: 'federationTag',
federationName: 'federationName'
});
user.save()
.success(function() {
res.send({ status: 'user created', user: user })
})
.error(function(err) {
res.send({ status: 'user not created', error: err });
});
} else {
res.send({ error: 'required params: name, password' });
}
}
return {
index: index,
create: create
}
})();
|
Include new module dependencies: ngMessages.
|
'use strict';
// Init the application configuration module for AngularJS application
var ApplicationConfiguration = (function() {
// Init module configuration options
var applicationModuleName = 'Codeaux';
var applicationModuleVendorDependencies = ['ngResource', 'ngCookies', 'ngAnimate', 'ngTouch', 'ngMessages',
'ngSanitize', 'ui.router', 'ui.bootstrap', 'ui.utils'];
// Add a new vertical module
var registerModule = function(moduleName, dependencies) {
// Create angular module
angular.module(moduleName, dependencies || []);
// Add the module to the AngularJS configuration file
angular.module(applicationModuleName).requires.push(moduleName);
};
return {
applicationModuleName: applicationModuleName,
applicationModuleVendorDependencies: applicationModuleVendorDependencies,
registerModule: registerModule
};
})();
|
'use strict';
// Init the application configuration module for AngularJS application
var ApplicationConfiguration = (function() {
// Init module configuration options
var applicationModuleName = 'Codeaux';
var applicationModuleVendorDependencies = ['ngResource', 'ngCookies', 'ngAnimate', 'ngTouch',
'ngSanitize', 'ui.router', 'ui.bootstrap', 'ui.utils'];
// Add a new vertical module
var registerModule = function(moduleName, dependencies) {
// Create angular module
angular.module(moduleName, dependencies || []);
// Add the module to the AngularJS configuration file
angular.module(applicationModuleName).requires.push(moduleName);
};
return {
applicationModuleName: applicationModuleName,
applicationModuleVendorDependencies: applicationModuleVendorDependencies,
registerModule: registerModule
};
})();
|
Add a test for extracting service domain from a link
|
#!/usr/bin/env python
import os
import webapp
import unittest
class WebappTestExtractingServiceDomainsFromLinks(unittest.TestCase):
#def setUp(self):
# self.app = webapp.app.test_client()
def test_extract_service_domain_from_link(self):
status, domain = webapp.extract_service_domain_from_link('https://foo.service.gov.uk/blah')
assert True == status
assert "foo.service.gov.uk" == domain
def test_extract_nonservice_domain_from_link(self):
status, domain = webapp.extract_service_domain_from_link('https://foo.foo.gov.uk/blah')
assert False == status
class WebappTestExtractingServiceLinkFromSlug(unittest.TestCase):
def test_find_link_from_slug(self):
status, link = webapp.find_link_from_slug('/lasting-power-of-attorney')
assert True == status
assert "https://lastingpowerofattorney.service.gov.uk/" == link
def test_fail_to_find_link_from_slug(self):
status, link = webapp.find_link_from_slug('/bank-holidays')
assert False == status
if __name__ == '__main__':
unittest.main()
|
#!/usr/bin/env python
import os
import webapp
import unittest
class WebappTestExtractingServiceDomainsFromLinks(unittest.TestCase):
#def setUp(self):
# self.app = webapp.app.test_client()
def test_extract_service_domain_from_link(self):
status, domain = webapp.extract_service_domain_from_link('https://foo.service.gov.uk/blah')
assert True == status
assert "foo.service.gov.uk" == domain
def test_extract_nonservice_domain_from_link(self):
status, domain = webapp.extract_service_domain_from_link('https://foo.foo.gov.uk/blah')
assert False == status
if __name__ == '__main__':
unittest.main()
|
Add timeout for name setting
|
Template.videoFlexTab.helpers({
});
Template.videoFlexTab.onCreated(function() {
this.timeout = null;
this.autorun(() => {
});
// Opening a PR so we can do this via the https://meet.jit.si/external_api.js
$.getScript( "https://cdn.rawgit.com/geekgonecrazy/jitsi-meet/master/external_api.js" )
.done(function( script, textStatus ) {
var domain = "meet.jit.si"; // Need to get from settings
var room = "a124124124124124125125126"; // Need to calc from instance id and room id
var width = 500;
var height = 500;
var configOverwrite = {};
var interfaceConfigOverwrite = {};
var api = new JitsiMeetExternalAPI(domain, room, width, height, document.getElementById('videoContainer'), configOverwrite, interfaceConfigOverwrite, true);
// This for sure needs to be an onReady of some sort instead
setTimeout(() => {
api.executeCommand('displayName', [Meteor.user().name])
}, 3000);
})
.fail(function( jqxhr, settings, exception ) {
// Show an error
});
});
Template.videoFlexTab.events({
});
|
Template.videoFlexTab.helpers({
});
Template.videoFlexTab.onCreated(function() {
this.timeout = null;
this.autorun(() => {
});
// Opening a PR so we can do this via the https://meet.jit.si/external_api.js
$.getScript( "https://cdn.rawgit.com/geekgonecrazy/jitsi-meet/master/external_api.js" )
.done(function( script, textStatus ) {
var domain = "meet.jit.si"; // Need to get from config
var room = "a124124124124124125125125"; // Need to calc from instance id and room id
var width = 500;
var height = 500;
var configOverwrite = {};
var interfaceConfigOverwrite = {};
var api = new JitsiMeetExternalAPI(domain, room, width, height, document.getElementById('videoContainer'), configOverwrite, interfaceConfigOverwrite, true);
api.executeCommand('displayName', [Meteor.user().name]);
})
.fail(function( jqxhr, settings, exception ) {
// Show an error
});
});
Template.videoFlexTab.events({
});
|
inventory: Move size from UserTshirt to Tshirt
|
import uuid
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from symposion.conference.models import Conference
from root.models import Base
class Tshirt(Base):
""" Model to store the different types of tshirt. """
gender = models.CharField(_("gender"), max_length=255)
size = models.CharField(_("size"), max_length=5)
limit = models.PositiveIntegerField(_("limit"), default=0)
price = models.PositiveIntegerField(_("price"), default=0, db_index=True)
conference = models.ForeignKey(Conference, verbose_name=_("conference"))
class Meta:
verbose_name = _("tshirt")
verbose_name_plural = _("tshirts")
def __unicode(self):
return u"%s: %s" % (self.conference.title, self.gender)
class UserTshirt(Base):
""" Model for maitaining the tshirt order entry for all the Users. """
uuid = models.UUIDField(default=uuid.uuid4, editable=False)
user = models.ForeignKey(User, on_delete=models.CASCADE)
tshirt = models.ForeignKey(Tshirt, on_delete=models.CASCADE)
class Meta:
verbose_name = _("user tshirt")
verbose_name_plural = _("tshirt")
ordering = ['-timestamp']
def __unicode__(self):
return u'%s:%s:%s' % (self.user.username, self.tshirt.gender, self.size)
|
import uuid
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from symposion.conference.models import Conference
from root.models import Base
class Tshirt(Base):
""" Model to store the different types of tshirt. """
gender = models.CharField(_("gender"), max_length=255)
limit = models.PositiveIntegerField(_("limit"), default=0)
price = models.PositiveIntegerField(_("price"), default=0, db_index=True)
conference = models.ForeignKey(Conference, verbose_name=_("conference"))
class Meta:
verbose_name = _("tshirt")
verbose_name_plural = _("tshirts")
def __unicode(self):
return u"%s: %s" % (self.conference.title, self.gender)
class UserTshirt(Base):
""" Model for maitaining the tshirt order entry for all the Users. """
uuid = models.UUIDField(default=uuid.uuid4, editable=False)
size = models.CharField(_("size"), max_length=5)
user = models.ForeignKey(User, on_delete=models.CASCADE)
tshirt = models.ForeignKey(Tshirt, on_delete=models.CASCADE)
class Meta:
verbose_name = _("user tshirt")
verbose_name_plural = _("tshirt")
ordering = ['-timestamp']
def __unicode__(self):
return u'%s:%s:%s' % (self.user.username, self.tshirt.gender, self.size)
|
Add that test to the Feed tests.
|
<?php
require_once 'PHPUnit/Framework.php';
require_once 'FeedAuthorTest.php';
require_once 'FeedCategoryTest.php';
require_once 'FeedContributorTest.php';
require_once 'FeedIdTest.php';
require_once 'FeedRightsTest.php';
require_once 'FeedSubtitleTest.php';
require_once 'FeedTitleTest.php';
require_once 'FeedUpdatedTest.php';
class Atom10_FeedTests
{
public static function suite()
{
$suite = new PHPUnit_Framework_TestSuite('ComplexPie Atom 1.0 Feed');
$suite->addTestSuite('FeedAuthorTest');
$suite->addTestSuite('FeedCategoryTest');
$suite->addTestSuite('FeedContributorTest');
$suite->addTestSuite('FeedIdTest');
$suite->addTestSuite('FeedRightsTest');
$suite->addTestSuite('FeedSubtitleTest');
$suite->addTestSuite('FeedTitleTest');
$suite->addTestSuite('FeedUpdatedTest');
return $suite;
}
}
?>
|
<?php
require_once 'PHPUnit/Framework.php';
require_once 'FeedAuthorTest.php';
require_once 'FeedContributorTest.php';
require_once 'FeedIdTest.php';
require_once 'FeedRightsTest.php';
require_once 'FeedSubtitleTest.php';
require_once 'FeedTitleTest.php';
require_once 'FeedUpdatedTest.php';
class Atom10_FeedTests
{
public static function suite()
{
$suite = new PHPUnit_Framework_TestSuite('ComplexPie Atom 1.0 Feed');
$suite->addTestSuite('FeedAuthorTest');
$suite->addTestSuite('FeedContributorTest');
$suite->addTestSuite('FeedIdTest');
$suite->addTestSuite('FeedRightsTest');
$suite->addTestSuite('FeedSubtitleTest');
$suite->addTestSuite('FeedTitleTest');
$suite->addTestSuite('FeedUpdatedTest');
return $suite;
}
}
?>
|
Fix message generation: when the value contained replacement group for regex it was crashing
|
package com.bloatit.framework.webprocessor.annotations;
import java.util.regex.Matcher;
public class Message {
public enum What {
UNKNOWN, NOT_FOUND, CONVERSION_ERROR, MIN_ERROR, MAX_ERROR, NO_ERROR, LENGTH_ERROR, OPTIONAL_ERROR, PRECISION_ERROR
}
private final String message;
private final What what;
public Message(final String message, final What what, final String name, final String value) {
super();
if (what == null || message == null) {
throw new NullPointerException();
}
this.message = extractErrorMessage(message, name, value);
this.what = what;
}
public Message(final String message) {
this.message = message;
this.what = What.UNKNOWN;
}
private String extractErrorMessage(final String aMessage, final String name, final String value) {
String errorMsg = aMessage.replaceAll("%param", Matcher.quoteReplacement(name));
if (!value.isEmpty()) {
errorMsg = errorMsg.replaceAll("%value", Matcher.quoteReplacement(value));
} else {
errorMsg = errorMsg.replaceAll("%value", "null");
}
return errorMsg;
}
public String getMessage() {
return message;
}
public What getWhat() {
return what;
}
}
|
package com.bloatit.framework.webprocessor.annotations;
public class Message {
public enum What {
UNKNOWN, NOT_FOUND, CONVERSION_ERROR, MIN_ERROR, MAX_ERROR, NO_ERROR, LENGTH_ERROR, OPTIONAL_ERROR, PRECISION_ERROR
}
private final String message;
private final What what;
public Message(final String message, final What what, final String name, final String value) {
super();
if (what == null || message == null) {
throw new NullPointerException();
}
this.message = extractErrorMessage(message, name, value);
this.what = what;
}
public Message(final String message) {
this.message = message;
this.what = What.UNKNOWN;
}
private String extractErrorMessage(final String aMessage, final String name, final String value) {
String errorMsg = aMessage.replaceAll("%param", name);
if (!value.isEmpty()) {
errorMsg = errorMsg.replaceAll("%value", value);
} else {
errorMsg = errorMsg.replaceAll("%value", "null");
}
return errorMsg;
}
public String getMessage() {
return message;
}
public What getWhat() {
return what;
}
}
|
Remove nonexistent packages from find_packages
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from setuptools import find_packages
from setuptools import setup
__version__ = "0.13.0"
setup(
name='pyramid_zipkin',
version=__version__,
provides=["pyramid_zipkin"],
author='Yelp, Inc.',
author_email='opensource+pyramid-zipkin@yelp.com',
license='Copyright Yelp 2016',
url="https://github.com/Yelp/pyramid_zipkin",
description='Zipkin instrumentation for the Pyramid framework.',
packages=find_packages(exclude=('tests*',)),
package_data={'': ['*.thrift']},
install_requires=[
'pyramid',
'six',
'py_zipkin',
],
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Topic :: Software Development :: Libraries :: Python Modules",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
],
)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from setuptools import find_packages
from setuptools import setup
__version__ = "0.13.0"
setup(
name='pyramid_zipkin',
version=__version__,
provides=["pyramid_zipkin"],
author='Yelp, Inc.',
author_email='opensource+pyramid-zipkin@yelp.com',
license='Copyright Yelp 2016',
url="https://github.com/Yelp/pyramid_zipkin",
description='Zipkin instrumentation for the Pyramid framework.',
packages=find_packages(exclude=('tests*', 'testing*', 'tools*')),
package_data={'': ['*.thrift']},
install_requires=[
'pyramid',
'six',
'py_zipkin',
],
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Topic :: Software Development :: Libraries :: Python Modules",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
],
)
|
Add alias for core directories, update devtool property
|
/*global
module, __dirname, require
*/
/**
* @name webpack
* @type {Object}
* @property NoEmitOnErrorsPlugin
*/
/**
* @name path
* @property resolve
*/
var webpack = require('webpack'),
path = require('path');
module.exports = {
entry: {
bundle: './src/index'
},
output: {
filename: 'js/[name].js',
path: path.resolve(__dirname, './build/js'),
publicPath: '../build/'
},
module: {
loaders: [{
test: /\.js/,
exclude: '/node_modules/',
loader: 'babel-loader'
}, {
test: /\.(png|jpg|gif)$/,
loader: 'file-loader?name=images/img-[hash:6].[ext]'
}]
},
plugins: [
new webpack.NoEmitOnErrorsPlugin()
],
devtool: '#cheap-module-eval-source-map',
resolve: {
alias: {
src: path.resolve(__dirname, 'src'),
components: path.resolve(__dirname, 'src/components'),
constants: path.resolve(__dirname, 'src/constants'),
data: path.resolve(__dirname, 'src/data'),
scenes: path.resolve(__dirname, 'src/scenes'),
scss: path.resolve(__dirname, 'src/scss'),
services: path.resolve(__dirname, 'src/services')
}
}
};
|
/*global
module, __dirname, require
*/
/**
* @name webpack
* @type {Object}
* @property NoEmitOnErrorsPlugin
*/
/**
* @name path
* @property resolve
*/
var webpack = require('webpack'),
path = require('path');
module.exports = {
entry: {
bundle: './src/index'
},
output: {
filename: 'js/[name].js',
path: path.resolve(__dirname, './build/js'),
publicPath: '../build/'
},
module: {
loaders: [{
test: /\.js/,
exclude: '/node_modules/',
loader: 'babel-loader'
}, {
test: /\.(png|jpg|gif)$/,
loader: 'file-loader?name=images/img-[hash:6].[ext]'
}]
},
plugins: [
new webpack.NoEmitOnErrorsPlugin()
]
};
|
Fix bug at fragment creation
|
package fr.masciulli.drinks.activity;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.MenuItem;
import fr.masciulli.drinks.R;
import fr.masciulli.drinks.fragment.DrinkDetailFragment;
public class DrinkDetailActivity extends FragmentActivity {
private DrinkDetailFragment mDetailFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drink_detail);
if (savedInstanceState == null) {
mDetailFragment = new DrinkDetailFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.drink_detail_container, mDetailFragment)
.commit();
}
getActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public void finish() {
super.finish();
// override transitions to skip the standard window animations
overridePendingTransition(0, 0);
}
@Override
public void onBackPressed() {
mDetailFragment.onBackPressed();
}
}
|
package fr.masciulli.drinks.activity;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.MenuItem;
import fr.masciulli.drinks.R;
import fr.masciulli.drinks.fragment.DrinkDetailFragment;
public class DrinkDetailActivity extends FragmentActivity {
private DrinkDetailFragment mDetailFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drink_detail);
if (savedInstanceState == null) {
mDetailFragment = new DrinkDetailFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.drink_detail_container, new DrinkDetailFragment())
.commit();
}
getActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public void finish() {
super.finish();
// override transitions to skip the standard window animations
overridePendingTransition(0, 0);
}
@Override
public void onBackPressed() {
mDetailFragment.onBackPressed();
}
}
|
Add a level of uper directory
|
import os
import sys
(dir, filename) = os.path.split(os.path.abspath(sys.argv[0]))
print(dir)
filenames = os.listdir(dir)
for file in filenames:
print(file)
print()
print()
print()
print('*****************************************************')
updir = os.path.abspath('..')
print(updir)
filenames = os.listdir(updir)
for file in filenames:
print(file)
print()
print()
print()
print('*****************************************************')
os.chdir(updir)
upupdir = os.path.abspath('..')
print(upupdir)
filenames = os.listdir(upupdir)
for file in filenames:
print(file)
print()
print()
print()
print('*****************************************************')
os.chdir(upupdir)
upupupdir = os.path.abspath('..')
print(upupupdir)
filenames = os.listdir(upupupdir)
for file in filenames:
print(file)
print()
print()
print()
print('*****************************************************')
os.chdir(upupupdir)
upupupupdir = os.path.abspath('..')
print(upupupupdir)
filenames = os.listdir(upupupupdir)
for file in filenames:
print(file)
|
import os
import sys
(dir, filename) = os.path.split(os.path.abspath(sys.argv[0]))
print(dir)
filenames = os.listdir(dir)
for file in filenames:
print(file)
print('*****************************************************')
updir = os.path.abspath('..')
print(updir)
filenames = os.listdir(updir)
for file in filenames:
print(file)
print('*****************************************************')
os.chdir(updir)
upupdir = os.path.abspath('..')
print(upupdir)
filenames = os.listdir(upupdir)
for file in filenames:
print(file)
print('*****************************************************')
os.chdir(upupdir)
upupupdir = os.path.abspath('..')
print(upupupdir)
filenames = os.listdir(upupupdir)
for file in filenames:
print(file)
|
Exclude `.test.js` files in babel transpile
|
const path = require('path');
module.exports = {
entry: './src',
output: {
filename: 'react-animation-components.js',
path: path.resolve(__dirname, 'lib'),
library: 'react-animations',
libraryTarget: 'umd',
umdNamedDefine: true,
},
resolve: {
modules: [path.join(__dirname, './src'), 'node_modules'],
extensions: ['.js', '.jsx'],
},
module: {
rules: [
{
test: /\.(js|jsx|es6)?$/,
exclude: /\.test.js/,
loader: 'babel-loader',
},
],
},
externals: {
react: 'react',
'react-dom': 'react-dom',
'prop-types': 'prop-types',
'react-transition-group': 'react-transition-group',
},
};
|
const path = require('path');
module.exports = {
entry: './src',
output: {
filename: 'react-animation-components.js',
path: path.resolve(__dirname, 'lib'),
library: 'react-animations',
libraryTarget: 'umd',
umdNamedDefine: true,
},
resolve: {
modules: [path.join(__dirname, './src'), 'node_modules'],
extensions: ['.js', '.jsx'],
},
module: {
rules: [
{
test: /\.(js|jsx|es6)?$/,
loader: 'babel-loader',
},
],
},
externals: {
react: 'react',
'react-dom': 'react-dom',
'prop-types': 'prop-types',
'react-transition-group': 'react-transition-group',
},
};
|
Update to handle when response isnt json
|
/* istanbul ignore file */
const http = require('http')
function parseJSON(data) {
try {
return JSON.parse(data)
} catch (e) {
return data
}
}
module.exports = function httpRequest(body) {
return new Promise((resolve, reject) => {
const request = http.request(
{
hostname: 'server',
port: 8653,
path: '/graphql',
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
Accept: 'application/json',
'X-Requested-With': 'Node.js',
},
},
response => {
let xbody = ''
response.setEncoding('utf8')
response.on('data', d => {
xbody += d
})
response.on('end', () => {
const { statusCode } = response
if (statusCode < 400 && statusCode >= 200) {
resolve(parseJSON(xbody))
} else {
reject(parseJSON(xbody))
}
})
}
)
request.write(body)
request.end()
})
}
|
/* istanbul ignore file */
const http = require('http')
module.exports = function httpRequest(body) {
return new Promise((resolve, reject) => {
const request = http.request(
{
hostname: 'server',
port: 8653,
path: '/graphql',
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
Accept: 'application/json',
'X-Requested-With': 'Node.js',
},
},
response => {
let xbody = ''
response.setEncoding('utf8')
response.on('data', d => {
xbody += d
})
response.on('end', () => {
const { statusCode } = response
if (statusCode < 400 && statusCode >= 200) {
resolve(JSON.parse(xbody))
} else {
reject(JSON.parse(xbody))
}
})
}
)
request.write(body)
request.end()
})
}
|
Use contenthash to generate the JS bundles names
|
const baseConfig = require('./webpack.base.config.js');
const merge = require('webpack-merge');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const WebpackCleanupPlugin = require('webpack-cleanup-plugin');
module.exports = merge(baseConfig, {
bail: true,
devtool: 'source-map',
mode: 'production',
output: {
filename: '[name].[contenthash:8].js',
chunkFilename: '[name].[contenthash:8].js',
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].[contenthash:8].css',
chunkFilename: '[name].[contenthash:8].css',
}),
new OptimizeCSSAssetsPlugin({
cssProcessorOptions: { discardComments: { removeAll: true } },
canPrint: false,
}),
new WebpackCleanupPlugin({
exclude: ['robots.txt', 'favicon-32x32.png', 'favicon-48x48.png'],
}),
],
});
|
const baseConfig = require('./webpack.base.config.js');
const merge = require('webpack-merge');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const WebpackCleanupPlugin = require('webpack-cleanup-plugin');
module.exports = merge(baseConfig, {
bail: true,
devtool: 'source-map',
mode: 'production',
output: {
filename: '[name].[hash:8].js',
chunkFilename: '[name].[hash:8].js',
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].[contenthash:8].css',
chunkFilename: '[name].[contenthash:8].css',
}),
new OptimizeCSSAssetsPlugin({
cssProcessorOptions: { discardComments: { removeAll: true } },
canPrint: false,
}),
new WebpackCleanupPlugin({
exclude: ['robots.txt', 'favicon-32x32.png', 'favicon-48x48.png'],
}),
],
});
|
Add image_alt for adding Alt attribute to img tags
Added image_alt for adding alt attribute to img tags for SEO
|
from openerp.osv import osv, fields
class product_image(osv.Model):
_name = 'product.image'
_columns = {
'name': fields.char('Name'),
'description': fields.text('Description'),
'image_alt': fields.text('Image Label'),
'image': fields.binary('Image'),
'image_small': fields.binary('Small Image'),
'product_tmpl_id': fields.many2one('product.template', 'Product'),
}
product_image()
class product_product(osv.Model):
_inherit = 'product.product'
_columns = {
'images': fields.related('product_tmpl_id', 'images', type="one2many", relation="product.image", string='Images', store=False),
}
product_product()
class product_template(osv.Model):
_inherit = 'product.template'
_columns = {
'images': fields.one2many('product.image', 'product_tmpl_id', string='Images'),
}
product_template()
|
from openerp.osv import osv, fields
class product_image(osv.Model):
_name = 'product.image'
_columns = {
'name': fields.char('Name'),
'description': fields.text('Description'),
'image': fields.binary('Image'),
'image_small': fields.binary('Small Image'),
'product_tmpl_id': fields.many2one('product.template', 'Product'),
}
product_image()
class product_product(osv.Model):
_inherit = 'product.product'
_columns = {
'images': fields.related('product_tmpl_id', 'images', type="one2many", relation="product.image", string='Images', store=False),
}
product_product()
class product_template(osv.Model):
_inherit = 'product.template'
_columns = {
'images': fields.one2many('product.image', 'product_tmpl_id', string='Images'),
}
product_template()
|
Fix error format of check formula endpoint
|
from rest_framework.views import APIView
from rest_framework.reverse import reverse
from rest_framework.response import Response
from rest_framework import generics, status
from django.core.exceptions import ValidationError
from .models import *
from .serializers import *
from .formula import validate_formula
class MetricsBase(APIView):
def get(self, request, format=None):
"""
:type request: Request
:param request:
:return:
"""
result = {
"Metrics": reverse('metrics-create', request=request)
}
return Response(result)
class FormulaValidate(APIView):
def get(self, request):
if "formula" not in request.QUERY_PARAMS:
return Response({ "formula": "Can not be empty"}, status=status.HTTP_400_BAD_REQUEST)
try:
validate_formula(request.QUERY_PARAMS["formula"])
return Response(status=status.HTTP_204_NO_CONTENT)
except ValidationError as e:
return Response({ "formula": e.message }, status=status.HTTP_400_BAD_REQUEST)
class MetricsCreate(generics.CreateAPIView):
model = Metric
serializer_class = MetricSerializer
class MetricsDetail(generics.RetrieveAPIView):
model = Metric
serializer_class = MetricSerializer
|
from rest_framework.views import APIView
from rest_framework.reverse import reverse
from rest_framework.response import Response
from rest_framework import generics, status
from django.core.exceptions import ValidationError
from .models import *
from .serializers import *
from .formula import validate_formula
class MetricsBase(APIView):
def get(self, request, format=None):
"""
:type request: Request
:param request:
:return:
"""
result = {
"Metrics": reverse('metrics-create', request=request)
}
return Response(result)
class FormulaValidate(APIView):
def get(self, request):
if "formula" not in request.QUERY_PARAMS:
return Response("No formula provided")
try:
validate_formula(request.QUERY_PARAMS["formula"])
return Response(status=status.HTTP_204_NO_CONTENT)
except ValidationError as e:
return Response({ "formula": e.message }, status=status.HTTP_400_BAD_REQUEST)
class MetricsCreate(generics.CreateAPIView):
model = Metric
serializer_class = MetricSerializer
class MetricsDetail(generics.RetrieveAPIView):
model = Metric
serializer_class = MetricSerializer
|
Add .yaml extension on default cassette name.
|
from __future__ import absolute_import, unicode_literals
import inspect
import logging
import os
import unittest
import vcr
logger = logging.getLogger(__name__)
class VCRTestCase(unittest.TestCase):
vcr_enabled = True
def setUp(self):
super(VCRTestCase, self).setUp()
if self.vcr_enabled:
myvcr = vcr.VCR(**self._get_vcr_kwargs())
name = self._get_cassette_name()
cm = myvcr.use_cassette(name)
self.cassette = cm.__enter__()
self.addCleanup(cm.__exit__, None, None, None)
def _get_vcr_kwargs(self):
return dict(
cassette_library_dir=self._get_cassette_library_dir(),
)
def _get_cassette_library_dir(self):
testdir = os.path.dirname(inspect.getfile(self.__class__))
return os.path.join(testdir, 'cassettes')
def _get_cassette_name(self):
return '{0}.{1}.yaml'.format(self.__class__.__name__,
self._testMethodName)
|
from __future__ import absolute_import, unicode_literals
import inspect
import logging
import os
import unittest
import vcr
logger = logging.getLogger(__name__)
class VCRTestCase(unittest.TestCase):
vcr_enabled = True
def setUp(self):
super(VCRTestCase, self).setUp()
if self.vcr_enabled:
myvcr = vcr.VCR(**self._get_vcr_kwargs())
name = self._get_cassette_name()
cm = myvcr.use_cassette(name)
self.cassette = cm.__enter__()
self.addCleanup(cm.__exit__, None, None, None)
def _get_vcr_kwargs(self):
return dict(
cassette_library_dir=self._get_cassette_library_dir(),
)
def _get_cassette_library_dir(self):
testdir = os.path.dirname(inspect.getfile(self.__class__))
return os.path.join(testdir, 'cassettes')
def _get_cassette_name(self):
return '{0}.{1}'.format(self.__class__.__name__,
self._testMethodName)
|
Change name for arff read test.
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@4095 d6536bca-fef9-0310-8506-e4c0a848fbcf
|
#!/usr/bin/env python
"""Test for parsing arff headers only."""
import os
from scipy.testing import *
from scipy.io.arff.arffread import read_header, MetaData
data_path = os.path.join(os.path.dirname(__file__), 'data')
test1 = os.path.join(data_path, 'test1.arff')
class HeaderTest(TestCase):
def test_fullheader1(self):
"""Parsing trivial header with nothing."""
ofile = open(test1)
rel, attrs = read_header(ofile)
# Test relation
assert rel == 'test1'
# Test numerical attributes
assert len(attrs) == 5
for i in range(4):
assert attrs[i][0] == 'attr%d' % i
assert attrs[i][1] == 'REAL'
classes = attrs[4][1]
# Test nominal attribute
assert attrs[4][0] == 'class'
assert attrs[4][1] == '{class0, class1, class2, class3}'
if __name__ == "__main__":
nose.run(argv=['', __file__])
|
#!/usr/bin/env python
"""Test for parsing arff headers only."""
import os
from scipy.testing import *
from scipy.io.arff.arffread import read_header, MetaData
data_path = os.path.join(os.path.dirname(__file__), 'data')
test1 = os.path.join(data_path, 'test1.arff')
class HeaderTest(TestCase):
def test_trivial1(self):
"""Parsing trivial header with nothing."""
ofile = open(test1)
rel, attrs = read_header(ofile)
# Test relation
assert rel == 'test1'
# Test numerical attributes
assert len(attrs) == 5
for i in range(4):
assert attrs[i][0] == 'attr%d' % i
assert attrs[i][1] == 'REAL'
classes = attrs[4][1]
# Test nominal attribute
assert attrs[4][0] == 'class'
assert attrs[4][1] == '{class0, class1, class2, class3}'
if __name__ == "__main__":
nose.run(argv=['', __file__])
|
Fix crash problem on orientation change
|
package se.treehou.ng.ohcommunicator.connector.models;
import java.util.ArrayList;
import java.util.List;
import se.treehou.ng.ohcommunicator.connector.ConnectorUtil;
public class OHLinkedPage {
private String id = "";
private String link;
private String title;
private boolean leaf;
private List<OHWidget> widget = new ArrayList<>();
public String getId() {
return id;
}
public void setId(String id) {
if(id == null) id = "";
this.id = id;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isLeaf() {
return leaf;
}
public void setLeaf(boolean leaf) {
this.leaf = leaf;
}
public List<OHWidget> getWidgets() {
return widget;
}
public void setWidgets(List<OHWidget> widget) {
this.widget = widget;
}
public String getBaseUrl(){
return ConnectorUtil.getBaseUrl(getLink());
}
}
|
package se.treehou.ng.ohcommunicator.connector.models;
import java.util.ArrayList;
import java.util.List;
import se.treehou.ng.ohcommunicator.connector.ConnectorUtil;
public class OHLinkedPage {
private String id;
private String link;
private String title;
private boolean leaf;
private List<OHWidget> widget = new ArrayList<>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isLeaf() {
return leaf;
}
public void setLeaf(boolean leaf) {
this.leaf = leaf;
}
public List<OHWidget> getWidgets() {
return widget;
}
public void setWidgets(List<OHWidget> widget) {
this.widget = widget;
}
public String getBaseUrl(){
return ConnectorUtil.getBaseUrl(getLink());
}
}
|
Fix typo in instant replay kepress enum value
|
package com.jaku.core;
public enum KeypressKeyValues {
HOME("Home"),
REV("Rev"),
FWD("Fwd"),
PLAY("Play"),
SELECT("Select"),
LEFT("Left"),
RIGHT("Right"),
DOWN("Down"),
UP("Up"),
BACK("Back"),
INTANT_REPLAY("InstantReplay"),
INFO("Info"),
BACKSPACE("Backspace"),
SEARCH("Search"),
ENTER("Enter"),
FIND_REMOTE("FindRemote"),
VOLUME_DOWN("VolumeDown"),
VOLUME_MUTE("VolumeMute"),
VOLUME_UP("VolumeUp"),
POWER_OFF("PowerOff"),
POWER_ON("PowerOn"),
CHANNELUP("ChannelUp"),
CHANNELDOWN("ChannelDown"),
INPUTTUNER("InputTuner"),
INPUTHDMI1("InputHDMI1"),
INPUTHDMI2("InputHDMI2"),
INPUTHDMI3("InputHDMI3"),
INPUTHDMI4("InputHDMI4"),
INPUTAV1("InputAV1"),
LIT_("Lit_");
private final String method;
KeypressKeyValues(String method) {
this.method = method;
}
public String getValue() {
return method;
}
}
|
package com.jaku.core;
public enum KeypressKeyValues {
HOME("Home"),
REV("Rev"),
FWD("Fwd"),
PLAY("Play"),
SELECT("Select"),
LEFT("Left"),
RIGHT("Right"),
DOWN("Down"),
UP("Up"),
BACK("Back"),
INTANT_REPLAY("IntantReplay"),
INFO("Info"),
BACKSPACE("Backspace"),
SEARCH("Search"),
ENTER("Enter"),
FIND_REMOTE("FindRemote"),
VOLUME_DOWN("VolumeDown"),
VOLUME_MUTE("VolumeMute"),
VOLUME_UP("VolumeUp"),
POWER_OFF("PowerOff"),
POWER_ON("PowerOn"),
CHANNELUP("ChannelUp"),
CHANNELDOWN("ChannelDown"),
INPUTTUNER("InputTuner"),
INPUTHDMI1("InputHDMI1"),
INPUTHDMI2("InputHDMI2"),
INPUTHDMI3("InputHDMI3"),
INPUTHDMI4("InputHDMI4"),
INPUTAV1("InputAV1"),
LIT_("Lit_");
private final String method;
KeypressKeyValues(String method) {
this.method = method;
}
public String getValue() {
return method;
}
}
|
Add method to ID Generator
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trellisldp.spi;
import java.util.function.Supplier;
/**
* The IdentifierService provides a mechanism for creating new identifiers.
*
* @author acoburn
*/
public interface IdentifierService {
/**
* Get a Supplier that generates Strings with the provided prefix
* @param prefix the prefix
* @param hierarchy the levels of hierarchy to add
* @param length the length of each level of hierarchy
* @return a String Supplier
*/
Supplier<String> getSupplier(String prefix, Integer hierarchy, Integer length);
/**
* Get a Supplier that generates Strings with the provided prefix
* @param prefix the prefix
* @return a String Supplier
*/
Supplier<String> getSupplier(String prefix);
/**
* Get a Supplier that generates Strings with the provided prefix
* @return a String Supplier
*/
Supplier<String> getSupplier();
}
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trellisldp.spi;
import java.util.function.Supplier;
/**
* The IdentifierService provides a mechanism for creating new identifiers.
*
* @author acoburn
*/
public interface IdentifierService {
/**
* Get a Supplier that generates Strings with the provided prefix
* @param prefix the prefix
* @return a String Supplier
*/
Supplier<String> getSupplier(String prefix);
/**
* Get a Supplier that generates Strings with the provided prefix
* @return a String Supplier
*/
Supplier<String> getSupplier();
}
|
Update the PyPI version to 0.2.11
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='0.2.11',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='0.2.10',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
Check uniqueness of generated RandomStrings
|
package utils
import (
"math/rand"
"sync"
"testing"
"github.com/stretchr/testify/assert"
)
func TestRandomString(t *testing.T) {
rand.Seed(42)
s1 := RandomString(10)
s2 := RandomString(20)
rand.Seed(42)
s3 := RandomString(10)
s4 := RandomString(20)
assert.Len(t, s1, 10)
assert.Len(t, s2, 20)
assert.Len(t, s3, 10)
assert.Len(t, s4, 20)
assert.NotEqual(t, s1, s2)
assert.Equal(t, s1, s3)
assert.Equal(t, s2, s4)
}
func TestRandomStringConcurrentAccess(t *testing.T) {
n := 10000
var wg sync.WaitGroup
wg.Add(n)
ms := make(map[string]struct{})
var mu sync.Mutex
for i := 0; i < n; i++ {
go func() {
s := RandomString(10)
defer wg.Done()
mu.Lock()
defer mu.Unlock()
if _, ok := ms[s]; ok {
t.Fatal("should be unique strings")
}
var q struct{}
ms[s] = q
}()
}
wg.Wait()
}
|
package utils
import (
"math/rand"
"sync"
"testing"
"github.com/stretchr/testify/assert"
)
func TestRandomString(t *testing.T) {
rand.Seed(42)
s1 := RandomString(10)
s2 := RandomString(20)
rand.Seed(42)
s3 := RandomString(10)
s4 := RandomString(20)
assert.Len(t, s1, 10)
assert.Len(t, s2, 20)
assert.Len(t, s3, 10)
assert.Len(t, s4, 20)
assert.NotEqual(t, s1, s2)
assert.Equal(t, s1, s3)
assert.Equal(t, s2, s4)
}
func TestRandomStringConcurrentAccess(t *testing.T) {
n := 10000
var wg sync.WaitGroup
wg.Add(n)
for i := 0; i < n; i++ {
go func() {
RandomString(10)
wg.Done()
}()
}
wg.Wait()
}
|
Use is_null to check if a state isn't available.
|
<?php
/**
* @version $Id$
* @category Nooku
* @package Nooku_Server
* @subpackage Sections
* @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
defined('KOOWA') or die( 'Restricted access' ); ?>
<div id="filter" class="group">
<ul>
<li class="<?= is_null($state->published) ? 'active' : ''; ?> separator-right">
<a href="<?= @route('published=' ) ?>">
<?= @text('All') ?>
</a>
</li>
<li class="<?= $state->published === true ? 'active' : ''; ?>">
<a href="<?= @route($state->published === true ? 'published=' : 'published=1') ?>">
<?= @text('Published') ?>
</a>
</li>
<li class="<?= $state->published === false ? 'active' : ''; ?>">
<a href="<?= @route($state->published === false ? 'published=' : 'published=0' ) ?>">
<?= @text('Unpublished') ?>
</a>
</li>
</ul>
</div>
|
<?php
/**
* @version $Id$
* @category Nooku
* @package Nooku_Server
* @subpackage Sections
* @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
defined('KOOWA') or die( 'Restricted access' ); ?>
<div id="filter" class="group">
<ul>
<li class="<?= $state->published === null ? 'active' : ''; ?> separator-right">
<a href="<?= @route('published=' ) ?>">
<?= @text('All') ?>
</a>
</li>
<li class="<?= $state->published === true ? 'active' : ''; ?>">
<a href="<?= @route($state->published === true ? 'published=' : 'published=1') ?>">
<?= @text('Published') ?>
</a>
</li>
<li class="<?= $state->published === false ? 'active' : ''; ?>">
<a href="<?= @route($state->published === false ? 'published=' : 'published=0' ) ?>">
<?= @text('Unpublished') ?>
</a>
</li>
</ul>
</div>
|
Fix not nullable field for lr-uprns to be nullable
|
"""Create lr_uprn column with a GIN index
Revision ID: 45a35ac9bfe
Revises: 2bbd8de7dcb
Create Date: 2015-09-22 10:36:04.307515
"""
# revision identifiers, used by Alembic.
revision = '45a35ac9bfe'
down_revision = '2bbd8de7dcb'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('title_register_data', sa.Column('lr_uprns', postgresql.ARRAY(sa.String()), nullable=True))
op.create_index('idx_title_uprns', 'title_register_data', ['lr_uprns'], unique=False, postgresql_using='gin')
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_index('idx_title_uprns', table_name='title_register_data')
op.drop_column('title_register_data', 'lr_uprns')
### end Alembic commands ###
|
"""Create lr_uprn column with a GIN index
Revision ID: 45a35ac9bfe
Revises: 2bbd8de7dcb
Create Date: 2015-09-22 10:36:04.307515
"""
# revision identifiers, used by Alembic.
revision = '45a35ac9bfe'
down_revision = '2bbd8de7dcb'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('title_register_data', sa.Column('lr_uprns', postgresql.ARRAY(sa.String()), nullable=False))
op.create_index('idx_title_uprns', 'title_register_data', ['lr_uprns'], unique=False, postgresql_using='gin')
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_index('idx_title_uprns', table_name='title_register_data')
op.drop_column('title_register_data', 'lr_uprns')
### end Alembic commands ###
|
Fix misleading description in JSDoc
|
import HorizontalLayout from './layouts/HorizontalLayout';
import VerticalLayout from './layouts/VerticalLayout';
import SameHeightLayout from './layouts/SameHeightLayout';
import SameWidthLayout from './layouts/SameWidthLayout';
import SameSizeLayout from './layouts/SameSizeLayout';
import PackedLayout from './layouts/PackedLayout';
/**
* Calculates and returns an array of objects representing
* the next positions the FilterItems are supposed to assume.
* @param {String} Layout - name of helper method to be used
* @param {Object} Filterizr - instance
* @return {Object} layout to be used by Filterizr
*/
const Positions = (Layout, Filterizr) => {
switch(Layout) {
case 'horizontal':
return HorizontalLayout(Filterizr);
case 'vertical':
return VerticalLayout(Filterizr);
case 'sameHeight':
return SameHeightLayout(Filterizr);
case 'sameWidth':
return SameWidthLayout(Filterizr);
case 'sameSize':
return SameSizeLayout(Filterizr);
case 'packed':
return PackedLayout(Filterizr);
default:
return SameSizeLayout(Filterizr);
}
};
export default Positions;
|
import HorizontalLayout from './layouts/HorizontalLayout';
import VerticalLayout from './layouts/VerticalLayout';
import SameHeightLayout from './layouts/SameHeightLayout';
import SameWidthLayout from './layouts/SameWidthLayout';
import SameSizeLayout from './layouts/SameSizeLayout';
import PackedLayout from './layouts/PackedLayout';
/**
* Calculates and returns an array of objects representing
* the next positions the FilterItems are supposed to assume.
* @param {String} name of layout to decide the helper method to be used
* @param {Object} container is the FilterContainer
* @return {Object} layout to be used by Filterizr
*/
const Positions = (Layout, Filterizr) => {
switch(Layout) {
case 'horizontal':
return HorizontalLayout(Filterizr);
case 'vertical':
return VerticalLayout(Filterizr);
case 'sameHeight':
return SameHeightLayout(Filterizr);
case 'sameWidth':
return SameWidthLayout(Filterizr);
case 'sameSize':
return SameSizeLayout(Filterizr);
case 'packed':
return PackedLayout(Filterizr);
default:
return SameSizeLayout(Filterizr);
}
};
export default Positions;
|
Fix - Cambio nombre de tabla
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('usuarios', function (Blueprint $table) {
$table->increments('id');
$table->string('nombre');
$table->string('email')->unique();
$table->string('password');
$table->integer('tipo');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->integer('tipo');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
|
Remove comment about CDATA not being handled (since it is now).
|
//
// XMLIndent.java
//
import java.io.BufferedReader;
import java.io.FileReader;
import loci.formats.MetadataTools;
/** Indents XML to be more readable. */
public class XMLIndent {
public static void main(String[] args) throws Exception {
for (int i=0; i<args.length; i++) {
String f = args[i];
BufferedReader in = new BufferedReader(new FileReader(f));
StringBuffer sb = new StringBuffer();
while (true) {
String line = in.readLine();
if (line == null) break;
sb.append(line);
}
in.close();
System.out.println(MetadataTools.indentXML(sb.toString()));
}
}
}
|
//
// XMLIndent.java
//
import java.io.BufferedReader;
import java.io.FileReader;
import loci.formats.MetadataTools;
/** Indents XML to be more readable. Does not handle CDATA. */
public class XMLIndent {
public static void main(String[] args) throws Exception {
for (int i=0; i<args.length; i++) {
String f = args[i];
BufferedReader in = new BufferedReader(new FileReader(f));
StringBuffer sb = new StringBuffer();
while (true) {
String line = in.readLine();
if (line == null) break;
sb.append(line);
}
in.close();
System.out.println(MetadataTools.indentXML(sb.toString()));
}
}
}
|
Exit density inversion test if gsw is not available.
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Check density inversion QC test
"""
from numpy import ma
from cotede.qctests import density_inversion
def test():
try:
import gsw
except:
print('GSW package not available. Can\'t run density_inversion test.')
return
dummy_data = {
'PRES': ma.masked_array([0.0, 100, 5000]),
'TEMP': ma.masked_array([25.18, 19.73, 2.13]),
'PSAL': ma.masked_array([36.00, 34.74, 34.66])
}
cfg = {
'threshold': -0.03,
'flag_good': 1,
'flag_bad': 4
}
f, x = density_inversion(dummy_data, cfg, saveaux=True)
assert (f == [0,4,4]).all()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Check density inversion QC test
"""
from numpy import ma
from cotede.qctests import density_inversion
def test():
dummy_data = {
'PRES': ma.masked_array([0.0, 100, 5000]),
'TEMP': ma.masked_array([25.18, 19.73, 2.13]),
'PSAL': ma.masked_array([36.00, 34.74, 34.66])
}
cfg = {
'threshold': -0.03,
'flag_good': 1,
'flag_bad': 4
}
f, x = density_inversion(dummy_data, cfg, saveaux=True)
assert (f == [0,4,4]).all()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.